confusion about abstraction and encapsulation - encapsulation

Can anyone tell me with examples abstraction and encapsulation and difference between them?

They're certainly related, but subtly different.
Abstraction is the treating of concrete classes (types of objects) as abstractions. By that, I mean you don't have classes representing square, circle, rectangle and so on. All these can be abstracted to a common ancestor, shape. The abstraction is useful because there are certain operations that you can perform on any shape, such as drawing, setting the origin, setting the size and so on.
Encapsulation, on the other hand, is information hiding. It's the act of exposing only enough information to enable you to do what needs to be done.
A classic example there is a telephone book. You don't expose the fact that you're using a hash table or a couple of arrays or whatever bizarre structure you've chosen to represent it. Instead you provide only the operations that you expect to carry out on an object.
Encapsulation lets you change the internals of a class without having to worry about effects on the client. So maybe an array is fine when your phone book has twenty entries in it but, when you get so popular that people are clamouring to be added, you may want to switch to using hash tables or a database.
With encapsulation, this is a far more painless process since, as long as you maintain the public face of your class, you can change what you want. If you had "published" your internals, people may have come to depend on that, to the point where that dependency would break their code when you changed it. A good rule is to only "publish" what you expect to never change.
Encapsulation eases the task of abstraction since the internal details of an class are hidden from view.

Encapsulation:
Encapsulation is essentially the hiding of implementation details, separating data and behavior, and providing simple interfaces to complex black box entities.
Example: you press the toast lever down on your toaster, it activates the heating coils & timer, and your toast pops up ready to eat in a minute. The details of making toast are encapsulated into a simple interface of pushing the lever down. In 20 years, you might buy a nuclear toaster, but the same encapsulation of functionality will allow you to use it in the manner you're accustomed to now.
Abstraction:
Definition 1
In the general sense, the interface provided by an encapsulation is essentially an abstraction for its more complex innards. With this definition, the distinction is blurred.
Example: the same toaster from above can be said to be abstracting the complex action of toasting bread into a simple operation of pushing a lever.
Definition 2
Another more distinct meaning is the use of a hierarchy of types or other generality to allow entities to be used interchangeably in their more generic forms. Encapsulation often enables this type of abstraction.
Example: your toaster can toast slices of wheat bread, rye bread, raising bread, or even bagels. The only requirement is that they be sliced and limited to some common set of dimensions. Here we might say that your toaster can toast anything "Toastable". This is an abstraction that encompasses all of these items.
Grady Booch says...
(from http://en.wikipedia.org/wiki/Information_hiding)
In his influential book on object-oriented design, Grady Booch defined encapsulation as "the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation."[2] This formulation is cited by a number of books as an authoritative definition of encapsulation.

Related

What's the difference between using the Visitor pattern and a separate class?

I would like to know what is the difference between the Visitor pattern and using a static method to execute code in separation.
Let's take a look at an example where I might call the Visitor pattern:
new AnalyticsVisitor.accept(myClass);
and this when called in from myClass for example, would move the work into a visitor to execute. It would even garbage collect faster if it's memory intensive.
Now lets take a look at using a simple method to achieve more or less the same thing:
new AnalyticsManager.execute(myClass);
Have I achieved the same thing?
I have code separation.
I can apply this to several data structures
I can add info to legacy code without changing it.
So why use the Visitor pattern instead of just a class (unless for double dispatch)?
This question is still a little confused. I suspect you haven't understood the goal of the Visitor pattern.
As discussed here the visitor pattern is useful when you have complex data structure (such as a parse tree) that is relatively stable (in terms of development), but you want to be able to keep adding new operations on all of its elements. This is clumsy with standard OO techniques.
The technology the visitor pattern is based on is double-dispatch, so when you say "Why use the Visitor pattern unless for double-dispatch?" you are effectively saying "Why use the visitor pattern?"
Your example code only includes the client, so it isn't clear what your new technique actually offers.
The supplied code appears to be backwards for a real visitor pattern. It should be:
my_datastructure.accept(analytics_visitor);
where analytics_visitor inherits from MyDataStructureVisitor, and supplies individual methods for each of the element types that the data structure can hold.
As for the achievements:
"Code separation" is a vague term. The visitor pattern allows the data structure to be defined without all the the operations (putative methods) to be defined. Instead, they can be defined separately - with a cost of poorer encapsulation.)
It isn't clear what it means to apply a visitor pattern to several data structures. Each visitor class is associated with one data structure.
The goal isn't to add 'info' to legacy code. It is to add operations to legacy code.

Real name of the "container_of" pattern

