Rectangle 27 46

The Beauty of Encapsulation

Encapsulation is more than just defining accessor and mutator methods for a class. It is broader concept of object-oriented programming that consists in minimizing the interdependence between classes and it is typically implemented through information hiding.

In a object-oriented programming language like Java, you achieve encapsulation by hiding details using the accessibility modifiers (public, protected, private, plus no modifier which implies package private). With these levels of accessibility you control the level of encapsulation, the less restrictive the level, the more expensive change is when it happens and the more coupled the class is with other dependent classes (i.e. user classes, subclasses).

Therefore, the goal is not to hide the data itself, but the implementation details on how this data is manipulated.

The idea is to provide a public interface through which you gain access to this data. You can later change the internal representation of the data without compromising the public interface of the class. On the contrary, by exposing the data itself, you compromise encapsulation, and therefore, the capacity of changing the way you manipulate the data without affecting its users. You create a dependency with the data itself, and not with the public interface of the class. You would be creating a perfect cocktail for trouble when "change" finally finds you.

There are several reasons why you might want to encapsulate access to your fields. Joshua Bloch in his book Effective Java, in Item 14: Minimize the accessibility of classes and members, mentions several compelling reasons, which I quote here:

  • You can limit the values that can be stored in a field (i.e. gender must be F or M).
  • You can take actions when the field is modified (trigger event, validate, etc).
  • You can provide thread safety by synchronizing the method.
  • You can switch to a new data representation (i.e. calculated fields, different data type)

However, encapsulation is more than hiding fields. In Java you can hide entire classes, by this, hiding the implementation details of an entire API. Think, for example, in the method Arrays.asList(). It returns a List implementation, but you do no care which implementation, as long as it satisfies the List interface, right?. The implementation can be changed in the future without affecting the users of the method.

Think, for example, in the level of abstraction in the concept of a car. A car is complex in its internal implementation. They have several subsystem, like a transmission system, a brake system, a fuel system, etc.

However, we have simplified its abstraction, and we interact with all cars in the world through the public interface of their abstraction. We know that all cars have a steering wheel through which we control direction, they have a pedal that when you press it you accelerate the car and control speed, and another one that when you press it you make it stop, and you have a gear stick that let you control if you go forward or backwards. These features constitute the public interface of the car abstraction. In the morning you can drive a sedan and then get out of it and drive an SUV in the afternoon as if it was the same thing.

However, few of us know the details of how all these features are implemented under the hood. Think of the time when cars did not have a hydraulics directional system. One day, the car manufactures invented it, and they decide it to put it in cars from there on. Still, this did not change the way in which users were interacting with them. At most, users experienced an improvement in the use of the directional system. A change like this was possible because the internal implementation of a car is encapsulated. Changes can be safely done without affecting its public interface.

Now, think that car manufacturers decided to put the fuel cap below the car, and not in one of its sides. You go and buy one of these new cars, and when you run out of gas you go to the gas station, and you do not find the fuel cap. Suddenly you realize it's below the car, but you cannot reach it with the gas pump hose. Now, we have broken the public interface contract, and therefore, the entire world breaks, it falls apart because things are not working the way it was expected. A change like this would cost millions. We would need to change all gas pumps in the world. When we break encapsulation we have to pay a price.

So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface.

I really recommend you to read a paper by Alan Snyder called Encapsulation and Inheritance in Object-Oriented programming Languages. This link points to the original paper on ACM, but I am pretty sure you will be able to find a PDF copy through Google.

Great Response . especially when u summed up your comments in these 3 lines "So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface." .. Nice Job!

@oblivion It means the users of your API, the persons who would actually use it to solve a problem.

@Lealo, it would be very hard to just comment on that. My suggestion is that you open a question about it and make a reference to this post, that way you could get an extensive answer.

oop - Java Encapsulation - Stack Overflow

java oop java-ee encapsulation
Rectangle 27 46

The Beauty of Encapsulation

Encapsulation is more than just defining accessor and mutator methods for a class. It is broader concept of object-oriented programming that consists in minimizing the interdependence between classes and it is typically implemented through information hiding.

In a object-oriented programming language like Java, you achieve encapsulation by hiding details using the accessibility modifiers (public, protected, private, plus no modifier which implies package private). With these levels of accessibility you control the level of encapsulation, the less restrictive the level, the more expensive change is when it happens and the more coupled the class is with other dependent classes (i.e. user classes, subclasses).

Therefore, the goal is not to hide the data itself, but the implementation details on how this data is manipulated.

