why to make a classes or attributes private? - oop

I would like to ask why I should make a class private or make an attribute private I protect it from what? I think that only attributes that will be available to users in the application to supply them or update them like (mail, password, or age) only should be private but any other attribute that he wouldn't asked to fill out could be public? Is it true?
public class student{
private String mail;
public String getMail() {return mail;}
public mail(String email) {mail=email;}
}

Generally, in any OOP-Supported language, the encapsulation is used to prevent the alteration of code (data) accidentally from the outside functions. By defining the class members' private, we can protect the data from accidental corruption.
The following are the benefits of encapsulation:
Protection of data from accidental corruption
Specification of the accessibility of each of the members of a class
to the code outside the class
Flexibility and extensibility of the code and reduction in complexity
Lower coupling between objects and hence improvement in code
maintainability
Although we can and should use it in all scales of applications that we are writing, it's not about small applications. It's about large-scale frameworks.
I personally believe you can get so much benefit by deep diving into the OOP concepts. I can specify some references, yet there are plenty of exciting topics to follow by googling OOP.
Stackoverflow: Encapsulation concept
Object-Oriented programming (C#)
w3Schools What is OOP?
You also can search YouTube, there are plenty of resources to get started with the OOP Concept.

Related

Confusion with understanding abstraction and encapsulation in OOP

I was learning JS and came across the term OOP. Then, as I was learning OOP and I found such concepts as abstraction and encapsulation. Moreover, as I was making researching on the difference between them, majority of articles says that both abstraction and encapsulation are concerned with data hiding which confused me very much. However, I made an inference that encapsulation is when we just put variables and functions that operate on them in OBJECT while abstraction is when we use access modifiers to restrict access to properties or functions in an object. Again, encapsulation is when we use capsule like object and put variables and functions in it to achieve organization and reusability. But abstraction is when we restrict access to variables and functions inside object. IS THAT TRUE?
Encapsulation means that you protect your data inside your class (or object) for the outer world and like you say you access the private or protected data via methods (functions) from the same object.
Abstraction is something totally different. Lets take an example.
Imagine that you want to use constraints on your form fields. For example you have a formfield 'email' which may not be empty and must contain an valid email.
So you want to add different kind of constraints to a large number of form fields all over your application.
All constraints must have two methods:
1) a method that tests the formfield data if it is valid
2) a method that delivers an error message if the data is not valid
Now before you write all those different constraint objects you could write one ABSTRACT parent class That includes those two methods but without any code:
(I use PHP)
abstract class Constraint
{
// Force Extending classes to define this methods
abstract protected function validate(string $data);
abstract protected function getErrorMessage();
}
Above class is abstract and cannot be used (instantiated) by its self. But you can write different constraint classes that inherit the above class:
class NotEmptyConstraint extends Constraint
{
// Mandatory overwritten methods:
protected function validate(string $data)
{
if(strlen($data) > 0 ) {
return true;
}
return false;
}
protected function getErrorMessage();
{
return 'This is a mandatory field';
}
}
Now all your constraint classes have the two mandatory methods which you can safely use without you need to know which exact constraint your dealing with.
Hope it helps..
OOP is dogma.
The author of this website wrote an article on abstraction and why it doesn't work: https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/
In other words, cell phones and LAN phones are not based on the same hardcoded abstraction of a phone. They are free to be their own classes. Barbara Liskov (SOLID) would argue each are subtypes. I strongly discourage tying your hands by creating such arbitrary hierarchical categorization schemes. This is not how real machines are engineered. Refer to fundamental principles of mechanical design, which dictate simplicity of design, meaning less components when feasible. A separate abstract class is a waste of time and distributes the design itself into two modules.
Encapsulation is the fallacious idea that objects own the data they operate on and, therefore, must control access to it. This notion is disproven by manufacturing's model for collaborative work, which is what my architecture is based on. A screwdriver doesn't own a screw simply because it changes its position. It simply has access to it.
OOP and encapsulation led to the distributed process code model. Objects e-mail work to one another like useless office employees who don't keep e-mail trails. If you've ever gotten e-mail from people asking for help who don't give you any information, then you understand my parody. In manufacturing, steps are documented and never communicate, which creates tremendous benefits. OOP is only enough know-how to write monolithic automated processes, not processes which stop on a dime, reverse, can insert or replace steps on the fly, and try steps again. OOP is a model for distributed manufacturing, whereas manufacturing is a model for organizing everyone who creates some product in the same space.

Recommended naming conventions for class-members: Stick to "STANDARD" or to "WORLD's best practices"?

