File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes OO, Patterns, UML and Refactoring and the fly likes What is the benefit of Encapsulation? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "What is the benefit of Encapsulation?" Watch "What is the benefit of Encapsulation?" New topic
Author

What is the benefit of Encapsulation?

Hemal Mahagederawatte
Greenhorn

Joined: Dec 17, 2008
Posts: 16
what is the benefit of encapsulation. making the variables private and writing setter and getter method?
In text book I read that if you used encapsulation the user of the data does not need to know how, where, or in what form the owner of the data stores the data. And if the owner changes the way in which data is stored the user of the data need not be affected.

For a example in the Class A if you have a variable of the type int. And the Class B instances use that variable. If the user change the variable type to float Class B methods are also effected and they have to change their methods.
So what is the benefit of using encapsulation?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Providing setters and getters actually is a very weak form of encapsulation. In general, you should try to avoid those, too, and have methods with nmore intelligent behavior instead. See http://www.pragprog.com/articles/tell-dont-ask


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
Originally posted by Hemal Mahagederawatte:

For a example in the Class A if you have a variable of the type int. And the Class B instances use that variable. If the user change the variable type to float Class B methods are also effected and they have to change their methods.
So what is the benefit of using encapsulation?


The benefit of encapsulation is to allow one class ("server") to make a contract with another class ("client") to provide some service with only a very few things being required to be known about the "server" class such as method signature and return type. The benefit is only realized if the contract of what is required and what is returned remains the same. So, in your example, there is no benefit since the contract was broken by Class A.

Instead of class A changing int type to float, class A should create another new variable of type float for other classes to use so that class B is not "broken" or that contract is not broken between them. Class C could refer to new float variable and Class B could still refer to old int variable and everyone is happy. Better yet, methods would used to retrieve values such as: "getIntVar()" and "getFloatVar" depending on what was wanted.

The real benefit of good encapsulation is that Class A can be completely re-written from top to bottom and as long as the contract is honored as to what Class A is expected to do(have methods "getIntVar()" and "getFloatVar"), then everything in Class B and C works the same. Think carefully about what is exposed and how it is exposed. Things that will change often and break other classes need to be considered carefully before exposing. Good encapsulation means hiding things that are expected to change often so to avoid breaking other classes.
[ December 17, 2008: Message edited by: herb slocomb ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
In fact, class B probably never should have used a variable of class A - that's already a violation of encapsulation. Instead, class B should have class A to do whatever it wants it to have done.

These things are quite hard to discuss in the abstract. Perhaps you have a concrete, real example?
Hemal Mahagederawatte
Greenhorn

Joined: Dec 17, 2008
Posts: 16
Hi herb slocomb & Ilja Preuss,
Thank you so much for your replyies
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
Originally posted by Ilja Preuss:


These things are quite hard to discuss in the abstract.


Democritus focused on the physical form of reality with atoms as its basis whereas Heraclitus pointed out that the process of change is the constant. In modern terms we have two lenses to view the world; as entities or as processes; Object oriented programming or programming based on processes; linguistic emphasis on nouns as the essential part of speech as in most Indo-European languages or an emphasis on verbs or actions as the key way to describe reality.

So, in essence, all the multiplicity or seeming complexity of the world can be deconstructed into more simple components, in many cases a binary construct as discussed above. But the bottom line is that discussing things in the abstract is the easiest thing to do and actually goes directly to the essential heart of the matter.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by herb slocomb:

So, in essence, all the multiplicity or seeming complexity of the world can be deconstructed into more simple components, in many cases a binary construct as discussed above. But the bottom line is that discussing things in the abstract is the easiest thing to do and actually goes directly to the essential heart of the matter.


Well, *I* don't find it to be easiest. And I have seen lots of discussions going on in the abstract for long without reaching any common understanding at all, and finally a concrete example helping everyone to get on the same page.

Actually, research shows that's exactly how people typically learn: by first understanding concrete, specific examples, and then abstracting from them.
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
Originally posted by Ilja Preuss:


Actually, research shows that's exactly how people typically learn: by first understanding concrete, specific examples, and then abstracting from them.


I'm one that has the opposite learning style. I need some of the big picture first, then all the details fall into place much more quickly.

I remember trying to learn C++ as COBOL programmer. The author said do this and do that to get the "Hello World" program to run. I didn't understand what any of the stuff I was typing really did. It seemed like gibberish compared to COBOL. Nor did I see any chapters really explaining what the curly braces were or why there had to be a "main ()" method or where the heck printf() method came from. I put the book down and didn't come back to C++ until years later...
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Good encapsulation means hiding things that are expected to change often so to avoid breaking other classes.


In my opinion, "good" encapsulation means "hiding" details from other classes that do not need to know the details to carry our their function.

For example, if an object A asks another object B to print a document on a network printer. Object A does not need to know the details of how the document is printed. The code that actually "prints the document" should only be visible to object B.

The code statements that actually execute the printing might never change. However, following the design concept of "encapsulation", you would still hide the details from object A. The behaviour of printing is a part of object B only. Object A only needs to know how to "ask" object B to print.

Objects contain both data and behavior. Well-designed objects encapsulate data and behavior.
[ December 18, 2008: Message edited by: James Clark ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by herb slocomb:

I remember trying to learn C++ as COBOL programmer. The author said do this and do that to get the "Hello World" program to run. I didn't understand what any of the stuff I was typing really did.


Well, it seems to me that this just means that he wasn't good at explaining the example, not that a more abstract explanation had been better than the example to begin with. But this is becoming quite off topic, I fear...
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by James Clark:

In my opinion, "good" encapsulation means "hiding" details from other classes that do not need to know the details to carry our their function.


In fact, what we are talking about here is information hiding. Enapsulation actually doesn't mean more than putting operations close to the data they are operating on (i.e. on the same class).
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Encapsulation refers to "hiding" or "shielding" behaviour as well. As a matter of fact, shielding client objects from the details of "behaviour" is more important that "hiding" data implementation details, in my opinion.
[ December 18, 2008: Message edited by: James Clark ]
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
Originally posted by James Clark:
Encapsulation refers to "hiding" or "shielding" behaviour as well.




This may seem academic, but if we put it in a context of how a sequence of design steps can be done it may be helpful:

1) Decide on classes.
2) Decide what classes will do - what are their methods and data : Encapsulation.
3) Decide what parts of the class, which methods and data from step 2, are exposed - Data hiding and "interface".

