Real example of the use of encapsulation

Asked

Viewed 337 times

5

I researched about encapsulation, I even read some topics here, but I haven’t seen a real example of how to use it in a way that can show me its advantages, what problems it avoids.

I have an attribute like public, but it is a custom of programmers to do it private and create their properties get and set. Well, but they never show a real example of a system they’ve already done, the advantages of using it and the problems that have occurred and been solved.

I saw examples on Youtube videos, but I don’t see why they changed the public to the private, do not demonstrate what problems they would avoid. I’ve read some articles, seen some videos, but I just wanted a real and objective example showing the variables for the private because it avoids this kind of problem and the advantages are exactly those.

  • Worst I’ve ever seen, it wasn’t clear to me that question, but I’ll see it again...

  • In these cases I always remember the classic example of the bank account. If you leave everything public and accessible from any part of the code, important fields such as balance can be accessed in an unwanted way by anyone, without the necessary security care. Therefore it is necessary that such fields are private and can be accessed only by geters and setters.

  • 1

    @Max I’m sorry to tell you that this is the wrong reason to encapsulate, the example is bad (I know everyone uses it, that’s why OOP is so misused around), and getter/Setter does not solve the problem. I will answer.

  • @Heyjoe Did the answer resolve what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?

2 answers

5

It is not an obligation for an object to have getter and Setter for each attribute field (but exposing them directly as audiences usually is even worse). You have to create these methods only when you need to directly expose the information (which usually shouldn’t be the intention) and it doesn’t need to be the pair, it can be for example only one of them.

Internal object fields are implementation details, along with the internal algorithms that manipulate them. In the spirit of object orientation is a more general principle that is to keep the implementation hidden and expose only a programming interface (a set of externally accessible methods - read private, in the case of Java) stable that allows manipulating and making use of this internal state, and that does not necessarily have a one-to-one relationship with the object fields.

A getter or Setter may be halfway in that direction if there is a need to actually expose this type of interface. The article Encapsulation is not information Hiding, which may interest you, cites the example of an object representing a geographical coordinate: latitude and longitude only admit certain ranges of values, and encapsulation helps to set them within valid limits. This is an example of setters validating the values received.

I don’t use so much setters, but do a lot of validation in constructors. If a parameter argument was incorrectly passed I already shoot for example a IllegalArgumentException: "you are trying to build wrong the object!" It is also a form of encapsulation.

In real projects I also used a getter that needed to return a copy of a collection (you know what it is, right? A class that stores elements, such as a list, a set, etc.). Inside the object was a collection of immutable elements. I wanted to return a subset of that collection or a copy of it, so that if the client code tried to modify the returned collection, it would not modify my original collection. Modifying the elements was already guaranteed that it would not be possible, because these were immutable. I then made a getter that returned a copy or subset of the collection. Done.

Another example: a getter that returned the connected status (true or false) of a central alarm. This central encapsulated a Socket Java and the connected information came from socket.isClosed(). Note that it is not a simple getCampo() or isCampo(). It does a processing, though minimal, which is to reverse the returned value (isClosed() returns if it is closed, I had a isConectada() that returns if the connection is open).

  • I already read calmly but I like the notation of the striped to indicate that the wrong term is used :)

  • @Maniero Believe me, it is more reminder for me than for others :P although we make so many mistakes we learn :)

5

You are right, most people follow these "recommendations" because they have seen it somewhere and they are "teaching" other people also do not know why they do it. Some think they know.

In fact the answers given in link above rray shows well that getter and Setter alone cannot be considered encapsulation. Just because you left a field (and not attribute) private doesn’t mean it’s encapsulating something, especially when it puts a getter and Setter straight to him without thinking about what he’s doing.

I am increasingly convinced that getter/Setter and other methods that serve as a bulkhead to access the real state is abstraction and not encapsulation. Okay, I know it won’t be well accepted because the definition that is common in our environment says that this mechanism is encapsulation. So I don’t expect people to change their vision, and I’m not gonna insist on it. It seems to me that encapsulation is to leave everything necessary to the object in the object itself. If anyone asks more about, I can give an answer.

