Skip to content

Files

Latest commit

6c3f23e · Sep 21, 2019

History

History
38 lines (29 loc) · 1.06 KB

nested-loops-and-conditionals.md

File metadata and controls

38 lines (29 loc) · 1.06 KB

Nested Loops And Conditionals

Also known as the "Arrow Anti-Pattern".

What It Looks Like

if logged_in?
  tokens.each do |token|
    if token != current_session.token
      token.expire!
    end
  end
end

Why It Hurts

Code in loops and conditionals tends to conflate data transformation with side effects. This is because there's no way for a loop or an if to affect the rest of the system unless it has a side effect. As a result, it's hard to see at a glance what the code is doing, and where it might be unsafe to insert new code or reorder statements.

How To Fix It

Use Replace Loop with Pipeline to separate data transformation from side effects. Additionally, Replace Inline Code with Function Call and Extract Method can help abstract away complex boolean logic in conditionals.

References