Skip to content

Instantly share code, notes, and snippets.

@garyharan
Created November 3, 2023 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garyharan/b25e20ffb96684df8223836a7838eddc to your computer and use it in GitHub Desktop.
Save garyharan/b25e20ffb96684df8223836a7838eddc to your computer and use it in GitHub Desktop.
Ways to improve your coding practices

Best Practices when coding

Bring display logic down the line when you can

If your template has lots of ifs about what kind of models you have you may want to generisize the display portion.

One example is that instead of this:

class Car
  def url
    DisplayModule.display_url(self)
  end 
end

class Motorcycle
  def url
    DisplayModule.display_url(self)
  end
end

module DisplayModule
  def display_url(vehicle)
    if vehicle.class == Car
      "https://repo.com/car.png"
    else if vehicle.class == Motorcyle
      "https://repo.com/motorcycle.png"
    end
  end
end

You would be better off with this:

class Car
  def url
    DisplayModule.display_url("car.png")
  end 
end

class Motorcycle
  def url
    DisplayModule.display_url("motorcycle.png")
  end
end

module DisplayModule
  def display_url(file_path)
    "https://repo.com/#{file_path}"
  end
end

The code is functionally equivalent but you remove one if clause and now the display module's complexity does not need to grow if we add another type of vehicle.

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