DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
marlysson profile image
Marlysson Silva

Awesome approach and good arguments.

I don't know if you knows the "jsf" ( web programming in java ) , that some specific classes that requires the getters and setters ( convention over configuration ) to their internal implementations uses all structure of the application that use some implementation.

Do you know some advice about it? Or isn't related to the post and there aren't to do?

Collapse
 
scottshipp profile image
scottshipp

I think I should have tackled this in the article. You are going to be on the hook to use getters and setters for libraries (like JSF) that reflect on them. Can't really avoid that.

But you can avoid a dangerous anti-pattern (in my opinion), which is then passing such objects around inside the application.

Usually, Java libraries that use reflection on getters and setters are doing it to bind data to/from these objects. There is usually a specific intent behind this, such as to create a POJO from incoming data, such as from the JSON body of an http request.

I believe that this type of automatic object creation should be limited to a single place at the edge of the application. If the usual pattern is followed of turning around and passing the resulting object around inside the app, it creates a situation where changes in the JSON body (or whatever it is), makes you have to change all the code paths that the object travels across.

So its best if you can isolate and decouple these auto-generated objects from your application. Build walls around them and keep them at the edges.

Collapse
 
aminmansuri profile image
hidden_dude

There are ways around getters/setters/properties but they aren't very simple. Like using a visitor pattern or renderers. They definitely aren't popular and would confuse the average programmer.

For some things getters/setters, while not real OO, are a good solution. For example the way Hibernate handles DB properties, or ActiveRecord. As long as people remember to wrap these with real objects later that expose behavior instead of attibutes.