Step 3 depends on step 2 being done first - what can be hidden depends on what there is to hide, but they are distinct. As practical matter, everything is hidden except what a class is responsible to provide for others, but this can change slightly over time.
[ December 18, 2008: Message edited by: herb slocomb ]
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Herb, there is something very important missing from your steps below. The decision on classes (step #1) is based upon a set of business/domain requirements. And business/domain requirements are based either upon a business model or some other domain.

An close analysis of these requirements will determine the classes and behaviors. This will result in a business/domain object-oriented software model.

When you are designing the object model, in addition to the requirements, you are considering principles like reusability, maintainability, scaleability, encapsulation, composition, interface inheritance, coupling, etc.

At the same time, if the application system is large enough, there is an architect who is designing the architecture for the system. He/she is focusing on the Quality of Service requirements, hardware, performance, servers, load balancing, clustering, capacity, scaleability, maintainability, security, communications, etc.
[ December 18, 2008: Message edited by: James Clark ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by James Clark:
Encapsulation refers to "hiding" or "shielding" behaviour as well. As a matter of fact, shielding client objects from the details of "behaviour" is more important that "hiding" data implementation details, in my opinion.

[ December 18, 2008: Message edited by: James Clark ]


I'm not exactly sure what you mean by "hiding behavior". Care to elaborate?

I find this article to be quite good: http://www.javaworld.com/javaworld/jw-05-2001/jw-0518-encapsulation.html
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by herb slocomb:

This may seem academic, but if we put it in a context of how a sequence of design steps can be done it may be helpful:

1) Decide on classes.
2) Decide what classes will do - what are their methods and data : Encapsulation.
3) Decide what parts of the class, which methods and data from step 2, are exposed - Data hiding and "interface".

Step 3 depends on step 2 being done first - what can be hidden depends on what there is to hide, but they are distinct. As practical matter, everything is hidden except what a class is responsible to provide for others, but this can change slightly over time.


In my experience, it works quite differently:
- decide what behavior is needed
- decide how to distribute that behavior over classes - that is, what classes are needed, what are their responsibilities
- decide what public interface the classes need to be able to fulfill their responsibilities
- decide how the classes need to work internally (including what data they need) to make the interface work

And all that in very tight, iterative cycles, going back and forth between the different steps all the time.
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
I'm not exactly sure what you mean by "hiding behavior". Care to elaborate?


I am referring to encapsulation and using the term "hiding behavior" to describe part of what it means. Well-designed objects encapsulate both data and behavior.

My example above explains the concept and rationale for encapsulating object behavior. Repeated below.


For example, if an object A asks another object B to print a document on a network printer. Object A does not need to know the details of how the document is printed. The code that actually "prints the document" should only be visible to object B.

The code statements that actually execute the printing might never change. However, following the design concept of "encapsulation", you would still hide the details from object A. The behaviour of printing is a part of object B only. Object A only needs to know how to "ask" object B to print.