E.g. in Linux driver development one can find the container_of macro. In essence it is the reverse operator to an ->, yielding the pointer to the containing structure if you got a pointer to a member.
Besides from Greg Kroah's blog I found this pattern in the list and hash implementation of Pintos.
The real name of this pattern is "container_of()." Attempting to fit this C-ism into a Java or C++ design pattern taxonomy is futile. The point is not to chain responsibility, or to designate or delegate anything. If you must think in these terms then it's a "messy generalized inheritance." If you don't have to think in these terms then it's a lot less messy.
I'd say it's a not-very featureful Chain Of Responsibility. The only reason you need a pointer back to your parent container structure is to place parent container functionality within reach of the contained elements. As such, it could be seen as an implementation detail required to allow a request to trickle up the "chain" until it gets handled at the correct "level".
With a container / contained relationship, that "correct" level is just one level up, and the trickle up doesn't go through enough levels (since there is only one level) to generate much interest as an ideal example of the pattern. Still, the general ideas behind Chain of Responsibility still hold; a request is made at a point in the chain which cannot handle it, and is handled at a different point in the change which can.
With a small non-generic container / contained relationship, the coupling of this two link chain can get quite tight. For example, your examples lack of a generic "command" handling framework (since the command language set is small), and such a framework generally requires (for type safety) a Command / Message Object. That's a lot of overhead, for a list that just wants to let it's elements directly notify at the element level that they want to be removed from the list.
And yes, there is a C2 pattern's page for it... If you agree with my reasoning.

Game player object design

I'm supporting a server for an online card game and while thinking about refactoring it into a better state I have found myself unable to decide what is a proper object model for my needs.
I have a Player class which has a lot of attributes. The first problem is just that - the class is too big. The second problem is that I don't know how to refactor it. I will list some of the attributes and issues with these.
Some attributes are very tightly bound to a player: nick, email, last login &c. These, I suppose, are to be kept directly in the player class and in the same table in the DB.
Now, some attributes are a little more difficult, like money and gold amount. The problem with these is that they are historically stored in a different table, there might be some more currencies later on and that they MUST be synched into the database at their own pace.
Third category of attributes are loosely coupled to the player, like status string, experience, achievements, statistics &c. These are stored in different tables in the DB and MUST be stored, retrieved, cached and synchronized at their own pace.
Note that one of the big problems here is that we have to implement relatively complex database synchronization schemes because we have a lot of online players and our game is soft-realtime and we have to make load on the DB as low as possible.
My questions are:
How to determine which attributes to store within a player class and which not to? Say, experience, nickname, money amount?
When one has some attributes that may be grouped together like (strength, agility, endurance, &c.) and (handItem, headItem, feetItem, weapon) when they should be grouped and when not?
What to do with complex database synchronization schemes? Make a separate model for each attribute that needs to be synched independently or make some DataManager classes to take them apart and work with them?
What to do with the need for a class to have several different "data representations" for external consumers? Like XML, Json, another XML for some external service, human-readable string, &c.
I'm sorry if my questions are bogus, I'm not really good at OOP design, I'm more an FP guy. And my English is not very good =).
There is no "limit" to what you can store in a player class. As long as it is concerning him and him only, it should be in his class. But one thing you should consider is to make several player classes. The idea is : if you don't need is, don't query it. You may have PlayerView_Small, PlayerBuying, PlayerFighting, PlayerSettings (depending on your game, they may not be fulfilling the exact same purpose)... This way for each "need" of info on a player, you only load the player data you need, and can handle it properly. Also, you may use inheritance if some class is only a more detailed version of the other.
If you are talking about the class, it may be in a sub-class PlayerAttributes of which an instance is contained into PlayerFighting and PlayerView_Detailed. In the database, it might be interesting to store it as a string (conveniently outputted by our class, and accepted in constructor), to avoid having too much fields, but you will lose the sorting ability. That's probably not a problem in our case, but might be in some others.
Blank for now, I don't understand where there is synchronization, will edit when informed.
In your PlayerViewDetailInfo(or in your PlayerAllData depending what you need), you place some methods such as ToXmlClient1(), ToJson(), ToHumanReadableString() (although that might be a bit confusing to the eye, you should consider HTML^^). The class having the method should be the class with the least (but sufficient to provide the answer) data. When requested, you load the Player... which has the method giving the correct output, and you write it directly in the response.

Using Flyweight Pattern in database-driven application

