Created
June 27, 2014 18:40
-
-
Save JacobNinja/c5d147cab78a7d2a47a6 to your computer and use it in GitHub Desktop.
Ruby anti-patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# For loop | |
# suggested: replace with each | |
for i in x | |
end | |
# each_with_object mutates array | |
# suggested: replace with map | |
each_with_object([]) |list, i| | |
list << i | |
end | |
# array set by index | |
array = [] | |
array[2] = 'foo' | |
# multiple return statements | |
return true if foo | |
return true if bar | |
# calling methods in initialize | |
# suggested: create a constructor to process the arg before initializing | |
def initialize(arg) | |
@arg = process_arg(arg) | |
end | |
# next in iter | |
# suggested: use select/reject to filter collection before iterating | |
each do |i| | |
next if i == "bar" | |
end | |
# type sniffing | |
# suggested: interface | |
foo.is_a?(Bar) | |
foo.kind_of?(Bar) | |
# hash ||= for initial value | |
# suggested: override hash constructor | |
foo[bar] ||= 0 | |
foo[bar] += 1 | |
# ternary returns true or false when invoking boolean operation | |
# suggested: ternary is not necessary | |
foo == bar ? true : false | |
# Array#delete | |
# suggested: select/reject | |
foo.each do |i| | |
foo.delete(i) if bar | |
end | |
# variable reassignment | |
# suggested: control flow (if/case) | |
result ||= 'foo' if bar | |
result ||= 'bar' if foo | |
result = 'baz' unless result | |
# setting instance variables outside of setters/initialize | |
def foo | |
@bar = rand(25) | |
end | |
# duplicate return values | |
# suggested: combine statements with a boolean or | |
if foo | |
return 'foo' | |
elsif bar | |
return 'foo' | |
else | |
return 'bar' | |
end | |
# boolean parameters | |
def foo(should_do_something=false) | |
do_something if should_do_something | |
end | |
# string concatenation | |
# suggested: use Array#join | |
time = day + hour + ":" + min | |
# inject/reduce: mutate and return memo | |
# suggested: use each_with_object instead | |
foo.inject([]) do |m, i| | |
m << i | |
m | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment