tags:

views:

66

answers:

5

I need to make sure that no object attribute is null and add defautl value in case if it is null. Is there any easy way to do this, or do I have to do it manually by cheking every attrute by its getter and setters?

+2  A: 

You can use reflection to iterate over the object's field, and set them. You'd obviously need some sort of mapping between types or even field names and required default values but this can be done quite easily in a loop. For example:

for (Field f : obj.getClass().getFields()) {
  f.setAccessible(true);
  if (f.get(obj) == null) {
     f.set(obj, getDefaultValueForType(f.getType()));
  }
}
Guss
+3  A: 

You need to manually filter input to constructors and setters. Well... you could use reflection but I wouldn't advise it. Part of the job of constructors and setters is to validate input. That can include things like:

public void setPrice(double price) {
  if (price < 0.0d) {
    throw new IllegalArgumentException("price cannot be negative " + price);
  }
  this.price = price;
}

and

public void setName(String name) {
  if (name == null) {
    throw new NullPointerException("name cannot be null");
  }
  this.name = name;
}

You could use wrapper functions for the actual check and throwing the exception.

cletus
Yeah, just specify default values when introducing the variables and/or in the constructor and then in each setter guard against passing in null.
Petri Pellinen
I won't throw a `NullPointerException` in case of `null` argument : it doesn't give any hint. I'll throw `IllegalArgumentException` in every case and let the JVM throw `NullPointerException` itself when it enconters one.I aggree not to use reflexion.
Jean-Philippe Caruana
See http://stackoverflow.com/questions/3881/illegalargumentexception-or-nullpointerexception-for-a-null-parameter for a discussion on this. Personally, I prefer to use `InvalidArgumentException` in both cases.
Pascal Thivent
Why not give a default value when initializing the variables?
Andrew Dyster
Let's not turn this into a `NullPointerException` vs `IllegalArgumentException` debate. That's been done to death. This ie neither the time nor the place.
cletus
A: 

You can create a function that returns a boolean value and checks every attribute. You can call that function to do the job for you.

Alternatively, you can initialize the object with default values. That way there is no need for you to do any checking.

Lucas T
A: 

Maybe check Hibernate Validator 4.0, the Reference Implementation of the JSR 303: Bean Validation.

This is an example of an annotated class:

public class Address {

    @NotNull 
    private String line1;
    private String line2;
    private String zip;
    private String state;

    @Length(max = 20)
    @NotNull
    private String country;

    @Range(min = -2, max = 50, message = "Floor out of range")
    public int floor;

        ...
}

For an introduction, see Getting started with JSR 303 (Bean Validation) – part 1 and part 2 or the "Getting started" section of the reference guide which is part of the Hibernate Validator distribution.

Pascal Thivent
A: 

I don't have enough context to give you a correct answer, but I'll suggest you to make you code immutable as much as possible. Use public final fields. No more getters or setters : every field has to be defined by the constructor. Your code is shorter, more readable and prevents you from writing code with side effects.

It doesn't prevent you from passing null arguments to your constructor though... You can still check every argument as suggested by @cletus, but I'll suggest you to throw IllegalArgumentException instead of NullPointerException that doesn't give no new hint about what you've done.

Anyway, that's what I do as much as I can and it improved my code (readability, stability) to a great extend. Everyone in my team does so and we are very happy with that. We learned that when we try to write some erlang code where everything is immutable.

Hope this helps.

Jean-Philippe Caruana