So, the topic says it all.
It is simply about how to prefix/suffix/mark special types of class members.
As we can see in sap-standard, there is no real convention, either, because of no existing guidelines, or because of too much developers or because of outsourcing to other companies, which might have their own. Of course this might become an "opinion" based discussion, so please forgive. Nevertheless I would like to hear some pro's and cons, and in this case we are only dealing with ABAP-OO.
What would You recommend / have seen mostly used / is entitled as best practice for nearly all kind's of class-members, like these, for example:
public instance methods ( ALSO GETTERS / SETTERS )
protected instance methods
private instance methods
public static methods
protected static methods
private static methods
public instance attribute TABLES ( include kind of table if you want )
protected instance attribute TABLES
private instance attribute TABLES
-->All the above stuff also for structures and simple datatypes
static public constants
static private constants
interface-members
I am on my search for a most common denominator to extract those, which convention would fit best into abap-oo and also might be near to world's
conventions of other languages.
Obviously we can say, that hungarian notation can be said as being obsolete
(means, that an instance table does not really need a "T" and a structure does not really need a "S" somewhere in their prefizes. But, according to other languages, a private counter could be named
_instance_counter, what I personally prefer).
I am already surprised by all the sap-"standard" differences, now I would like to wait for some of You.
SAP-Press has actually published a set of ABAP development guidelines.
Official ABAP development guidelines
Highlights include:
Separation of concerns
Program type and attributes
Checks for accuracy
Code formatting and organization
Comments and alternative notation
Error handling
Data storage
Data types and objects
Calculations and accesses
Fields and tables
Modularization
Dynamic programming
We could argue best practise until we're blue in the face, but in the end all you really want is consistency.
When I start at a new client I always ask for THEIR development standards, whether I agree with their standards or not isn't really relevant. However, people are usually open for discussion if you present a reasoned argument.

Why to use access specifiers/Modifiers in Java?

I am learning Java and my question is Why to use access specifiers/Modifiers in Java? why we need to use Public, Private, Protected and Default access to class, Method or variables. If I am programmer then Obviously I know everything from program. If I am end user then I don't know what program is? Then from whom I am hiding details? Where the data hiding comes in picture? Please help me with some examples as point of programmer as well as as point of end user.
Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state.
A benefit of encapsulation is that it can reduce system complexity, and thus increases robustness, by allowing the developer to limit the inter-dependencies between software components. [1]
[1] http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
As point of software designer: practical and semantic reasons.
Variables describe an object instance's state. Protected variables are inherited. This is practical as classes in the inheritance chain can share structural similarities with each other. Non-inheriting variables remain private. Variables are only public when they are constants (public static final variables).
Methods describe an object's behaviour. The inheritance of protected and the usage of public methods is pretty much the same as with variables, except that while variables describe state, methods describe behaviour. One difference is the usage of package private methods, which approach is usually used inside frameworks.
If you do need a practical example, let's say the details of your FB password is stored as a private variable and your LoginID is stored as a protected variable in a FBDetails class...
Now anyone can inherit the FBDetails class to get your LoginID but apparently no one can access your password.

Object Oriented Programming and Encapsulation C++

Given the below sample class in C++, as you can see one can access all properties/methods for pic1 from the calling module. But only can access to pic2 via those declaration under public. Beside the just mentioned point, as a beginner to object oriented programming, I just wonder which method is preferred by the pro for real life implementation?
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System;
ref class myClass
{
PictureBox^ pic2;
public:
PictureBox^ pic1;
void setPic2() {pic2 = gcnew PictureBox;}
void addPic2ToControl(System::Windows::Forms::Form^ x) {x->Controls->Add(pic2);}
void setPic2Image(String^ filePath) {pic2->Image = dynamic_cast<Image^>(gcnew Bitmap(filePath));}
//more functions for to access pic2...
};
Encapsulation in C++ is usually accomplished by marking fields in your class as private or protected. However, you shouldn't rely on this totally as a way to keep stuff truly private per se-- if this is actually a security issue, for example, it won't help at all (remember friend functions.) It's more intended as a way to "divide-and-conquer" the program complexity and keep the code clean. This is an age-old challenge in computer programming, and encapsulation is just one of many valid techniques programmers have developed over the years.
How should encapsulation be used in your source code? Well a lot of people will insist, for example, that you should never have public variables in your classes, only public methods, and that public variables should be emulated using "getter/setter" functions. I don't necessarily agree with this, but I think it's fair to say that your classes should treat what it does as public information, and how it does it (and its internal state) as private information. This is just common sense anyway, even if you're not doing OOP. Among C programmers, a static (persistant) variable within a function is considered better practice than a variable with global scope if you can get away with it.
What is Encapsulation?
Encapsulation means binding the data and the methods that operate on that data in a single unit.
How do you implement Encapsulation?
By creating a type like structure or a class
Usually the data member variables inside a class are kept under private or protected access specifiers and the access to them is provided through public member functions. This guards honest mistakes of a programmer of accidentally modifying the member data if available publically. It provides a means of accessing and modifying the member data through explicit publically exposed function calls and hence more deliberate and less error prone.
Given the above, I believe, keeping pic2 private and providing access to it through member functions seems to be the appropriate way
One of the pros of restricting access to members through methods is that you now control the management of the variable at a central location (within the class itself). If later you decide to do some processing to pic2 before providing it to the caller you can do that in your access methods without the need to change it at multiple places
Later on if performance is a concern you can consider the option of inlining the methods

What are the different types of encapsulation?

