0

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");
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Voila
  • 306
  • 2
  • 5
  • 16
  • 3
    Should that be `if (item.getLocation() == null)` ? – khelwood Apr 26 '21 at 18:44
  • 1
    Probably it's good answer for you https://stackoverflow.com/questions/271526/avoiding-nullpointerexception-in-java – M. Dudek Apr 26 '21 at 18:44
  • If you might have multiple threads operating on the location, consider explicitly synchronizing, or using `AtomicReference.getAndUpdate()` or `updateAndGet()`. – Andy Thomas Apr 26 '21 at 18:44
  • 1
    Does this answer your question? [Is there a standard function to check for null, undefined, or blank variables in JavaScript?](https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in) – charlie scott Apr 26 '21 at 18:49

3 Answers3

0

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;
    }
}
Jason
  • 5,154
  • 2
  • 12
  • 22
0

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

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.

DwB
  • 37,124
  • 11
  • 56
  • 82