You have converted your domain
model into a fully functional web application. This application is already
quite useful on its own, although there are still many improvements you
can make. So let's transform your application into something more serious,
and by the way, let's learn some interesting things about OpenXava.
Let's start by learning some basic Java concepts like properties.
If you don't like videos follow
the instructions below.
Concepts
In order to understand some concepts well in this lesson you have to know
how properties work in Java. The standard way to define a property in Java
is:
// Property
private int quantity; // Has a field
public int getQuantity() { // A getter to return the field value
return quantity;
}
public void setQuantity(int quantity) { // Changes the field value
this.quantity = quantity;
}
This is based on the idea that you never should access the state
(the fields) of an object directly, but always calling methods. This is
very useful because you can change the implementation of a property
without affecting the code that uses it. Moreover, all tools, frameworks
and libraries from the Java ecosystem rely on this convention (part of
JavaBeans specification). Therefore, we should use this convention always.
A property in Java is a getter method (
getQuantity() for example)
and a setter method (
setQuantity(int quantity)) if the property is
modifiable. In fact, the field (
private int quantity in this case)
is not needed.
The problem of this approach is
that it is very verbose, a lot of the code of our classes are getters and
setters that really do not add value and make a lot of noise. To solve
this problem we use a library called Lombok. With Lombok you can define
the above
quantity property in this way:
@Getter @Setter // It generates a getter and a setter method
int quantity;
@Getter and
@Setter generate the getter and the
setter in the compiled code, so when you access the property you have to
use them, thus:
int q = theObject.getQuantity(); // Never int q = theObject.quantity
theObject.setQuantity(q + 10); // Never theObject.quantity = q + 10;
You can declare
@Getter and
@Setter at class level
so all the fields have getter and setter automatically. And of course, you
can write your own setter and getter if you want to use your own logic:
// @Data // NEVER USE @Data
@Getter @Setter
public class Issue {
int number;
String description;
public String getDescription() { // Your own getter overwrites the generated one by Lombok
if (description == null) return "No description yet";
return description;
}
}
In this case Lombok generates for you
getNumber(), setNumber()
and
setDescription() while
getDescription() is the one
written by you. Note as you never should use the
@Data annotation
of Lombok, given that it produces infinite recursive loops when you have
reciprocal references, something very usual in business applications.