Monday, 11 May 2015

Immutable Objects with Lombok - workshop

An immutable object is an object whose state cannot be modified after it is created.


Why Immutable Objects are important?


Because you have no total control : objects can be passed anywhere and can arrive from anywhere  in the code. If they are mutable, then any object can modify their state. Different threads can access the same model object and modify/read its state creating many problems difficult to handle.

What is an Immutable object?


Final private fields,  No Setters & Unmodifiable collections

An example ?



What does Lombok?


Project Lombok aims to reduce boilerplate codes by replacing them with a simple set of annotations.

How to install Lombok?


see here : https://projectlombok.org/download.html


Workshop :

Create a model object called Home with the following fields :   

String address;
The street name of your home

int age;
How old were you when you enter this house


int fromYear;
Which year you start living there
int toYear;
Which year you left


Create a toString() method to print the details.




Create a class called MyHomes that prints the list of Homes you lived in.   

This class should create as many homes you lived in and print the details for each one of them. 


Now make the class immutable

Now try to clean the Home class code with Lombok!!

Hints / Immutability support :-

val
@AllArgsConstructor
@Builder
@Value
@FieldDefaults



 
 How can we change a value? 

Add an immutable boolean field to indicate if the address has been verified.

Default should be false.

Add a method to MyHomes to verify a List of Homes


 Now try to use the @Wither annotation from Lombok!!




End of the workshop











Stretch content


































































No comments:

Post a Comment