mardi 19 décembre 2017

Checking an object is correctly built in Java

This is a general issue/problem that I have come across. I wondered if anyone knows of any well suited design patterns or techniques.

private ExternalObject personObject; 
private String name;
private int age;
private String address;
private String postCode;

public MyBuilderClass(ExternalObject obj)
     this.personObject=obj;
     build();
}

public build() {
    setName(personObject.getName());
    setAge(personObject.getAge());
    setAddress(personObject.getAddress());
    setPostCode(personObject.getPostCode());
    .
    .
    . many more setters
}

The class above takes external objects from a queue and constructs MyBuilderClass objects.

A MyBuilderClass object is successfully built if all of the fields have been set to non-null non-empty values.

There will be many MyBuilderClass objects that cannot be built because data will be missing from the ExternalObject.

My problem, what is the best way to detect if an object has been correctly built?

  • I could check for null or empty values in the set methods and throw an exception. The problem with this approach is throwing exceptions is expensive and it will clogg the log files up because there will be many instances where an object cannot be built;

What other approaches could I use?

Aucun commentaire:

Enregistrer un commentaire