java beans = default constructor + getters + setters
You want to model a person and in your model each person must have a name and surname.
In java beans convention you would have to
1) create a person and then
2) populate it with name and surname.
But in between 1 and 2 you have existing object that has inconsistent state, its a person without a name. in this trivial example it looks as a exaggeration but if you have a complex system it starts to matter.
Let’s see simple example
class Person { private String firstName; private String lastName; public String getFirstName() {return firstName;} public void setFirstName(String firstName) {this.firstName = firstName;} public String getLastName() {return lastName;} public void setLastName(String lastName) {this.lastName = lastName;} }
The code creates instance of Person an initiates it:
Person president = new Person(); p.setFirstName("George"); p.setLastName("Bush");
From the above line of code the below can be incurred
- This means that the object is in constant state when all 3 lines are completed and in not consistent state before that.
- The object is indeed mutable: values that it calls may be changed by invoking of setter.
Our class Person is not thread-safe and therefore we cannot use it directly in multi threaded environment without thinking about syncrhonization.
Here is an example. Several years ago Barak Obama became the President of the US. How can we express this in code?
p.setFirstName("Barak"); p.setLastName("Obama");
In mutlti threaded environment the president object is in wrong state when when setFristName() had already completed and setLastName() has not called yet because the object contains “Barak Bush” that is obviously wrong.
What is the solution? Let’s make `Person immutable:
class Person { private final String firstName; private final String lastName; Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() {return firstName;} public String getLastName() {return lastName;} }
As you can see there is not way to change either first or last name stored in object. The fields a final and do not have setters. So, our example looks like:
Person president = new Person("George", "Bush"); // elections..... president = new Person("Barak", "Obama");
Since Person is immutable we cannot re-use the old instance of Person and change its attribute. We have to create the new instance instead. If president is volatile reference assignment is atomic and therefore the code is thread safe.
Disadvantage
The problem of constructors is that they are not flexible. Our example has only 2 parameters. But think about real world when class Person has probably 20 or more field. In this case creating of such object is pretty verbose.
Moreover some fields can be optional. In this case you will probably want to create several overloaded constructors with different number of parameters. To avoid dupplicate assignemnt code it is common technique to use so called telescopic constructors
Few FAQ’s
Is using JavaBeans for data storage a bad practice and should be avoided, or is it perfectly safe?
No, is not a bad practice. Is not perfectly safe either. Depends on the situation.
The problem with mutable objects ( not with JavaBeans per se ) is using different threads to access them.
You have to synchronize the access to avoid one thread modify the object while other is accessing it.
Immutable objects doesn’t have this problem, because, .. well they can’t change, and thus, you don’t have to synchronize anything.
To make sure an object is immutable you have to declare your attributes as final.
class MyBean { private final int i; }
If you want to assign a reasonable value to MyBean.i you have to specify it in the constructor:
public MyBean( int i ) { this.i = i; }
Since the variable is final, you can’t use a setter. You can just provide a getter.
This is perfectly thread-safe and the best is, you don’t have to synchronize the access, because if two threads try to get the value of i they both will always see the value that was assigned on instantiation, you don’t have to synchronize anything.
Is not bad practice or good practice. Must of us have to work with a single thread, even in multithread environments like servlets.
How to set and change values if Immutable Objects
The Solution is to create immutable beans, and still provide a
bunch of setters is using Builders like
Setting Value
Employee e = new EmployeeBuilder() .setName("Oscar") .setLastName("Reyes") .setAge(0x1F) .setEmployeeId("123forme") .build();
Which looks pretty similar to the regular setXyz used in regular beans with the benefit of using immutable data.
If you need to change one value, you can use a class method
Employee e = Employee.withName( e, "Mr. Oscar");
Which takes the existing object, and copy all the values, and set’s a new one….
public static EmployeeWithName( Employee e , String newName ){ return new Employee( newName, e.lastName, e.age, e.employeeId ); }
But again, in a single thread model is perfectly safe to use getters/setters.