The idea is to provide a public interface through which you gain access to this data. You can later change the internal representation of the data without compromising the public interface of the class. On the contrary, by exposing the data itself, you compromise encapsulation, and therefore, the capacity of changing the way you manipulate the data without affecting its users. You create a dependency with the data itself, and not with the public interface of the class. You would be creating a perfect cocktail for trouble when "change" finally finds you.

There are several reasons why you might want to encapsulate access to your fields. Joshua Bloch in his book Effective Java, in Item 14: Minimize the accessibility of classes and members, mentions several compelling reasons, which I quote here:

  • You can limit the values that can be stored in a field (i.e. gender must be F or M).
  • You can take actions when the field is modified (trigger event, validate, etc).
  • You can provide thread safety by synchronizing the method.
  • You can switch to a new data representation (i.e. calculated fields, different data type)

However, encapsulation is more than hiding fields. In Java you can hide entire classes, by this, hiding the implementation details of an entire API. Think, for example, in the method Arrays.asList(). It returns a List implementation, but you do no care which implementation, as long as it satisfies the List interface, right?. The implementation can be changed in the future without affecting the users of the method.

Think, for example, in the level of abstraction in the concept of a car. A car is complex in its internal implementation. They have several subsystem, like a transmission system, a brake system, a fuel system, etc.

However, we have simplified its abstraction, and we interact with all cars in the world through the public interface of their abstraction. We know that all cars have a steering wheel through which we control direction, they have a pedal that when you press it you accelerate the car and control speed, and another one that when you press it you make it stop, and you have a gear stick that let you control if you go forward or backwards. These features constitute the public interface of the car abstraction. In the morning you can drive a sedan and then get out of it and drive an SUV in the afternoon as if it was the same thing.

However, few of us know the details of how all these features are implemented under the hood. Think of the time when cars did not have a hydraulics directional system. One day, the car manufactures invented it, and they decide it to put it in cars from there on. Still, this did not change the way in which users were interacting with them. At most, users experienced an improvement in the use of the directional system. A change like this was possible because the internal implementation of a car is encapsulated. Changes can be safely done without affecting its public interface.

Now, think that car manufacturers decided to put the fuel cap below the car, and not in one of its sides. You go and buy one of these new cars, and when you run out of gas you go to the gas station, and you do not find the fuel cap. Suddenly you realize it's below the car, but you cannot reach it with the gas pump hose. Now, we have broken the public interface contract, and therefore, the entire world breaks, it falls apart because things are not working the way it was expected. A change like this would cost millions. We would need to change all gas pumps in the world. When we break encapsulation we have to pay a price.

So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface.

I really recommend you to read a paper by Alan Snyder called Encapsulation and Inheritance in Object-Oriented programming Languages. This link points to the original paper on ACM, but I am pretty sure you will be able to find a PDF copy through Google.

Great Response . especially when u summed up your comments in these 3 lines "So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface." .. Nice Job!

@oblivion It means the users of your API, the persons who would actually use it to solve a problem.

@Lealo, it would be very hard to just comment on that. My suggestion is that you open a question about it and make a reference to this post, that way you could get an extensive answer.

oop - Java Encapsulation - Stack Overflow

java oop java-ee encapsulation
Rectangle 27 45

The Beauty of Encapsulation

Encapsulation is more than just defining accessor and mutator methods for a class. It is broader concept of object-oriented programming that consists in minimizing the interdependence between classes and it is typically implemented through information hiding.

In a object-oriented programming language like Java, you achieve encapsulation by hiding details using the accessibility modifiers (public, protected, private, plus no modifier which implies package private). With these levels of accessibility you control the level of encapsulation, the less restrictive the level, the more expensive change is when it happens and the more coupled the class is with other dependent classes (i.e. user classes, subclasses).

Therefore, the goal is not to hide the data itself, but the implementation details on how this data is manipulated.

The idea is to provide a public interface through which you gain access to this data. You can later change the internal representation of the data without compromising the public interface of the class. On the contrary, by exposing the data itself, you compromise encapsulation, and therefore, the capacity of changing the way you manipulate the data without affecting its users. You create a dependency with the data itself, and not with the public interface of the class. You would be creating a perfect cocktail for trouble when "change" finally finds you.

There are several reasons why you might want to encapsulate access to your fields. Joshua Bloch in his book Effective Java, in Item 14: Minimize the accessibility of classes and members, mentions several compelling reasons, which I quote here:

  • You can limit the values that can be stored in a field (i.e. gender must be F or M).
  • You can take actions when the field is modified (trigger event, validate, etc).
  • You can provide thread safety by synchronizing the method.
  • You can switch to a new data representation (i.e. calculated fields, different data type)

