-1

I'm currently working on a project that will diminish a class that being used by other several classes.

if(condition_A)
{
     doSomething();
}
else if(condition_B)
{
     classToBeRemoved();
}
else
{
     doAnother();
}

The first solution that came up to me is to negate the condition of the if-else statement that will be modified.

if(condition_A)
{
     doSomething();
}
else if(!condition_B)
{
     doAnother();
}

This method of refactoring do not affect the functionality of the code but sometimes if the condition is too long, it affects the readability of the code.

Is there another way that will maintain the readability of the code other than negating the condition?

Rnine
  • 13
  • 3

1 Answers1

0

Maybe with functions, vaguely like:

List<BooleanSupplier> actions = new ArrayList<>();
actions.add(() -> {
    if (!condition_A) {
        return false;
    }
    doSomething();
    return true;
});
actions.add(this::canDoSomething);

if (!actions.stream().anyMatch(p::get)) {
    doAnother();
}

I took the liberty to abstract condition+action into a predicate, instead of using a Pair or such.

This is uglier, but could decouple things, as now the add's can come from outside the class, defining a public void addAction(BooleanSupplier action).

Though probably a parameter is needed to provide a data context (Predicate<?>).

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138