Home > OS >  What's the cleanest way to organize if/else blocks for assigning a variable from multiple poten
What's the cleanest way to organize if/else blocks for assigning a variable from multiple poten

Time:04-29

What's the cleanest way to sequentially attempt to assign a variable from a dataset, moving to the following if the former returns null or is empty? I'm working in Java.

Pseudo code:

I know .contains exists for maps; the real code I'm working with isn't a map, but this should give a decent illustration.

Object variable = firstmap.get(key);
if (variable == null) {
  variable = secondmap.get(key);
  if (variable == null) {
    variable = thirdmap.get(key);
    if (variable == null) {
      ...
    }
  }
}

I could break this up like this, sure, but it still doesn't seem great:

Object variable = firstmap.get(key);
if (variable == null) {
  variable = secondmap.get(key);
}
if (variable == null) {
  variable = thirdmap.get(key);
}
if (variable == null) {
  ...
}
...

Is there a cleaner way? Having a true brain burp.

CodePudding user response:

What you're doing is known as a "coalesce". You could try something like this:

public <T> T coalesce(T ... values) {
    for (T value : values) {
      if (value != null) {
         return value;
      }
    return null;
}

And set the variable with

variable = coalesce(firstMap.get(key), secondMap.get(key), thirdMap.get(key));

CodePudding user response:

You could try this:

Object variable;
boolean found =
    (variable = firstmap.get(key)) != null ||
    (variable = secondmap.get(key)) != null ||
    (variable = thirdmap.get(key)) != null ||
    ...
    (variable = nthmap.get(key)) != null;

It will only check the maps until it gets to the first one that contained the key because || is short circuiting.

  • Related