Search code examples
ruby

is there any way to write conditional statements cleaner if/else


I have an if-else-statement that I would like to make more DRY.

if flag?
  box? && ball?
else
  box?
end

And maybe I have another statement that looks like this

if flag?
  box? && ball? 
else
  box? && ball? && bat? 
end

How to clean up those conditions and make them look more DRY?


Solution

  • To simplify conditions like these, it sometimes helps to write them verbose and then transform them step by step, following the De Morgan's laws.

    if flag?
      box? && ball?
    else
      box?
    end
    

    can be written as

    (flag? && box? && ball?) || (!flag? && box?)
    

    Because box? must be true in both cases, you can check first before the other conditions.

    box? && ((flag? && ball?) || (!flag?))
    

    Which can be transformed to

    box? && (!flag? || ball?)
    

    The other expression can be transformed, following the same steps:

    if flag?
      box? && ball? 
    else
      box? && ball? && bat? 
    end 
    

    Write as verbose condition

    (flag? && box? && ball?) || (!flag? && box? && ball? && bat?)
    

    and transform

    (box? && ball?) && ((flag?) || (!flag? && bat?))
    

    ending up with

    box? && ball? && (flag? || bat?)