well i've a good question about verification of relationships.
Follows below the three classes to suppose the question:
public class Son {
private Integer idSon;
private String name;
private Father father;
}
public class Father {
private Integer idFather;
private String name;
private GrandFather grandFather;
}
public class GrandFather {
private Integer idGrandFather;
private String name;
}
Following these principies, let's suppose that we've to do relationships verifications, instead every time we do something like this "in differents parts of our code":
Son son = new SonBusiness().getById(idSon); //Get a Son from database
if(son.getFather == null){
throw new Throwable("Father's Son does not exist");
}
wouldn't be better create some method like:
public void verifySonsDatas(Son son, Bollean verifyFather, Boolean verifyGrandFather) throws Throwable{
if(son == null){
throw new Throwable("Son does not exist");
}
if(verifyFather){
if(son.getFather == null){
throw new Throwable("Father's Son does not exist");
}
}
and so on for any son's ralationships..
Somebody else agree that with this approach we avoid many redundant codes and we can concentrate the verification inside an unique method...?
If we think about 10 relations, imagine writting if(object == null) it does not appear be a good thing for me.
Thanks!
If null is part of the contract then I suppose yes creating a helper method is better than repeating the same code all over the place. However the much better alternative is to just avoid this in some way. For example consider the following:
Or if nulls are illegal then make the constructor the delegate for the exception:
If an object is invalid within its own specifications it makes more sense not to construct it at all.
Finally, you are checking for a null and throwing an exception:
So why bother? If nulls are illegal, why not get a NullPointerException?