views:

229

answers:

4

So I have function that formats a date to coerce to given enum DateType{CURRENT, START, END} what would be the best way to handling return value with cases that use switch statement

public static String format(Date date, DateType datetype) {
    ..validation checks

    switch(datetype){
    case CURRENT:{
        return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss");
    }               
    ... 
     default:throw new ("Something strange happend");
    }

}

OR throw excpetion at the end

   public static String format(Date date, DateType datetype) {
            ..validation checks

            switch(datetype){
            case CURRENT:{
                return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss");
            }               
            ... 
            }

               //It will never reach here, just to make compiler happy 
        throw new IllegalArgumentException("Something strange happend");    
        }

OR return null

public static String format(Date date, DateType datetype) {
            ..validation checks

            switch(datetype){
            case CURRENT:{
                return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss");
            }               
            ... 
            }

             return null;   
}

What would be the best practice here ? Also all the enum values will be handled in the case statement

+2  A: 

Throw an exception, since this is an exceptional case.

And throw it outside the switch, it would be more readable. Otherwise it sounds like "the default case is exceptional".

Bozho
Additionally, throwing the exception outside of the switch statement will allow a compile warning if you haven't covered all of the enum values as cases in the switch (or if the enum is later expanded).
ILMTitan
+1  A: 

I would go with the first approach (but with IllegalArgumentException as in your second approach). You should include a default statement to guard against cases when someone modifys (extends) your enum. Putting the exception in the default-statement makes clear to the reader that the code is never supposed to get past the switch-statement. Otherwise they would have to check if really all of the enum values are in the switch.

Space_C0wb0y
+1  A: 

Exceptions, as you can obey more to the parent than a single return int can. Usually you use Exceptions where they exist (C++), and return values where not (C).

penguinpower
+1  A: 

I think that throw new IllegalArgumentException("Something strange happend") is the best pratice.

Using null will just presumibly cause a NullPointerException somewhere when you use the return value but it will be less informative than raising a specific exception that describes the problem!

And you know: clear errors = better developing.

Jack