What are the different types of encapsulation?
Am I right in thinking this basically refers to central OO concepts such as Abstraction, Polymorphism and Inheritance?
My understanding of encapsulation is that it is a method of hiding data / functionality, but I never really considered Polymorphism or Inheritance a form of encapsulation, although I can see how polymorphism could be considered encapsulation as it can hide the exact type of the object you are interacting with.
So, would you say that's about it, or am I missing some core concepts?
edit I just noticed in the comments someone mentioned it could refer to private / public methods, perhaps I'm thinking in to the question too much and expecting a more complicated answer than it really is?
You're thinking too much I think.
http://en.wikipedia.org/wiki/Information_hiding
Excerpt from this article:
Information hiding in computer science is the principle of hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed. The protection involves providing a stable interface which shields the remainder of the program from the implementation (the details that are most likely to change).
One common form of encapsulation is using properties to hide private data fields. An even more common form is the use of OO to encapsulate the complexity of software into well divisoned classes with roles and responsibilities. This is a key tennant of OO, as it moves from a monolithic procedural design style to a more structured style which strives to hide all irrelevant information except that which pertains to the particular task your working on.
It is my view and understanding that the term encapsulation (to encapsulate) is the art/science of capturing the essence of something for the purpose of display. In fact, by definition - to encapsulate is to package something or enclose it in another container. Therefore the term encapsulation would mean to take the essence of what you are attempting to achieve and packaging it in a useful form so that it can be reused as necessary.
So to interpret this, it would mean to package material in a form that would make it more useful later.
So really...interpret this as you see fit. I see it as taking a bunch of algorithms and utilities and creating a class structure that can be used as an API in other projects. This encapsulated code could be inherited and/or extended to make it useful for modified purposes without changing the underlying essence of the API.
Therefore, abstraction, polymorphism and inheritance aren't forms of encapsulation, but forms of extending and modifying encapsulated code.
Different forms of encapsulation would mean the modifiers on properties, methods, fields and classes - that is public, private, static, virtual (in C#). Everything else (i.e. overloads, overrides, shadows) is a modification or an extension to that encapsulation.
You may consider the modified code an encapsulation which could then be further inherited/abstracted/extended, but the package which is to be extended is the encapsulated product.
Encapsulation is defined by the International Organisation for Standardization's International Standard: "Information technology – Open Distributed Processing," ISO/IEC 10746, 1998.
It's defined in terms of more primitive definitions:
Entity: Any concrete or abstract thing of interest.
Object: A model of an entity. An object is characterised by its behaviour and,
dually, by its state.
Behaviour (of an object): A collection of actions with a set of constraints on
when they may occur.
Interface: An abstraction of the behaviour of an object that consists of a
subset of the interactions of that object together with a set of constraints
on when they may occur.
Encapsulation: the property that the information contained in an object is
accessible only through interactions at the interfaces supported by the
object.
The ISO does not define different types of encapsulation.
Other posts have mentioned information hiding. The ISO does not define encapsulation explicitly in terms of information hiding, though it does seem implicit, see "Encapsulation theory fundamentals," at http://www.edmundkirwan.com/pub/
Ed.
Encapsulation is more than simply information hiding. That is one aspect of it. It has to do with the interface to a module. An interface provides two very important functions: encapsulation and abstraction.
Abstraction is when a client of a module does not need to know more than what is in the interface.
and
Encapsulation is when a client of a module isn't able to know more than what is in the interface.
(Both definitions from Using UML by Perdita Stevens)
Since encapsulation simply refers to "information hiding" then I would imagine that a lot of things can be categorized as encapsulation. However I tend to think of encapsulation as "implementation hiding", in other words it is a tool that I use to create loose coupling between anything I write and anything client of what I have written.
So I tend to believe, pragmatically, that encapsulation is any paradigm or best-practice that allows me to present a clean, solid interface to any client.
Generally the usage of the word is pretty close to what it says. You encapsulate something when you contain it, and don't let any of the deals loose. The best way to think about it is that you are taking something and putting it into a black-box where no one can see the details anymore. The box hides everything, providing some other disassociated interface in its place.
Information hiding is just one aspect of encapsulation, since along with the data you can also hide any of the details of the code itself. The purpose of encapsulating a part of your system is to draw that bit of complexity away from the whole, thus making it easier to understand the separate details (on both sides). More?
Paul.
"Candidate Definitions for Encapsulation:
Physically grouping together related operations or things.
GateKeeper of state or data.
Hiding implementation."
Sourced from: Encapsulation Definition
There are two parts/ways to achieve Encapsulation:
First, encapsulation is a technique that packages related data and behaviors into a single unit, i.e, Physical grouping of operations(behaviors)
E.g.:-
class Person {
String name;
int age;
void talk() {
}
void think() {
}
void work() {
}
void play() {
}
}
Second, encapsulation is a technique for protecting data from misuse by the outside world, which is referred as ‘information hiding’ or ‘data hiding’.
E.g.:-
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public String getAge() {
return age;
}
}
Sourced from: What is Encapsulation in Java - the WHAT, WHY and HOW, spoiler author cites Interface as an example, which is not true. Interface are for Abstraction