Can anyone please give me any example of situation in a database-driven application where I should use Flyweight pattern?
How can I know that, I should use flyweight pattern at a point in my application?
I have learned flyweight pattern. But not able to understand an appropriate place in my database-driven business applications to use it.
Except for a very specialized database application, the Flyweight might be used by your application, but probably not for any class that represents an entity which is persisted in your database. Flyweight is used when there otherwise might be a need for so many instantiations of a class that if you instantiated one every discrete time you needed it performance would suffer. So instead, you instantiate a much smaller number of them and reuse them for each required instance by just changing data values for each use. This would be useful in a situation where, for example, you might have to instantiate thousands of such classes each second, which is generally not the case for entities persisted in a database.
You should apply any pattern when it naturally suggests itself as a solution to a concrete problem - not go looking for places in your application where you can apply a given pattern.
Flyweight's purpose is to address memory issues, so it only makes sense to apply it after you have profiled an application and determined that you have a ton of identical instances.
Colors and Brushes from the Base Class Library come to mind as examples.
Since a very important part of Flyweight is that the shared implementation is immutable, good candidates in a data-driven application would be what Domain-Driven Design refers to as Value Objects - but it only becomes relevant if you have a lot of identical values.
[Not a DB guy so this is my best guess]
The real bonus to the flyweight pattern is that you can reuse data if you need to; Another example is word processing where ideally you would have an object per "character" in your document, but that wuld eat up way too much memory so the flyweight memory lets you only store one of each unique value that you need.
A second (and perhaps simplest) way to look at it is like object pooling, only you're pooling on a "per-field" level as opposed to a "per-object" level.
In fact, now that i think about it, it's not unlike using a (comparatively small) chunk of memory in c(++) so store some raw data which you do pointer manipulation to get stuff out of.
[See this wikpedia article].

Abstraction VS Information Hiding VS Encapsulation