However, encapsulation is more than hiding fields. In Java you can hide entire classes, by this, hiding the implementation details of an entire API. Think, for example, in the method Arrays.asList(). It returns a List implementation, but you do no care which implementation, as long as it satisfies the List interface, right?. The implementation can be changed in the future without affecting the users of the method.

Think, for example, in the level of abstraction in the concept of a car. A car is complex in its internal implementation. They have several subsystem, like a transmission system, a brake system, a fuel system, etc.

However, we have simplified its abstraction, and we interact with all cars in the world through the public interface of their abstraction. We know that all cars have a steering wheel through which we control direction, they have a pedal that when you press it you accelerate the car and control speed, and another one that when you press it you make it stop, and you have a gear stick that let you control if you go forward or backwards. These features constitute the public interface of the car abstraction. In the morning you can drive a sedan and then get out of it and drive an SUV in the afternoon as if it was the same thing.

However, few of us know the details of how all these features are implemented under the hood. Think of the time when cars did not have a hydraulics directional system. One day, the car manufactures invented it, and they decide it to put it in cars from there on. Still, this did not change the way in which users were interacting with them. At most, users experienced an improvement in the use of the directional system. A change like this was possible because the internal implementation of a car is encapsulated. Changes can be safely done without affecting its public interface.

Now, think that car manufacturers decided to put the fuel cap below the car, and not in one of its sides. You go and buy one of these new cars, and when you run out of gas you go to the gas station, and you do not find the fuel cap. Suddenly you realize it's below the car, but you cannot reach it with the gas pump hose. Now, we have broken the public interface contract, and therefore, the entire world breaks, it falls apart because things are not working the way it was expected. A change like this would cost millions. We would need to change all gas pumps in the world. When we break encapsulation we have to pay a price.

So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface.

I really recommend you to read a paper by Alan Snyder called Encapsulation and Inheritance in Object-Oriented programming Languages. This link points to the original paper on ACM, but I am pretty sure you will be able to find a PDF copy through Google.

Great Response . especially when u summed up your comments in these 3 lines "So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface." .. Nice Job!

@oblivion It means the users of your API, the persons who would actually use it to solve a problem.

@Lealo, it would be very hard to just comment on that. My suggestion is that you open a question about it and make a reference to this post, that way you could get an extensive answer.

oop - Java Encapsulation - Stack Overflow

java oop java-ee encapsulation
Rectangle 27 13

Inner class: handy for ownership and encapsulation

The difference is well addressed by the other answer. Regarding their usage/relevance, here is my view:

They are handy to implement callbacks easily, without the burden to create new named class.

button.addActionListener(
      new ActionListener() {
         public void actionPerformed( ActionEvent e ) {
              frame.dispose();
         }
      }
);

They are also handy for threading (e.g. anonymous Runnable) and a few other similar pattern.

Static nested classes are essentially like regular classes, except that their name is OuterClass.StaticNestedClass and you can play with modifier. So it provided some form of encapsulation that can not exactly be achieved with top-level classes.

Think for instance of a LinkedList for which you would like the class Node (used only internally) to not be visible in the package view. Make it a static nested class so that it's fully internal to the LinkedList.

An instance of an inner class has access to the field of its enclosing class instance. Think again of the linked list and imagine Node is an inner class:

public class LinkedList {
  private Node root = null;

  public class Node {
    private Object obj;
    private Node next;

    ...

    public void setAsRoot() {
       root = this;
    }
  }

  public Node getRoot() {
    return root;
  }

  public void setRoot( Node node ) {
    root = node;
  }

}

Each Node instance belonging to a LinkedList can access it directly. There is an implicit ownership relationship between the list and its nodes; the list owns its nodes. The same ownership relationship would require extra code if implemented with regular classes.

I like this answer, coming from a .net world to a world where no delegates exists, inner classes can prove useful...

What are the uses of inner classes in Java? Are nested classes and inn...

java inner-classes
Rectangle 27 13

Inner class: handy for ownership and encapsulation

The difference is well addressed by the other answer. Regarding their usage/relevance, here is my view:

They are handy to implement callbacks easily, without the burden to create new named class.

button.addActionListener(
      new ActionListener() {
         public void actionPerformed( ActionEvent e ) {
              frame.dispose();
         }
      }
);

They are also handy for threading (e.g. anonymous Runnable) and a few other similar pattern.

