Search code examples
javanulldefault

How to avoid returning null value (which should be default result) during iteration of a list?


I would like to have a method that iterate through a loop and if some condition is met then return a value ("1" in this case). The default value if condition is not true would be null. Is that fine to return null in such situation? What would be the cleanest solution to do that?

for (Obj1 obj1 : objects1) {
    for (Obj2 obj2 : objects2) {
        if (...) {
          return "1";
        }
    }
}
return null;

Solution

  • Kepotx's answer is one good way (returning true or false):

    boolean b = containsOne();
    if (b) {
        // Do something with success...
    } else {
        // Do something with failure...
    }
    
    private boolean containsOne() {
        for (Obj1 obj1 : objects1) {
            for (Obj2 obj2 : objects2) {
                if (...) {
                    return true;
                }
            }
        }
    
        return false;
    }
    

    However another way you could do this is with a try and catch block which is mentioned in Clean Code:

    try {
        int i = getOne();
        // Do something with success...
    } catch (Exception e) {
        // Do something with failure...
    }
    
    private int getOne() throws Exception {
        for (Obj1 obj1 : objects1) {
            for (Obj2 obj2 : objects2) {
                if (...){
                    return 1;
                }
            }
        }
    
        throw new Exception();
    }