Objects contain both data and behavior. Well-designed objects encapsulate data and behavior.


The behavior of an object is represented by the statements that carry out some function. In the example above, the "behavior" of object B is hidden from client objects such as object A.

Only object B knows the details of how it prints and all the programming statements that execute this behavior are encapsulated in object B.

Object B exposes an interface to allow client objects to send it messages. This is the only detail that a client object, such as object A, needs to know. Object A only knows about the API to print not the details of the behavior. This is encapsulation.
[ December 19, 2008: Message edited by: James Clark ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by James Clark:
An close analysis of these requirements will determine the classes and behaviors. This will result in a business/domain object-oriented software model.

When you are designing the object model, in addition to the requirements, you are considering principles like reusability, maintainability, scaleability, encapsulation, composition, interface inheritance, coupling, etc.


Even more than that - the latter object model is a model of the *solution* domain, whereas the former model is one of the *problem* domain. The mapping between both models is *the* critical creative act done by software developers. http://www.objectmentor.com/resources/articles/CoffeeMaker.pdf is a nice article on this topic.

At the same time, if the application system is large enough, there is an architect who is designing the architecture for the system. He/she is focusing on the Quality of Service requirements, hardware, performance, servers, load balancing, clustering, capacity, scaleability, maintainability, security, communications, etc.


Whereas I agree that these are all things that need to be done, having a single person assigned to that role is just one way to do it, and there is far from being agreement in the community that it is the best way.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
James, would it be correct to say that you see information hiding as being one part of encapsulation?
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
In my example above, object B contains statements (25 lines of code) that execute the behavior of printing a document on a network printer. If we consider the 25 lines of code as implementation details or "information", then it is "hidden" from client objects by encapsulation.

The details (information) of the class behavior is encapsulated (hidden).

Note that I am only speaking in terms of Object technology. The term "information hiding" might have some other, older definitions that relate to other computer science concepts.

But, speaking in terms of object-oriented design, I consider "information hiding" a feature of encapsulation. I don't care for the term however. It is strange and awkward. If I were writing a paper, I would use the term encapsulation.
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
Originally posted by James Clark:

...
But, speaking in terms of object-oriented design, I consider "information hiding" a feature of encapsulation. ...


Is an object with all public variables and public methods encapuslated ?

I would say yes; encapsulation is bundling related data and data methods of an abstraction to create a class. The visibility of that data and methods is a separate issue and can be altered later without altering the essential meaning and purpose of the class. "Hiding" does not define the essential purpose of a class, it is a safety feature to prevent class misuse. Hence information hiding is not an essential feature of encapsulation and is a distinct, although related concept.

Distinguishing the two concepts using a design context, but trying to avoid writing a book on design and requirements, was what I tried to do earlier. The point being simply that encapsulation comes first, what to hide must come later.
[ December 19, 2008: Message edited by: herb slocomb ]
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Is an object with all public variables and public methods encapuslated ?

It is weakly encapsulated. The client objects still do not have to know the implementation details (information) about the behavior (the methods.) This information, the details, are still hidden from client objects. There is information hiding. There is encapsulation.

Encapsulation is more that just bundling fields and methods in a class. It is a much deeper concept. Too deep to completly discuss in an Internet forum. The visibility of data and methods determines the degree of encapsulation. It is not a separate issue.

"hiding" is strange and awkward when speaking about technical concepts. If we were talking about children playing in a playground, it might be appropriate. The term "information" is very general as well. The details of my wallet are hiding in my jeans. My jeans are implementing information hiding cause other humans can't see my wallet and don't know the information in it. My wallet is encapsulated. Oh well...
[ December 19, 2008: Message edited by: James Clark ]
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
Originally posted by James Clark:

... The visibility of data and methods determines the degree of encapsulation. It is not a separate issue....


Wiki: "The term encapsulation is often used interchangeably with information hiding." I see the validity of your approach and I have held it myself prior to recently reading some of the older books on OOP.

I think sometimes separating aspects of class design into separate areas of discussion with more distinct terms allows greater understanding. Going back to abstractions, notions of "what" and "how" should be distinct. We need a term to discuss what data and what methods an abstraction will hold to make it into a coherent entity that will define a class. We need another term to define how they operate.

Hence, one term to discuss defining essential aspects of a class(encapsulation) and another to discuss an aspect of implementation such as visibility("hiding"). Mixing visibility into the class definition I think causes confusion especially as in relation to real issues of visibility of the class in relation to other entities in packages, modules, subsystems, inheritence, components, etc. Changing the visibility of aspects of a class does not alter its essential responsibilities or purpose or functions.

Having to use the same term with several sets of different adjectives indicates that another separate term may be useful. You use "strong" and "weak" "degrees" of encapsulation. What about qualitative, non-degree aspects, such as "good" and "bad" encapsulation? An example would be mixing in methods of string functions into a static math class - bad encapsulation, even if "strong" information hiding. Another term is helpful to clearly identify what makes encapsulation strong or weak, good or bad.
[ December 19, 2008: Message edited by: herb slocomb ]
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Wiki: "The term encapsulation is often used interchangeably with information hiding."


What is described in the Wiki statement is a not concise. "information hiding" is only one part of the design concept of encapsulation. There are other parts. To use the terms interchangeably like they had equal meaning is not effective and may cause confusion.
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
Originally posted by James Clark:

"information hiding" is only one part of the design concept of encapsulation. There are other parts. To use the terms interchangeably like they had equal meaning is not effective and may cause confusion.


I agree that the terms are not equivalent. Looking back through my books, I see that most authors take your approach. But I just read an old edition of "Designing Object-Oriented Software" by Rebecca Wirfs-Brock and she focused on encapsulation as the "bundling" of related data and methods.

Using a definition of encapsulation that focuses only on the one aspect of "bundling" you can more effectively isolate that one aspect and deal more clearly with the factors that determine what should be bundled. Perhaps internal cohesion of a class and possibly how appropriately it models the abstraction are some factors to consider in this "bundling" analysis.

I think its worthwhile to carefully consider what goes into an appropriate bundling on its own without mixing in extraneous concepts relating to the interface a class or information hiding or implementation hiding all in the same term. Its possible to talk about information hiding completely separately from whether specific data or methods are appropriately bundled in the class.

If you say a class is badly encapsulated or weakly encapsulated, do you mean there are issues with bundling, with the interface, with information hiding, or with all of them, or with 3 out 4 of the previously mentioned aspects? I know most people mean the issue is with hiding information, but the issue could actually be the weak cohesion within a class or something related to bundling given that the term encapsulation encompasses those issues as well.
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
I agree that the terms are not equivalent. Looking back through my books, I see that most authors take your approach. But I just read an old edition of "Designing Object-Oriented Software" by Rebecca Wirfs-Brock and she focused on encapsulation as the "bundling" of related data and methods.


To get a comprehensive understanding of a concept, one should study many perspectives from many individuals. And then build upon this understanding with personal experience. In some cases, not all of the perspectives will be identical because experiences vary and authors may have different writing styles. Some perspectives may even include incorrect information or grossly opinionated views. You need to be able effectively filter the information and process it accordingly.

As I mentioned earlier, encapsulation is more that just "bundling fields and methods in a class." It is a much deeper concept.

1. Encapsulation is not the act of designing a class with related fields and methods.

2. Encapsulation is a design principle that is considered when designing a class with related fields and methods. This consideration includes the process of how client objects will communicate, i.e. interact, with the object. The focus is on multiple objects and how they communicate, not just a single object.

The author in the book you mention seems to be confusingly and roughly defining encapsulation as "designing a class with related data and methods." This is not correct.
[ December 19, 2008: Message edited by: James Clark ]
frank davis
Ranch Hand

Joined: Feb 12, 2001
Posts: 1479
Originally posted by James Clark:


2. Encapsulation is a design principle that is considered when designing a class with related fields and methods. This consideration includes the process of how client objects will communicate, i.e. interact, with the object. The focus is on multiple objects and how they communicate, not just a single object.

[ December 19, 2008: Message edited by: James Clark ]


How's this to tie it all together: Encapsulation is the principle of grouping together related data and methods that are needed to fulfill a class's responsibilities and to communicate any information relating to the responsibilities through a defined interface.

We have a reason to group data and info. We have a defined interface through which responsibilities should occur implying other info should be hidden.
Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
It is more about reducing the coupling between objects. The big benefit of encapsulation is the reduced dependency between objects.

In my example, object A does not need to know any details about printing the document on the network printer. All object A needs to know is that is it can ask object B to print and how to ask, i.e. send a message to object B.

If any codes statement need to change in object B for printing a document on the network, nothing has to change in object A.

If we needed to debug a problem about printing documents on the network, we would not have to look in object A. Because, the behavior is encapsulated in object B

Encapsulation is about reducing the coupling between objects and appropriately designing object behaviour in a modular fashion.
[ December 20, 2008: Message edited by: James Clark ]
 
 
subject: What is the benefit of Encapsulation?
 
Similar Threads
Question No.36 from Javacaps
What is Encapsulation
SCJP Requirements V. OO Concepts: encapsulation cohesion coupling.
encapsulation & abstraction
Bean?!