Static nested classes are essentially like regular classes, except that their name is OuterClass.StaticNestedClass and you can play with modifier. So it provided some form of encapsulation that can not exactly be achieved with top-level classes.

Think for instance of a LinkedList for which you would like the class Node (used only internally) to not be visible in the package view. Make it a static nested class so that it's fully internal to the LinkedList.

An instance of an inner class has access to the field of its enclosing class instance. Think again of the linked list and imagine Node is an inner class:

public class LinkedList {
  private Node root = null;

  public class Node {
    private Object obj;
    private Node next;

    ...

    public void setAsRoot() {
       root = this;
    }
  }

  public Node getRoot() {
    return root;
  }

  public void setRoot( Node node ) {
    root = node;
  }

}

Each Node instance belonging to a LinkedList can access it directly. There is an implicit ownership relationship between the list and its nodes; the list owns its nodes. The same ownership relationship would require extra code if implemented with regular classes.

I like this answer, coming from a .net world to a world where no delegates exists, inner classes can prove useful...

What are the uses of inner classes in Java? Are nested classes and inn...

java inner-classes
Rectangle 27 13

Inner class: handy for ownership and encapsulation

The difference is well addressed by the other answer. Regarding their usage/relevance, here is my view:

They are handy to implement callbacks easily, without the burden to create new named class.

button.addActionListener(
      new ActionListener() {
         public void actionPerformed( ActionEvent e ) {
              frame.dispose();
         }
      }
);

They are also handy for threading (e.g. anonymous Runnable) and a few other similar pattern.

Static nested classes are essentially like regular classes, except that their name is OuterClass.StaticNestedClass and you can play with modifier. So it provided some form of encapsulation that can not exactly be achieved with top-level classes.

Think for instance of a LinkedList for which you would like the class Node (used only internally) to not be visible in the package view. Make it a static nested class so that it's fully internal to the LinkedList.

An instance of an inner class has access to the field of its enclosing class instance. Think again of the linked list and imagine Node is an inner class:

public class LinkedList {
  private Node root = null;

  public class Node {
    private Object obj;
    private Node next;

    ...

    public void setAsRoot() {
       root = this;
    }
  }

  public Node getRoot() {
    return root;
  }

  public void setRoot( Node node ) {
    root = node;
  }

}

Each Node instance belonging to a LinkedList can access it directly. There is an implicit ownership relationship between the list and its nodes; the list owns its nodes. The same ownership relationship would require extra code if implemented with regular classes.

I like this answer, coming from a .net world to a world where no delegates exists, inner classes can prove useful...

What are the uses of inner classes in Java? Are nested classes and inn...

java inner-classes
Rectangle 27 14

This exposes the dependency being injected and violates the OOP principle of encapsulation.

Well, frankly speaking, everything violates encapsulation. :) It's a kind of a tender principle that must be treated well.

"Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation'". (Gang of Four 1995:19)

Aspect-oriented programming does. For example, you register onMethodCall() callback and that gives you a great opportunity to inject code to the normal method evaluation, adding strange side-effects etc.

Friend declaration in C++ does.

Class extention in Ruby does. Just redefine a string method somewhere after a string class was fully defined.

Well, a lot of stuff does.

Encapsulation is a good and important principle. But not the only one.

switch (principle)
{
      case encapsulation:
           if (there_is_a_reason)
      break!
}

I think this is sort of the point. It's dependant injection vs encapsulation. So only use dependant injection where it gives significant benifits. It's the DI everywhere that gives DI a bad name

Not sure what this answer is trying to say... That it's ok to violate encapsulation when doing DI, that it's "always ok" because it would be violated anyway, or merely that DI might be a reason to violate encapsulation? On another note, these days there is no need anymore to rely on public constructors or properties in order to inject dependencies; instead, we can inject into private annotated fields, which is simpler (less code) and preserves encapsulation. So, we can take advantage of both principles at the same time.

Inheritance does not in principle violate encapsulation, though it may do if the parent class is badly written. The other points you raise are one fairly fringe programming paradigm and several language features that have little to do with architecture or design.

oop - Must Dependency Injection come at the expense of Encapsulation? ...

oop dependency-injection inversion-of-control encapsulation
Rectangle 27 7

The primary purpose of encapsulation (scope) is to ensure that you write code that can't be broken. This applies to scope in general, so let me use a simpler example of a local variable inside a function:

function xyz ($x) {
  $y = 1;
  while ($y <= 10) {
    $array[] = $y * $x;
    $y++;
  }
  return $array;
}

