Most of the time when you create a Java bean you add all properties as private fields and create a public getter and setter for each field. In this post I will tell you why this isn’t good practices and how you can make it better.
Why getters and setters are most of the time not necessary?
Most getters and setters will just return the value they are created for. This results in huge files with a lot of unnecessary code. The benefit of such getters and setters is not really given. It just makes the code less readable.
A much better approach is to make all fields publicly available so that they can be accessed from outside. To make the beans more robust you should also implement a builder for each bean.
What’s the builder pattern?
A builder can be used to configure a bean and then return a final version of it. The huge benefit of this pattern is that your beans get immutable. This will prevent developers to set values after a bean was created. If this has be done, a new bean has to be created.
The builder for a certain bean contains private instances of all fields the bean to create also contains. They are typically exposed them using a fluent interface.
This way the builder can be configured in a very readable way. When everything is done the actual bean can be built using the build method of the builder.
You can then use the builder to create the build like this:
The project is also hosted on GitHub.