Can you tell me what is the difference between abstraction and information hiding in software development?
I am confused. Abstraction hides detail implementation and
information hiding abstracts whole details of something.
Update: I found a good answer for these three concepts. See the separate answer below for several citations taken from there.
Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition):
Abstraction and encapsulation are complementary concepts: abstraction
focuses on the observable behavior of an object... encapsulation
focuses upon the implementation that gives rise to this behavior...
encapsulation is most often achieved through information hiding, which
is the process of hiding all of the secrets of object that do not
contribute to its essential characteristics.
In other words: abstraction = the object externally; encapsulation (achieved through information hiding) = the object internally,
Example:
In the .NET Framework, the System.Text.StringBuilder class provides an abstraction over a string buffer. This buffer abstraction lets you work with the buffer without regard for its implementation. Thus, you're able to append strings to the buffer without regard for how the StringBuilder internally keeps track of things such the pointer to the buffer and managing memory when the buffer gets full (which it does with encapsulation via information hiding).
rp
The OP updated his question with several citations that he had found, namely in an article by Edward V. Berard titled, "Abstraction, Encapsulation, and Information Hiding". I am re-posting a slightly expanded and reformatted version of the OP's update, since it should be an answer in its own right.
(All citations are taken from the article mentioned above.)
Abstraction:
"One point of confusion regarding abstraction is its use as both process and an entity. Abstraction, as a process, denotes the extracting of the essential details about an item, or a group of items, while ignoring the inessential details. Abstraction, as an entity, denotes a model, a view, or some other focused representation for an actual item."
Information Hiding:
"Its interface or definition was chosen to reveal as little as possible about its inner workings." — [Parnas, 1972b]
"Abstraction can be […] used as a technique for identifying which information should be hidden."
"Confusion can occur when people fail to distinguish between the hiding of information, and a technique (e.g., abstraction) that is used to help identify which information is to be hidden."
Encapsulation:
"It […] refers to building a capsule, in the case a conceptual barrier, around some collection of things." — [Wirfs-Brock et al, 1990]
"As a process, encapsulation means the act of enclosing one or more items within a […] container. Encapsulation, as an entity, refers to a package or an enclosure that holds (contains, encloses) one or more items."
"If encapsulation was 'the same thing as information hiding,' then one might make the argument that 'everything that was encapsulated was also hidden.' This is obviously not true."
Conclusion:
"Abstraction, information hiding, and encapsulation are very different, but highly-related, concepts. One could argue that abstraction is a technique that help us identify which specific information should be visible, and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible."
Abstraction is hiding the implementation details by providing a layer over the basic functionality.
Information Hiding is hiding the data which is being affected by that implementation. Use of private and public comes under this. For example, hiding the variables of the classes.
Encapsulation is just putting all similar data and functions into a group e.g Class in programming; Packet in networking.
Through the use of Classes, we implement all three concepts - Abstraction, Information Hiding and Encapsulation
Please don't complicate simple concepts.
Encapsulation : Wrapping up of data and methods into a single unit is Encapsulation (e.g. Class)
Abstraction : It is an act of representing only the essential things without including background details. (e.g. Interface)
FOR EXAMPLES AND MORE INFO GOTO :
http://thecodekey.com/C_VB_Codes/Encapsulation.aspx
http://thecodekey.com/C_VB_Codes/Abstraction.aspx
Approved definitions here
P.S.: I also remember the definition from a book named C++ by Sumita Arora which we read in 11th class ;)
The meaning of abstraction given by the Oxford English Dictionary (OED) closest to the meaning intended here is 'The act of separating in thought'. A better definition might be 'Representing the essential features of something without including background or inessential detail.'
Information hiding is the principle that users of a software component (such as a class) need to know only the essential details of how to initialize and access the component, and do not need to know the details of the implementation.
Edit: I seems to me that abstraction is the process of deciding which parts of the implementation that should be hidden.
So its not abstraction VERSUS information hiding. It's information hiding VIA abstraction.
Abstraction
Abstraction is an act of representing essentail details without including the background details. A abstract class have only method signatures and implementing class can have its own implementation, in this way the complex details will be hidden from the user. Abstraction focuses on the outside view. In otherwords, Abstraction is sepration of interfaces from the actual implementation.
Encapsulation
Encapsulation explains binding the data members and methods into a single unit. Information hiding is the main purpose of encapsulation. Encapsulation is acheived by using access specifiers like private, public, protected. Class member variables are made private so that they cann't be accessible directly to outside world. Encapsulation focuses on the inner view. In otherwords, Encapsulation is a technique used to protect the information in an object from the other object.
Abstraction is hiding details of implementation as you put it.
You abstract something to a high enough point that you'll only have to do something very simple to perform an action.
Information hiding is hiding implementation details. Programming is hard. You can have a lot of things to deal with and handle. There can be variables you want/need to keep very close track of. Hiding information ensures that no one accidentally breaks something by using a variable or method you exposed publicly.
These 2 concepts are very closely tied together in object-oriented programming.
Abstraction - It is the process of identifying the essential characteristics of an object
without including the irrelevant and tedious details.
Encapsulation - It is the process of enclosing data and functions manipulating this data into a single unit.
Abstraction and Encapsulation are related but complementary concepts.
Abstraction is the process. Encapsulation is the mechanism by which Abstraction is implemented.
Abstraction focuses on the observable behavior of an object. Encapsulation focuses upon the implementation that give rise to this behavior.
Information Hiding - It is the process of hiding the implementation details of an object. It is a result of Encapsulation.
Abstraction : Abstraction is the concept/technique used to identify what should be the external view of an object. Making only the required interface available.
Information Hiding : It is complementary to Abstraction, as through information hiding Abstraction is achieved. Hiding everything else but the external view.
Encapsulation : Is binding of data and related functions into a unit. It facilitates Abstraction and information hiding. Allowing features like member access to be applied on the unit to achieve Abstraction and Information hiding
In very short
Encapsulation:– Information hiding
Abstraction :– Implementation hiding
Abstraction lets you focus on what the object does while Encapsulation means how an object works
Encapsulation: binding the data members and member functions together is called encapsulation. encapsulation is done through class.
abstraction: hiding the implementation details form usage or from view is called abstraction.
ex:
int x;
we don't know how int will internally work. but we know int will work. that is abstraction.
See Joel's post on the Law of Leaky Abstractions
JoelOnsoftware
Basically, abstracting gives you the freedom of thinking of higher level concepts. A non-programming analogy is that most of us do not know where our food comes from, or how it is produced, but the fact that we (usually) don't have to worry about it frees us up to do other things, like programming.
As for information hiding, I agree with jamting.
It's worth noting these terms have standardized, IEEE definitions, which can be searched at https://pascal.computer.org/.
abstraction
view of an object that focuses on the information relevant to a particular purpose and ignores the remainder of the information
process of formulating a view
process of suppressing irrelevant detail to establish a simplified model, or the result of that process
information hiding
software development technique in which each module's interfaces reveal as little as possible about the module's inner workings and other modules are prevented from using information about the module that is not in the module's interface specification
containment of a design or implementation decision in a single module so that the decision is hidden from other modules
encapsulation
software development technique that consists of isolating a system function or a set of data and operations on those data within a module and providing precise specifications for the module
concept that access to the names, meanings, and values of the responsibilities of a class is entirely separated from access to their realization
idea that a module has an outside that is distinct from its inside, that it has an external interface and an internal implementation
Abstraction allows you to treat a complex process as a simple process. For example, the standard "file" abstraction treats files as a contiguous array of bytes. The user/developer does not even have to think about issues of clusters and fragmentation. (Abstraction normally appears as classes or subroutines.)
Information hiding is about protecting your abstractions from malicious/incompetent users. By restricting control of some state (hard drive allocations, for example) to the original developer, huge amounts of error handling becomes redundant. If nobody else besides the file system driver can write to the hard drive, then the file system driver knows exactly what has been written to the hard drive and where. (The usual manifestation of this concept is private and protected keywords in OO languages.)
To abstract something we need to hide the detail or to hide the detail of something we need to abstract it.
But, both of them can be achieved by encapsulation.
So, information hiding is a goal, abstraction is a process, and encapsulation is a technique.
Abstraction simply means the technique in which only essential details of software is made visible to the user to help the user to use or operate with software, thus implementation details of that software are not shown(are made invisible).
Encapsulation is the technique that have package that hold one or more items and hence some of information (particularly program details) became visible and some not visible to the user, so encapsulation is achieved through information hiding.
In summary. Abstraction is for observable behavior (externally) and encapsulation is for invisibility (internally) but these two are really complementary.
Just adding on more details around InformationHiding, found This link is really good source with examples
InformationHiding is the idea that a design decision should be hidden from the rest of the system to prevent unintended coupling. InformationHiding is a design principle. InformationHiding should inform the way you encapsulate things, but of course it doesn't have to.
Encapsulation is a programming language feature.
Both Abstraction and Encapsulation are two of the four basic OOP concepts which allow you to model real-world things into objects so that you can implement them in your program and code. Many beginners get confused between Abstraction and Encapsulation because they both look very similar. If you ask someone what is Abstraction, he will tell that it's an OOP concept which focuses on relevant information by hiding unnecessary detail, and when you ask about Encapsulation, many will tell that it's another OOP concept which hides data from outside world. The definitions are not wrong as both Abstraction and Encapsulation does hide something, but the key difference is on intent.
Abstraction hides complexity by giving you a more abstract picture, a sort of 10,000 feet view, while Encapsulation hides internal working so that you can change it later. In other words, Abstraction hides details at the design level, while Encapsulation hides details at the implementation level.
After reading all the above answers one by one I cant stop myself from posting that
abstraction involves the facility to define objects that represent abstract "actors" that can perform work, report on and change their state, and "communicate" with other objects in the system.
Encapsulation is quite clear from above however ->
The term encapsulation refers to the hiding of state details, but extending the concept of data type from earlier programming languages to associate behavior most strongly with the data, and standardizing the way that different data types interact, is the beginning of abstraction.
reference wiki
I too was very confused about the two concepts of Abstraction and Encapsulation. But when I saw the abstraction article on myjavatrainer.com, It became clear to me that Abstraction and Encapsulation are Apples and Oranges, you can't really compare them because both are required.
Encapsulation is how the object is created, and abstraction is how the object is viewed in the outside world.
Encapsulation: binding data and the methods that act on it. this allows the hiding of data from all other methods in other classes.
example: MyList class that can add an item, remove an item, and remove all items
the methods add, remove, and removeAll act on the list(a private array) that can not be accessed directly from the outside.
Abstraction: is hiding the non relevant behavior and data.
How the items are actually stored, added, or deleted is hidden (abstracted).
My data may be held in simple array, ArrayList, LinkedList, and so on.
Also, how the methods are implemented is hidden from the outside.
Encapsulation- enforcing access to the internal data in a controlled manner or preventing members from being accessed directly.
Abstraction- Hiding the implementation details of certain methods is known as abstraction
Let's understand with the help of an example:-
class Rectangle
{
private int length;
private int breadth;// see the word private that means they cant be accesed from
outside world.
//now to make them accessed indirectly define getters and setters methods
void setLength(int length)
{
// we are adding this condition to prevent users to make any irrelevent changes
that is why we have made length private so that they should be set according to
certain restrictions
if(length!=0)
{
this.length=length
}
void getLength()
{
return length;
}
// same do for breadth
}
now for abstraction define a method that can only be accessed and user doesnt know
what is the body of the method and how it is working
Let's consider the above example, we can define a method area which calculates the area of the rectangle.
public int area()
{
return length*breadth;
}
Now, whenever a user uses the above method he will just get the area not the way how it is calculated. We can consider an example of println() method we just know that it is used for printing and we don't know how it prints the data.
I have written a blog in detail you can see the below link for more info
abstraction vs encapsulation

Resources