The purpose of this function is to pass a number and return an array. The example code is pretty basic. In order for function xyz() to be dependable, you need to be guaranteed that it does the exact same thing every time. So what if someone had the ability to from the outside change that initial value of $y or $array? Or even $x? If you were able to do that from outside of the function, you could no longer guarantee what that function is returning.

That is where scope (encapsulation) comes into play. It is a way of setting boundaries, of assigning permissions of what can and can't be done with your variables (and functions, properties, methods, objects) to make sure that bit of code will always do exactly what it is expected to do.

Take for instance any built-in php function like...strtolower() or preg_match() or ...well anything. They expect arguments to be passed to them, and they return something specific. Internally there are variables, loops, etc... to take the input and spit out an output. If you were to be able to change that stuff from the outside, there would be no way to guarantee that strotolower() will return a lowercased string you feed it, and that defeats the purpose of having a reusable code block.

This isn't necessarily all that useful when you are programming for yourself, but when you are writing code to be used and shared by many people, especially with using code that involves addons/plugins, etc... it is invaluable for ensuring your code does what it is supposed to be doing, and is accessed/used/called in an expected way.

methods - PHP: What is the purpose of encapsulation? - Stack Overflow

php methods properties encapsulation
Rectangle 27 8

I have also been confused like you too for a long time until i read the book Encapsulation and Inheritance in Object-Oriented Programming Language and a website that explained the importance of Encapsulation. I was actually directed from the website to the book.

People always say encapsulation is "hiding of information" therefore, maybe, making encapsulation focus on security as the main use. Yes you are hiding information in practice, but that should not be the definition as it could confuse people.

Encapsulation is simply "minimizing inter-dependencies among separately-written modules by defining strict external interfaces" (quoting from the book). That is to say that when i am building a module, i want a strict contract between my clients and me on how they can access my module. Reason being that, so that i can improve the inner workings without it AFFECTING my client's, life, application or whatever they are using my module for. Because their "module" does not exactly depend on the Inner workings of my module but depends on the "external interface", i made available to them.

So if i don't provide my client with a setter and gave them direct access to a variable, and i realize that i need to set some restriction on the variable before my client could use it, me changing it, could be me, changing the life of my client, or application of my client with HUGE EXPENSE. But if i provided the "strict contract" by creating a "strict external interface" i.e setter, then i can easily change my inner workings with very little or no expense to my clients.

In the setter situation (using encapsulation), if it happens that when you set a variable, and I return a message informing you that it has been assigned, now I could send a message via my "interface", informing my client of the new way my module have to be interacted with, i.e "You cannot assign negative numbers" that is if my clients try to assign negative number. But if i did not use encapsulation, and gave my client direct access to a variable and I do my changes, it could result to a crashed system, because,if the restriction i implemented, is that, you could not save negatives and my client have always been able to store negatives, my clients will have a crashed system in their hands (if that "crashed system" was a banking system, imagine what could happen).

So encapsulation is more about reducing dependency between module, so improvement can be made "quietly" with little or no expense to other modules interacting with it, than it is of security. Because the interacting modules depend on the "strict external interface or strict contract".

I hope this explains it properly. If not you could go the links below and read for yourself.

This makes way more sense to me than the twenty other times I've read about encapsulation before. The idea of improving my code without effecting the client's application was the key for me.

java - What is the use of encapsulation when I'm able to change the pr...

java encapsulation
Rectangle 27 8

I have also been confused like you too for a long time until i read the book Encapsulation and Inheritance in Object-Oriented Programming Language and a website that explained the importance of Encapsulation. I was actually directed from the website to the book.

People always say encapsulation is "hiding of information" therefore, maybe, making encapsulation focus on security as the main use. Yes you are hiding information in practice, but that should not be the definition as it could confuse people.

Encapsulation is simply "minimizing inter-dependencies among separately-written modules by defining strict external interfaces" (quoting from the book). That is to say that when i am building a module, i want a strict contract between my clients and me on how they can access my module. Reason being that, so that i can improve the inner workings without it AFFECTING my client's, life, application or whatever they are using my module for. Because their "module" does not exactly depend on the Inner workings of my module but depends on the "external interface", i made available to them.

So if i don't provide my client with a setter and gave them direct access to a variable, and i realize that i need to set some restriction on the variable before my client could use it, me changing it, could be me, changing the life of my client, or application of my client with HUGE EXPENSE. But if i provided the "strict contract" by creating a "strict external interface" i.e setter, then i can easily change my inner workings with very little or no expense to my clients.

