Can we not use the term object while defining encapsulation in OOP? - oop

I have read a definition of encapsulation which stated that "Encapsulation is the wrapping of data and functions into a single unit called class" .My question is that can we not use the term object instead of class in the definition because at last objects are created using the classes and objects only encapsulate data and functions inside them?

I don't have a problem with replacing "class" with "object" in the example sentence. It remains valid in class-based OOP languages while being more appropriate for prototype-based OOP languages. Classes are just a type system for OOP after all and not as fundamentally essential as encapsulation is.
I would, however, want to improve that sentence to make it clear that data and functions aren't "wrapped" in the same way. Data must be hidden and only be accessible to methods of an object.

The more important question to consider is why encapsulation is essential to true oop. Objects are to hide their attributes and inner workings, and present an interface for use by other objects. oop begins to break down when this encapsulation is broken. Code becomes harder to maintain if everyone has their hands on everyone else’s data. Consider setters and getters and all the ways we tend to break encapsulation. True object thinking is not primarily about classes and polymorphism. It is definitely about encapsulation and interfacing between objects.

Not every class has objects.
We can have static classes that have no objects.
If the definition were changed to use the word "object", these classes would not be covered. With "class", both static and non static classes are covered.
Even if a class is not static, it could have static data and functionality, again the term class is more appropriate.
Other classes may be abstract and therefore have no objects, they may still provide some encapsulation.
Template classes could also be though of as being capable of encapsulation even though there will be no objects of the template itself - only objects of "concrete" classes with specific types provided for the templates type parameters.
Also, the word "single" becomes a bit confusing if we apply it to objects since we can have multiple object of a class.
Cid's comment offers an additional reason for "class" over "object".

I assume you have a rough idea of what encapsulation is? So you are asking why couldn't the definition bee rephrased to
Encapsulation is the wrapping of data and functions into a single unit called an object.
Because encapsulation has nothing to do with objects at all. You can create some class called Car and it has some fields like engine, seats, steeringWheel and some methods applyBrakes, openWindow as well as some private members. Now you can say that the class encapsulates the inner workings of a car into a single unit - the Car class.
See? I didn't say anything about objects. Car objects are really just a bunch of references in memory pointing to other Engine, Seat and SteeringWheel objects.

In my opinion, "data" is the problematic term. Classes encapsulate attributes and methods that work on these attributes together. "data" suggests actual data and not meta data. That is probably why you thought of objects instead of classes.
Other than that, I would not replace class with object here, because it leaves out the important feature that all objects from one class have the same methods. With object, one could interpret that each object has its own set of functions.

Related

Is it correct to say that objects can display polymorphism

https://www.tutorialspoint.com/java/java_polymorphism.htm#:~:text=Polymorphism%20is%20the%20ability%20of,is%20considered%20to%20be%20polymorphic.
As per the link above, in which they say:
Polymorphism is the ability of an object to take on many forms.
I'm having trouble figuring out whether to take this literally or not.
From my knowledge of polymorphism, classes are polymorphic when they can have multiple children, each implementing a parent class method in a different way.
A function can be polymorphic as we can overload and override them so functions can display different behaviors.
I was told and taught that another form of polymorphism applies to objects that inherit from multiple parent classes.
In C++ for example an object may behave differently depending on its reference type if its methods aren't virtual.
Another example that comes to mind is in Java with multiple interfaces, I can look at an object as different types causing different expected behaviors.
Are these examples really considered polymorphism at play or is this just inheritance and Polymorphism best defines the first two examples (classes and methods)
Thanks
The literal meaning of the word "polymorphism" is what the tutorial says. However it makes very little sense to use the literal meaning of a technical term. In OOP, "polymorphism" means subtyping. There are other ways the term "polymorphism" is used in programming (ad-hoc and parametric polymorphism) but they are not related to OOP specifically.
"Polymorphic object" is not a standard term across the OOP literature. It has a very specific meaning in C++, and it's not "an object with several base classes". It is simply an object with at least one virtual function. From the OOP perspective, a C++ "polymorphic object" is just an object.
Deriving from more than one base classes is called multiple inheritance. I have never heard anyone using the term "polymorphism" for this.

Why wouldn't I make every eligable Kotlin class a data class?

