DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
scottshipp profile image
scottshipp

What do you have in mind exactly? Getters and setters can violate both the Law of Demeter and SOLID principles. The Interface Segregation Principle, which is the I in SOLID, states that no client should be forced to depend on methods it does not use. A bunch of extra methods that expose a class' data are often methods that clients shouldn't depend on.

As for the law of demeter, a getter is actually a classic and oft-cited example of demeter violation. Let's say you have an ecommerce site and its time for the customer to pay for the order. In the violation example, you take the customer's wallet (customer.getWallet()) and then you subtract the money out of it (wallet.deduct(orderAmount)). Picture this as a transaction in real life. You ask the customer to pay, they hand you their entire wallet and you reach in. This is meant to illustrate the need for the Law of Demeter. Google "law of demeter wallet" and you'll see what I mean.

Collapse
 
schrammel profile image
Schrammel

About SOLID:

In my opinion, by using a getter you can only break "Interface Segregation" if you break the "Liskov Substitution"

About LAW OF DEMETER:

the correct thing is that the customer makes the payment, and keep it for him, after all, it is not the wallet that pays, but the customer.

Code:
Custumer.deduct (orderAmount)


You said right at the beginning of the article.

"Now, I want to point out that there is no meaningful functional difference between that class, a public class with a public class member, and the following class, a public class with a private member that is exposed by getters and setters."

But I say:

Imagine that you use this code in 10 locations

car1.engine = new HemiEngine();

Now you need to enter a validation when changing the engine of the car. you will have to change the code in several places because you broke Demeter's law.

About changing engine properties

  • Single Responsibility: Ideally a class would encapsulate a property change, without getters there is no way to use a logic injected into the constructor
  • Integrity, with getters you can return a copy of the values ​​of your engine. Both of these reasons force you not to create public fields.