In the setter situation (using encapsulation), if it happens that when you set a variable, and I return a message informing you that it has been assigned, now I could send a message via my "interface", informing my client of the new way my module have to be interacted with, i.e "You cannot assign negative numbers" that is if my clients try to assign negative number. But if i did not use encapsulation, and gave my client direct access to a variable and I do my changes, it could result to a crashed system, because,if the restriction i implemented, is that, you could not save negatives and my client have always been able to store negatives, my clients will have a crashed system in their hands (if that "crashed system" was a banking system, imagine what could happen).

So encapsulation is more about reducing dependency between module, so improvement can be made "quietly" with little or no expense to other modules interacting with it, than it is of security. Because the interacting modules depend on the "strict external interface or strict contract".

I hope this explains it properly. If not you could go the links below and read for yourself.

This makes way more sense to me than the twenty other times I've read about encapsulation before. The idea of improving my code without effecting the client's application was the key for me.

java - What is the use of encapsulation when I'm able to change the pr...

java encapsulation
Rectangle 27 6

Abstraction and Encapsulation by using a single generalized example

Your both example tell about just encapsulation, not abstraction
hiding
Generalizing

@Rahul Now, I don't think both of them even explain encapsulation!

@Devrath If you want to tell abstraction using calulcator you might wanna go like this: There is an abstract concept of Calculator which calculates which is generalized and can be used as a base concept to make different kinds of calculator. For example, BasicCalculator and ScientificCalculator, both implementing there own ways of calculations but in the end fulfilling the criteria of generalized Calculator.

oop - difference between abstraction and encapsulation? - Stack Overfl...

oop encapsulation abstraction
Rectangle 27 182

Most answers here focus on OOP but encapsulation begins much earlier:

point x = { 1, 4 }
point y = { 23, 42 }

numeric d = distance(x, y)

Here, distance encapsulates the calculation of the (Euclidean) distance between two points in a plane: it hides implementation details. This is encapsulation, pure and simple.

Abstraction is the process of generalisation: taking a concrete implementation and making it applicable to different, albeit somewhat related, types of data. The classical example of abstraction is Cs qsort function to sort data:

The thing about qsort is that it doesn't care about the data it sorts in fact, it doesnt know what data it sorts. Rather, its input type is a typeless pointer (void*) which is just Cs way of saying I don't care about the type of data (this is also called type erasure). The important point is that the implementation of qsort always stays the same, regardless of data type. The only thing that has to change is the compare function, which differs from data type to data type. qsort therefore expects the user to provide said compare function as a function argument.

Encapsulation and abstraction go hand in hand so much so that you could make the point that they are truly inseparable. For practical purposes, this is probably true; that said, heres an encapsulation thats not much of an abstraction:

class point {
    numeric x
    numeric y
}

We encapsulate the points coordinate, but we dont materially abstract them away, beyond grouping them logically.

And heres an example of abstraction thats not encapsulation:

T pi<T> = 3.1415926535

This is a generic variable pi with a given value (), and the declaration doesnt care about the exact type of the variable. Admittedly, Id be hard-pressed to find something like this in real code: abstraction virtually always uses encapsulation. However, the above does actually exist in C++(14), via variable templates (= generic templates for variables); with a slightly more complex syntax, e.g.:

template <typename T> constexpr T pi = T{3.1415926535};

Though every method is an encapsulation, it is also an abstraction, because every time you put some things together and give it a name you create a new (abstract) concept. Encapsulation without abstraction is useless. Therefore it is not true that they've got nothing in common.

@proskor I maintain that the concepts are orthogonal even if their domains overlap. It may even be true that every encapsulation is-an abstraction (although Im not convinced) but even then I think that this would be incidental rather than an inherent property of either concept.

They are distinct, but not orthogonal. In fact, I do think that encapsulation is indeed a special kind of abstraction, namely a structural one. By considering something compound as a whole we basically ignore (abstract from) the details of how it is built up of something else, i.e. ignore its internal structure.

Abstraction is when we hide the implementation level details from the user and give access to only necessary values like Sum(1,10) will sum it up. We don't know how. We have abstracted the process of sum from user. Whereas standard definition of encapsulation suggest when we encapsulate i.e. make one data and the method acting on it. Something like class. Binding them into a single entity. The point I am trying to bring here is nothing is a hard line is both need each other to exist. Without one there isn't other.

@psylogic Im guessing the why is skipped because it seems so trivial: without abstraction and encapsulation we couldnt write complex systems. Even moderately complex problems would require such complex program code that they would fail from the outset. Without abstraction, you couldnt even write a program to print a number: the concept print involves countless abstractions (whats a screen? whats a character? whats a pixel? )