I'm of course excluding any reasons that involve violating the rules for what can be a data class. So if you know you won't need to inherit from it for example (although it's my understanding that rule is going away in Kotlin 1.1).
Are there any disadvantages to making a class a data class?
Why don't all eligible classes provide the functionality of a data class as long as they remain eligible? This should all be detectable by the compiler without needing a special keyword. Of course the answer to this might be obvious depending on the answer to question 1.
Is there any reason for me not to mark all of my eligible classes as data classes?
data modifier makes Kotlin generate common methods like toString, hashCode, equals for the most commons (%80) scenarios based on the primary constructor.
This shows 3 reasons why only few classes should be data:
Most non-data classes have a mix of properties defined in the primary constructor and in the body of the class. Also the primary constructor often has parameter that are not fields (but help initialise more complex fields in the body). In other words, data has very restrictive requirements which are rarely met by regular classes.
In addition to point 1, making a class data may hurt its extensibility. Even if the layout of the class in question conforms to the rules of data classes, later someone may want to add another property in the body of the class. In that case he will have to manually override hashCode because it may be used somewhere.
Marking a class data sends a message to the one who reads the code that you intend to use this class as a data career. Marking other classes will be misleading.
because of one the fundament pinciple of OO programming: encapsulation.
by design we deliberately limit ways in which other code can interact with out modules. this gives us maintainability (more powerful refactoring) and readablity

OOP Encapsulation Concept

In an interview I have been asked this. Is this is an example of Encapsulation?
class abc
{
}
I tried seeking for the answer from multiple books but couldn't find it.
We would start talking about encapsulation when the following would happen:
The class will have members and methods and therefore becomes a collection of data and methods.
In this class we start hiding the data within, and make it available only through public methods
This technique is known as encapsulation because it seals the data (and internal methods) safely inside the "capsule" of the class, where it can be accessed only by trusted users (i.e., by the methods of the class).
Until no methods and members, I don't think we are talking about encapsulation.
If the class is empty, there is no information to be encapsulated, so no encapsulation here.
No its not,
Encapsulation refers to the act of binding together data members and functions which manipulate them into a single entity.
Mostly they are bound into a class.
But the example here has to data members and functions to encapsulate, so it's not an Encapsulation

Correct OOP design without getters?

I recently read that getters/setters are evil and I have to say it makes sense, yet when I started learning OOP one of the first things I learned was "Encapsulate your fields" so I learned to create class give it some fields, create getters, setters for them and create constructor where I initialize these fields. And every time some other class needs to manipulate this object (or for instance display it) I pass it the object and it manipulate it using getters/setters. I can see problems with this approach.
But how to do it right? For instance displaying/rendering object that is "data" class - let's say Person, that has name and date of birth. Should the class have method for displaying the object where some Renderer would be passed as an argument? Wouldn't that violate principle that class should have only one purpose (in this case store state) so it should not care about presentation of this object.
Can you suggest some good resources where best practices in OOP design are presented? I'm planning to start a project in my spare time and I want it to be my learning project in correct OOP design..
Allen Holub made a big splash with "Why getter and setter methods are evil" back in 2003.
It's great that you've found and read the article. I admire anybody who's learning and thinking critically about what they're doing.
But take Mr. Holub with a grain of salt.
This is one view that got a lot of attention for its extreme position and the use of the word "evil", but it hasn't set the world on fire or been generally accepted as dogma.
Look at C#: they actually added syntactic sugar to the language to make get/set operations easier to write. Either this confirms someone's view of Microsoft as an evil empire or contradicts Mr. Holub's statement.
The fact is that people write objects so that clients can manipulate state. It doesn't mean that every object written that way is wrong, evil, or unworkable.
The extreme view is not practical.
"Encapsulate your fields" so I learned to create class give it some fields, create getters, setters
Python folks do not do this. Yet, they are still doing OO programming. Clearly, fussy getters and setters aren't essential.
They're common, because of limitations in C++ and Java. But they don't seem to be essential.
Python folks use properties sometimes to create a getter and setter functions that look like a simple attribute.
The point is that "Encapsulation" is a Design strategy. It has little or nothing to do with the implementation. You can have all public attributes, and still a nicely encapsulated design.
Also note that many people worry about "someone else" who "violates" the design by directly accessing attributes. I suppose this could happen, but then the class would stop working correctly.
In C++ (and Java) where you cannot see the source, it can be hard to understand the interface, so you need lots of hints. private methods, explicit getters and setters, etc.
In Python, where you can see all the source, it's trivial to understand the interface. We don't need to provide so many hints. As we say "Use the source, Luke" and "We're all adults here." We're all able to see the source, we don't need to be fussy about piling on getters and setters to provide yet more hints as to how the API works.
For instance displaying/rendering object that is "data" class - let's say Person, that has name and date of birth. Should the class have method for displaying the object where some Renderer would be passed as an argument?
Good idea.
Wouldn't that violate principle that class should have only one purpose (in this case store state) so it should not care about presentation of this object.
That's why the Render object is separate. Your design is quite nice.
No reason why a Person object can't call a general-purpose renderer and still have a narrow set of responsibilities. After all the Person object is responsible for the attributes, and passing those attributes to a Renderer is well within it's responsibilities.
If it's truly a problem (and it can be in some applications), you can introduce Helper classes. So the PersonRenderer class does Rendering of Person data. That way a change to Person also requires changes to PersonRenderer -- and nothing else. This is the Data Access Object design pattern.
Some folks will make the Render an internal class, contained within Person, so it's Person.PersonRenderer to enforce some more serious containment.
If you have getters and setters, you don't have encapsulation. And they are not necessary. Consider the std::string class. This has quite a complicated internal representation, yet has no getters or setters, and only one element of the representation is (probably) exposed simply by returning its value (i.e. size()). That's the kind of thing you should be aiming for.
The basic concept of why they are considered to be evil is, that a class/object should export function and not state. The state of an object is made of its members. Getters and Setters let external users read/modify the state of an object without using any function.
Hence the idea, that except for DataTransferObjects for which you might have Getters and a constructor for setting the state, the members of an objects should only be modified by calling a functionality of an object.
Why do you think getters are evil? See a post with answers proving the opposite:
Purpose of private members in a class
IMHO it contains a lot of what can rightfully be called "OOP best practices".
Update: OK, reading the article you are referring to, I understand more clearly what the issue is. And it's a whole different story from what the provocative title of the article suggests. I haven't yet read the full article, but AFAIU the basic point is that one should not unnecessarily publish class fields via mindlessly added (or generated) getters and setters. And with this point I fully agree.
By designing carefully and focusing on what you must do rather than how
you'll do it, you eliminate the vast majority of getter/setter methods in
your program. Don't ask for the information you need to do the work;
ask the object that has the information to do the work for you.
So far so good. However, I don't agree that providing a getter like this
int getSomeField();
inherently compromises your class design. Well it does, if you haven't designed your class interface well. Then, of course, it might happen that you realize too late that the field should be a long rather than an int, and changing it would break 1000 places in client code. IMHO in such case the designer is to blame, not the poor getter.
In some languages, like C++, there's the concept of friend. Using this concept you can make implementation details of a class visible to only a subset of other classes (or even functions). When you use Get/Set indiscriminately you give everyone access to everything.
When used sparingly friend is an excellent way of increasing encapsulation.
Assume you have many entity classes in your designs, and suppose they have a base class like Data. Adding different getter and setter methods for concrete implementations will pollute the client code that uses these entities like lots of dynamic_casts, to call required getter and setter methods.
Therefore, getter and setter methods may remain where they are, but you should protected client code. My recommendation would be to apply Visitor pattern or data collector for these cases.
In other words, ask yourself why do I need these accessor methods, how do I manipulate these entities? And then apply these manipulations in Visitor classes to keep client code clean, also extend the functionality of entity classes without polluting their code.
In the following paper concerning endotesting you'll find a pattern to avoid getters (in some circumstances) using what the author calls 'smart handlers'. It has a lot in common with how Holub approaches avoiding some getters.
http://www.mockobjects.com/files/endotesting.pdf
Anything that is public is part of the API of the class. Changing these parts may break other stuff, relying on that. A public field, that is not only connected with an API, but with internal representation, can be risky. Example: You save data in a field as an array. This array is public, so the data can be changed from other classes. Later you decide to switch to a generic List. Code that use this field as an array is broken.

what is a member vs. a property

A friend who is new to OO programming asked me the difference between a Member and Property, and I was ashamed to admit that I couldn't give him a good answer. Since properties can also be objects themselves, I was left with a general description and list of exceptions.
Can somebody please lay out a good definition of when to consider something a member vs. a property? Maybe I'm bastardizing the concept, or is it just that a member is just the internal name I use, and the property is what's exposed to other objects?
I don't think that not knowing the answer to this question has affected the quality of my programming, and it's just a semantics point, but it still bothers me that I can't explain it to him.
A property is one kind of member. Others might be constructors, methods, fields, nested types, conversions, indexers etc - depending on the language/platform, of course. A lot of the time the exact meaning of terminology depends on the context.
To give a C#-specific definition, from the C# 3.0 spec, section 1.6.1:
The following table provides an overview of the kinds of members a class can contain.
(Rows for...)
Constants
Fields
Methods
Properties
Indexers
Events
Operators
Constructors
Destructors
Types
Note that that's members of a class. Different "things" have different kinds of members - in C#, an interface can't have a field as a member, for example.
Neither of the two terms has any defined meaning whatsoever in Object-Oriented Programming or Object-Oriented Design. Nor do they have any defined meaning in the overwhelming majority of programming languages.
Only a very small number of programming languages have a concept called property or member, and even fewer have both.
Some examples of languages that have either one of the two are C++ (which has members), ECMAScript (which has properties) and C# (which has both). However, these terms don't necessarily denote the same concepts in different programming languages. For example, the term "member" means roughly the same thing in C++ and C#, but the term "property" means completely different things in ECMAScript and C#. In fact, the term "property" in ECMAScript denotes roughly the same concept (ie. means roughly the same thing) as the term "member" in C++ and C#.
All this is just to say that those two terms mean exactly what the relevant specification for the programming language says they mean, no more and no less. (Insert gratuitous Lewis Carroll quote here.)
Properties is one kind of members.
In C#, for example, a class can have the following members:
Constructors
Destructors
Constants
Fields
Methods
Properties
Indexers
Operators
Events
Delegates
Classes
Interfaces
Structs
MSDN: C#: class
Members are just objects or primitive types belonging to a class.
Properties give you more power than members. It's like a simplified way to create getters and setters letting you make, for instance, public getters and private setters; and put whatever logic you want in the way it will be read or written to. They can be used as a way to expose members, being possible to change the reading and writing policy later more easily.
This applies to C#. Not sure if this is true for the other languages though.
A member (variable) is just some part of the object. A property is (I'll qualify this with "usually" - I'm not sure that it's a technically clear word that has unambiguous meaning across multiple languages) is a publicly accessible aspect of the object, e.g. through getter and setter methods.
So while (almost always) a property is a reacheable member variable, you can have a property that's not really part of the object state (not that this is good design):
public class Foo {
public String getJunk()
{ return "Junk";}
public void setJunk(String ignore){;}
}
}
Both properties and methods are members of an object. A property describes some aspect of the object while a method accesses or uses the owning object.
An example in pseudo-code:
Object Ball
Property color(some Value)
Method bounce(subroutine describing the movement of the Ball)
Where the ball is defined and given a color(property) while the method bounce is a subroutine that describes the how the ball will react on hitting another object.
Not all languages have properties, i.e. Java only has fields that must be accessed by getters and setters.
Properties are a way to expose fields, where fields are the actual variables. For example (C#):
class Foo {
private int field;
public int Property {
get { return field; }
set { field = value; }
}
}
from PHP manual:
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization.
Member is a generic term (likely originated in C++, but also defined in Java) used to denote a component of a class. Property is a broad concept used to denote a particular characteristic of a class which, once the class is instantiated, will help define the object's state.
The following passages, extracted from "Object-Oriented Analysis and Design" by Grady Booch help clarify the subject. Firstly, it's important to understand the concepts of state and behaviour:
The state of an object encompasses all of the (usually static) properties of the object plus the current (usually dynamic) values of each of these properties. By properties, we mean the totality of the object's attributes and relationships with other objects.
Behaviour is how an object acts and reacts, in terms of its state changes and message passing (methods); the outwardly visible and testable activity of an object.
So, the behaviour of an object depends on the available operations and its state (properties and their current values). Note that OOP is quite generic regarding certain nomenclature, as it varies wildly from language to language:
The terms field (Object Pascal), instance variable (Smalltalk), member object (C++), and slot (CLOS) are interchangeable, meaning a repository for part of the state of an object. Collectively, they constitute the object's structure.
An operation upon an object, defined as part of the declaration of a class. The terms message (Smalltalk), method (many OO languages), member function (C++), and operation are usually interchangeable.
But the notation introduced by the author is precise:
An attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class. Using the language-independent syntax, an attribute may have a name, a class, or both, and optionally a default expression: A:C=E.
An operation denotes some service provided by the class. Operations (...) are distinguished from attributes by appending parentheses or by providing the operation's complete signature, composed of return class, name, and formal arguments (if any): R N(Arguments)
In summary, you can think of members as everything that composes the class, and properties as the members (attributes) that collectively define the structure of the class, plus its relationships to other classes. When the class is instantiated, values are assigned to its properties in order to define the object's state.
Cheers