Skip to content

Instantly share code, notes, and snippets.

@ki4jnq
Last active June 18, 2020 14:32
Show Gist options
  • Save ki4jnq/d933282e81bfbd4006fa297203a50b3f to your computer and use it in GitHub Desktop.
Save ki4jnq/d933282e81bfbd4006fa297203a50b3f to your computer and use it in GitHub Desktop.
Pragmatic Code Guidelines

What's This?

While often "good style" and idioms are language specific, some principles transcend language choice or personal preference. This is an attempt collect some of those practices in one place.

Control Flow

Extensive branching structures quickly become difficult to maintain. When you find yourself creating deeply nested structures, start looking for ways to break it down.

1. The happy path should follow the least amout of control flow possible

Consider the following code:

if current_user.signed_in?
  if current_user.admin?
    render "admin/landing_page"
  else
    render "user/landing_page"
else
  redirect_to "signin"
end

Instead of nesting two levels, we can change up some of our logic and flatten out the control:

redirect_to "signin" and return if !current_user.signed_in?

(WIP)

2. Try to break down large branching structures into lots of small structures in their own functions.

3. (OOP) Consider using interfaces and polymorphic types instead of if-else

4. (FP) Use Higher-order functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment