How to refactor long if-else condition

Vladislav Kopylov
1 min readJun 17, 2018

--

Photo by NESA by Makers on Unsplash

Sometimes you write a code with long if-else conditions. Rubocop doesn’t like it and will print offenses as:

Metrics/AbcSize: Assignment Branch Condition size for transform_for_machine is too high.
Metrics/MethodLength: Method has too many lines.
Metrics/PerceivedComplexity: Perceived complexity for transform is too high.

How to fix it? — Use Dictionary!

Example 1. We use if-else condition to return a value. Here is a function that takes one argument and returns a string or default string. Rubocop doesn’t like it and prints “Metrics/MethodLength: Method has too many lines. [13/10]”. We can refactor it easily.

Example 2. We can use if-else condition to manipulate an object. Here is a module that implements image conversion algorithm. It is just long if-else condition for choosing a right module. And here we could use a dictionary.

Example 3. If we have to refactor a difficult algorithm, we could use dictionary with procs. Here is an example of refactoring a searching algorithm.

And it is all. I hope the material is useful.

--

--

Vladislav Kopylov
Vladislav Kopylov

Responses (3)