Category Archives: Uncategorized

Best practice passing options to methods

Here’s a simple issue that can be solved quite simply. A complaint a developer made once of my code was a good one: try to avoid passing booleans as method parameters because they don’t convey meaning. Example:

 public void applyMagic(String spell, boolean wideArea, boolean greenSmoke, boolean loudNoise);

The call would look like this:

applyMagic(“3wishes”, true, false, true);

The problem is, if you’re just reading the method call and unfamiliar with the method declaration (and possibly, even if you are), what the heck does “true, false, true” mean? It’s ambiguous and does not convey intent. The proper way to refactor this method declaration is to force the passing of symbolic values that do convey meaning.

One of the simplest and nifty ways to do this is to pass a variable length array of enum options. For example:

public enum Options {

public void applyMagic(String spell, Option… opts {
List<Option> options = Arrays.asList(opts);
boolean optWideArea = options.contains(WIDE_AREA);
boolean optGreenSmoke = options.contains(GREEN_SMOKE);
boolean opt_LOUD_NOISE = options.contains(LOUD_NOISE);

where the new method call then becomes:

applyMatgic(“3wishes”, WIDE_AREA, GREEN_SMOKE, LOUD_NOISE);

Much more informative and clear, right?