oop - difference between abstraction and encapsulation? - Stack Overfl...

oop encapsulation abstraction
Rectangle 27 5

A good depenancy injection container/system will allow for constructor injection. The dependant objects will be encapsulated, and need not be exposed publicly at all. Further, by using a DP system, none of your code even "knows" the details of how the object is constructed, possibly even including the object being constructed. There is more encapsulation in this case since nearly all of your code not only is shielded from knowledge of the encapsulated objects, but does not even participate in the objects construction.

Now, I am assuming you are comparing against the case where the created object creates its own encapsulated objects, most likely in its constructor. My understanding of DP is that we want to take this responsibility away from the object and give it to someone else. To that end, the "someone else", which is the DP container in this case, does have intimate knowledge which "violates" encapsulation; the benefit is that it pulls that knowledge out of the object, iteself. Someone has to have it. The rest of your application does not.

I would think of it this way: The dependancy injection container/system violates encapsulation, but your code does not. In fact, your code is more "encapsulated" then ever.

If you have a situation where the client object CAN instantiate its dependencies directly, then why not do so? It's definitely the simplest thing to do, and does not necessarily reduce testability. Besides the simplicity and better encapsulation, this also makes it easier to have stateful objects instead of stateless singletons.

Adding to what @Rogrio said it's also potentially significantly more efficient. Not every class ever created in the history of the world needed to have every single one of its dependencies instantiated for the entirety of the owning object's lifetime. An object using DI loses the most basic control of its own dependencies, namely their lifetime.

oop - Must Dependency Injection come at the expense of Encapsulation? ...

oop dependency-injection inversion-of-control encapsulation
Rectangle 27 40

Take example of television - it is Encapsulation, because:

Now, Abstraction is When we know a little about something and which can help us to manipulate something for which we don't know how it works internally.

  • With remote we know that pressing the number keys will change the channels. We are not aware as to what actually happens internally. We can manipulate the hidden thing but we don't know how it is being done internally.

Programmatically, when we can acess the hidden data somehow and know something.. is Abstraction .. And when we know nothing about the internals its Encapsulation.

Without remote we can't change anything on TV we have to see what it shows coz all controls are hidden.

My interviewer was happy with this example, cheers

oop - What's the difference between abstraction and encapsulation? - S...

oop encapsulation abstraction
Rectangle 27 57

There is another way of looking at this issue that you might find interesting.

When we use IoC/dependency injection, we're not using OOP concepts. Admittedly we're using an OO language as the 'host', but the ideas behind IoC come from component-oriented software engineering, not OO.

Component software is all about managing dependencies - an example in common use is .NET's Assembly mechanism. Each assembly publishes the list of assemblies that it references, and this makes it much easier to pull together (and validate) the pieces needed for a running application.

By applying similar techniques in our OO programs via IoC, we aim to make programs easier to configure and maintain. Publishing dependencies (as constructor parameters or whatever) is a key part of this. Encapsulation doesn't really apply, as in the component/service oriented world, there is no 'implementation type' for details to leak from.

Unfortunately our languages don't currently segregate the fine-grained, object-oriented concepts from the coarser-grained component-oriented ones, so this is a distinction that you have to hold in your mind only :)

Encapsulation is not just a piece of fancy terminology. It is a real thing with real benefits, and it doesn't matter if you consider your program to be "component oriented" or "object oriented". Encapsulation is supposed to protect the state of your object/component/service/whatever from being changed in unexpected ways, and IoC does take away some of this protection, so there's definitely a tradeoff.

Arguments supplied through a constructor still fall within the realm of expected ways in which the object may be "changed": they're explicitly exposed, and invariants around them are enforced. Information hiding is the better term for the kind of privacy you're referring to, @RonInbar, and it's not necessarily always beneficial (it makes the pasta harder to untangle ;-)).

The whole point of OOP is that the pasta tangle is separated out into separate classes and that you only have to mess with it at all if it's the behaviour of that particular class you wish to modify (this is how OOP mitigates complexity). A class (or module) encapsulates its internals while exposing a convenient public interface (this is how OOP facilitates reuse). A class that exposes its dependencies via interfaces creates complexity for its clients and is less reusable as a result. It is also inherently more fragile.

An interface can be implemented by different types that behave in different ways, so an interface does not enforce constraints in the way that a concrete class does. By exposing its dependencies in such a way that they must be satisfied by interfaces, a class opens itself up to the possibility that an injected dependency behaves in an unexpected manner, opening up the potential for a whole class of runtime bugs that code with statically compiled dependencies does not suffer from.

