java - How to avoid if/else when using multple suppliers? -
is there way avoid using if/else statements when data can queried multiple locations , should returned on first non null instance?
i'm trying load preferences user 3 different locations (user preferences, group preferences , system preferences). example:
preference getpreference(user user, preference.type type) { preference preference = getuserpreferencefor(user, type); if (preference != null) { return preference; } preference = getgrouppreferencefor(user, type); if (preference != null) { return preference; } return getsystempreferencefor(user, type); }
i avoid using these if checks , chain these methods behavior remain same code wouldn't have ugly duplication.
i have thought of few solutions non of these strike elegant one. example, 1 way to have each of these methods provide default scatter if statements.
preference getpreference(user user, preference.type type) { preference preference = getuserpreferencefor(user, type); if (preference != null) { return preference; } return getgrouppreferencefor(user, type); } preference preference getgrouppreferencefor( if (preference != null) { return preference; } return getsystempreferencefor(user, type); }
another way use provider interface, create subclasses each , iterate on providers until first non null found.
public interface preferenceprovider { preference getpreference(user user, preference.type type); } public class userpreferenceprovider implements preferenceprovider { public preference getpreference(user user, preference.type type) { ... } } ... group , system provider same way final static preferenceprovider[] providers = new preferenceprovider[] { new userpreferenceprovider(), new grouppreferenceprovider(), new systempreferenceprovider() }; preference getpreference(user user, preference.type type) { preference preference = null; (preferenceprovider provider : providers) { preference = provider.getuserpreferencefor(user, type); if (preference != null) { return preference; } } }
the last 1 close enough still has null check (which i'd avoid) , i'm pretty confident there's design pattern solves problem. can't remember 1 ...
what about:
preference getpreference(user user, preference.type type) { preference preference = getuserpreferencefor(user, type); if (preference == null) { preference = getgrouppreferencefor(user, type); if (preference == null) { preference = getsystempreferencefor(user, type); } } return preference; }
it still uses if
s looks elegant enough me.
Comments
Post a Comment