Search
⌘K
    to navigateEnterto select Escto close

    Extract statements into methods for clarity

    Let's see this example.

    1def sanitized_path
    2  s = request.path.downcase
    3
    4  # remove trailing slash
    5  s1 = s[-1] == '/' ? s[0..-2] : s
    6
    7  # strip .html
    8  s2 = s1[-5..-1] == '.html' ? s1[0..-6] : s1
    9
    10  # strip %20 at the end
    11  s2[-3..-1] == '%20' ? s2[0..-4] : s2
    12end
    13
    

    In the above code we have comments to help use understand what's happening. Instead of having the comment we can extract those statements into methods.

    The advantage of creating a new method is that we get an opportunity to give the method an english sounding name. The method name itself could reveal what's happening and we won't need comment.

    Let's extract the second statement into a method.

    1def sanitized_path
    2  s = request.path.downcase
    3
    4  s1 = remove_trailing_slash s
    5
    6  # strip .html
    7  s2 = s1[-5..-1] == '.html' ? s1[0..-6] : s1
    8
    9  # strip %20 at the end
    10  s2[-3..-1] == '%20' ? s2[0..-4] : s2
    11end
    12
    13def remove_trailing_slash(input)
    14  input[-1] == '/' ? input[0..-2] : input
    15end

    Now let's do the same to the next statement.

    1def sanitized_path
    2  s = request.path.downcase
    3
    4  s1 = remove_trailing_slash s
    5  s2 = strip_html s1
    6
    7  # strip %20 at the end
    8  s2[-3..-1] == '%20' ? s2[0..-4] : s2
    9end
    10
    11def remove_trailing_slash(input)
    12  input[-1] == '/' ? input[0..-2] : input
    13end
    14
    15def strip_html(input)
    16  input[-5..-1] == '.html' ? input[0..-6] : input
    17end

    Now let's do the same to the last statement.

    1def sanitized_path
    2  s = request.path.downcase
    3
    4  s1 = remove_trailing_slash s
    5  s2 = strip_html s1
    6  remove_trailing_percentage_20 s2
    7end
    8
    9def remove_trailing_slash(input)
    10  input[-1] == '/' ? input[0..-2] : input
    11end
    12
    13def strip_html(input)
    14  input[-5..-1] == '.html' ? input[0..-6] : input
    15end
    16
    17def remove_trailing_percentage_20(input)
    18  input[-3..-1] == '%20' ? input[0..-4] : input
    19end

    Now let's look at method sanitized_path.

    The whole method reads like a list of operations to be done. When we are looking at the method we are not interested in finding out how the work is done. Rather we are interested in seeing what is being done.

    If we want to look at how then we can get into the implementation of any of those methods.

    This is a much better solution, where we have both what and how.

    When statements are not extracted into methods then we only see what is being done. So every time we come back to this code we have to take a pause and build a mental model of what is being done by reading the code.

    Previous
    Next