java - Checking error value after each step -
i have following java method:
public error mymainmethod() { error ret = invokefirstsub(); if (ret != error.no_error) { return ret; } ret = invokesecondsub(); if (ret != error.no_error) { return ret; } // rest }
basically, after each sub invocation check return value , exit when error occurs. how can refactored? first idea put whole invocation sequence inside try-catch loop, asserts , catch first assertionerror, don't find quite elegant. practice?
based on refactoring practices there 2 improvements possible:
avoid multiple return statements (makes code readability clumsy large method having many return statements)
encapsulate logic wherever possible i.e. move error checking logic method
iserror()
inside error enumpublic error mymainmethod() {
error ret = invokefirstsub();
ret = (ret.iserror()) ? ret : invokesecondsub();
ret = (ret.iserror()) ? ret : invokethirdsub();
// on , finally
ret = (ret.iserror()) ? ret : error.no_error;
// rest
return ret; }
further noted strategy pattern might fit though based on feasibility in case in managing subs 1 per class or subs in class.
Comments
Post a Comment