Is there a clean/best way to set a variable inside a object only if its unassigned or null ?
Example: currently I am doing this.
if (item.getLocation() != null) {
item.setLocation("/somelocation");
}
Is there a clean/best way to set a variable inside a object only if its unassigned or null ?
Example: currently I am doing this.
if (item.getLocation() != null) {
item.setLocation("/somelocation");
}
This might be a good reason to use encapsulation. You could create a contract that ensures that assignment is only made if the items location is null. This prevents you from having to write the case code twice, and it will throw an exception if used in a way that breaks the contract you create.
public class Item {
// constructors, fields, methods
public void setLocationIfAbsent(String location) {
if (this.location != null) {
throw new IllegalStateException("Item already has a location, cannot re-assign.");
}
this.location = location;
}
}
Yes, there is a best way, assuming the object in question only offers a getter and setter for the field. It is the one you have written, except you want == null
.
Your current technique is functional but terrible. Only the item class cares whether or not the location is null. Put that logic in the setter for location. Here is some sample code:
public class Item
{
private String location;
public void setLocation(String newValue)
{
if (StringUtils.isEmpty(location))
{
location = newValue;
}
}
}
The user of the Item class can call the setLocation
method as many times as it chooses.