What is the point of having a private field and a couple of methods that normally access the field in the same way that it would be directly accessed? How can this be encapsulation? I think it can be abstraction, because abstraction presupposes that concrete internal mechanism doesn’t matter.

Encapsulation has to do with the fact that the behavior to change the state of the object is next to the object itself. Then there will be a method that will make the change or access to the value of the field. But nothing says it should be getter or Setter. And to me that violates the larger abstraction of the object because it’s just a bulkhead for the implementation detail, it helps, but it doesn’t completely solve the problem of mater the concept of the generic object, you’re not exposing the implementation detail but you’re exposing how this detail is, which almost equals.

But it can be too. If the only behavior to access/change the field is directly related to the state in a pure and simple way, fine. The important thing for encapsulation is that the behavior that allows the access/ mutation of the field is in the same object.

There is a chain that preaches that should never have methods setters and maybe not even getters. These people say, and I’m even right, that there should be methods that dictate certain actions that will manipulate the state in some way, but not something so direct.

I disagree a little bit because there are many cases that the only thing you should do with the field is change its value, and a lot of the time to pick up some data is just take the value of the field.

Of course, the people abuse, even for not understanding how to apply this technique correctly. When a class is full of getters and mainly setters There really must be something wrong. So I prefer a simple anemic model.

To illustrate using the max motivator in the comments above: you should not have one getSaldo() and setSaldo(), must have a Depositar() and Sacar(), among other methods that can change the balance. Maybe a getSaldo() makes sense, but a simple change of method name can give another impression, something like ObtemSaldo() or PedeSaldo(). Need to understand what is operation to give good names, one of the things I like in DDD :).

Note that the method Sacar() does much more than just fiddle with the balance, it is not a simple Setter, beyond the obviousness that it does not change the balance directly, it will make a subtraction.

I made an example in What is the relationship between encapsulation and polymorphism?. I think it serves as the requested example.

If you use a constructor properly then you have a very low need to use setters. The validation there can be considered as a encapsulation as said Piovezan in his reply, after all it is close to its object.

For me the biggest mistake of using these mechanisms is to be just a bulkhead for the field as it is almost all getters and setters I see being used.

Often the appropriate way to get information is to take a set and not just a field, there would also enter the same idea that the method should not only return the state of a field. Of course, to do this will probably create a complication because you may have to create a class just to support the set of fields that will return in a given situation.

Still following Piovezan’s reply, even though he used the term getXXX() in some method, I do not know if all can be considered as getters. If it returns a subset of a collection of data, is that by itself no longer a method with a special meaning? Calling something getter means that it has no function beyond giving a value, no specific semantics, it becomes part of the mechanism of the object and not of its meaning.

Note that some languages offer better mechanisms to work with these things, such as properties and tuples.

I know this is a complicated thing to explain, abstractions are poorly understood by humans. Imagine creating the right abstractions, so I say OOP is very difficult. I need to find a way to better explain mechanism and semantics.

  • I’m gonna defend my getter. The principle of encapsulation dictates that implementation is separated from the interface provided by the object. So although the getter should return information from the object, there is no obligation for it to return a field. This information could be generated in real time, for example. In the case it is being generated from the values of a field, and although it is not the case to call getCampo(), she is still a getAlgumaCoisa() (as in the case were getSetoresInibidos()). In any case, I will withdraw from the reply, or exchange for another example.

  • You’re right about that, maybe I wasn’t so clear, it’s not typical getter. I think he’s more than one getter, besides being a getter, it has meaning, it functions as something more useful to the object than a getter. I didn’t say it was your mistake and I don’t think you should take it back. I will try to improve, but first I need to research a little, because it is these answers that will make me think a lot and conclude interesting things.

  • Just an idea that can help more lay people (like me) to understand: an object application that does not have "typical getter and Setter" in something more common, such as user system, products, employees etc. In my opinion, simple getter and Setter are very used because most systems are relatively simple

  • @Guilhermecostamilam you’re right, I just don’t understand why someone uses OOP in a simple system. OOP is for managing complexity.

  • Personally I do not use OOP nor in complex system (except native android application), in PHP I use more functions separated only by files (organization) and array to save data, in JS when I need an object, to send to the database for example, create an anonymous with {var1: 'var 1', ...}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.