oop - Must Dependency Injection come at the expense of Encapsulation? ...

oop dependency-injection inversion-of-control encapsulation
Rectangle 27 2

If you have private fields they can't be accessed outside the class, that means basically those fields don't exist to the outside world and yes you can change their value through setter methods but using setter methods you have more flexibility/control to say who gets to change the fields and to what value can they be changed to...basically with encapsulation you get to put restrictions on how and who changes your fields. For example you have: private double salary, you setter method could restrict that only hr staff can change the salary field it could be written as:

void setSalary(Person p,double newSalary)    
{    
//only HR objects have access to change salary field.   
If(p instanceof HR && newSalary>=0)    
//change salary.   
else   
 S.o.p("access denied");    
}

Imagine if salary was public and could be access directly any can change it however and whenever they want, this basically the significance of encapsulation

java - What is the use of encapsulation when I'm able to change the pr...

java encapsulation
Rectangle 27 2

If you have private fields they can't be accessed outside the class, that means basically those fields don't exist to the outside world and yes you can change their value through setter methods but using setter methods you have more flexibility/control to say who gets to change the fields and to what value can they be changed to...basically with encapsulation you get to put restrictions on how and who changes your fields. For example you have: private double salary, you setter method could restrict that only hr staff can change the salary field it could be written as:

void setSalary(Person p,double newSalary)    
{    
//only HR objects have access to change salary field.   
If(p instanceof HR && newSalary>=0)    
//change salary.   
else   
 S.o.p("access denied");    
}

Imagine if salary was public and could be access directly any can change it however and whenever they want, this basically the significance of encapsulation

java - What is the use of encapsulation when I'm able to change the pr...

java encapsulation
Rectangle 27 29

It's a good question - but at some point, encapsulation in its purest form needs to be violated if the object is ever to have its dependency fulfilled. Some provider of the dependency must know both that the object in question requires a Foo, and the provider has to have a way of providing the Foo to the object.

Classically this latter case is handled as you say, through constructor arguments or setter methods. However, this is not necessarily true - I know that the latest versions of the Spring DI framework in Java, for example, let you annotate private fields (e.g. with @Autowired) and the dependency will be set via reflection without you needing to expose the dependency through any of the classes public methods/constructors. This might be the kind of solution you were looking for.

That said, I don't think that constructor injection is much of a problem, either. I've always felt that objects should be fully valid after construction, such that anything they need in order to perform their role (i.e. be in a valid state) should be supplied through the constructor anyway. If you have an object that requires a collaborator to work, it seems fine to me that the constructor publically advertises this requirement and ensures it is fulfilled when a new instance of the class is created.

Ideally when dealing with objects, you interact with them through an interface anyway, and the more you do this (and have dependencies wired through DI), the less you actually have to deal with constructors yourself. In the ideal situation, your code doesn't deal with or even ever create concrete instances of classes; so it just gets given an IFoo through DI, without worrying about what the constructor of FooImpl indicates it needs to do its job, and in fact without even being aware of FooImpl's existance. From this point of view, the encapsulation is perfect.

This is an opinion of course, but to my mind DI doesn't necessarily violate encapsulation and in fact can help it by centralising all of the necessary knowledge of internals into one place. Not only is this a good thing in itself, but even better this place is outside your own codebase, so none of the code you write needs to know about classes' dependencies.

Thanks for the detailed reply :) Would you know of a DI framework for .net that allows for private members to be injected into? Might Spring.net support this? How significant might the impact on performance be, as this mechanism relies on reflection?

Good points. I advise against using @Autowired on private fields; that makes the class hard to test; how do you then inject mocks or stubs?

I disagree. DI does violate encapsulation, and this can be avoided. For example, by using a ServiceLocator, which obviously does not need to know anything about the client class; it only needs to know about the implementations of the Foo dependency. But the best thing, in most cases, is to simply use the "new" operator.

@Rogerio - Arguably any DI framework acts exactly like the ServiceLocator you describe; the client doesn't know anything specific about Foo implementations, and the DI tool doesn't know anything specific about the client. And using "new" is much worse for violating encapsulation, as you need to know not only the exact implementation class, but also the exact classes and instances of all the dependencies it needs.

Using "new" to instantiate a helper class, which often isn't even public, promotes encapsulation. The DI alternative would be to make the helper class public and add a public constructor or setter in the client class; both changes would break the encapsulation provided by the original helper class.

oop - Must Dependency Injection come at the expense of Encapsulation? ...

oop dependency-injection inversion-of-control encapsulation