text
stringlengths
0
444
# bad -- more work when class renamed/method moved
def self.call(param1, param2)
TestClass.new(param1).call(param2)
end
# bad -- more verbose than necessary
def self.call(param1, param2)
self.new(param1).call(param2)
end
# good
def self.call(param1, param2)
new(param1).call(param2)
end
# ...other methods...
end
----
=== Defining Constants within a Block [[no-constant-definition-in-block]]
Do not define constants within a block, since the block's scope does not isolate or namespace the constant in any way.
Define the constant outside of the block instead, or use a variable or method if defining the constant in the outer scope would be problematic.
[source,ruby]
----
# bad - FILES_TO_LINT is now defined globally
task :lint do
FILES_TO_LINT = Dir['lib/*.rb']
# ...
end
# good - files_to_lint is only defined inside the block
task :lint do
files_to_lint = Dir['lib/*.rb']
# ...
end
----
== Classes: Constructors
=== Factory Methods [[factory-methods]]
Consider adding factory methods to provide additional sensible ways to create instances of a particular class.
[source,ruby]
----
class Person
def self.create(options_hash)
# body omitted
end
end
----
=== Disjunctive Assignment in Constructor [[disjunctive-assignment-in-constructor]]
In constructors, avoid unnecessary disjunctive assignment (`||=`) of instance variables.
Prefer plain assignment.
In ruby, instance variables (beginning with an `@`) are nil until assigned a value, so in most cases the disjunction is unnecessary.
[source,ruby]
----
# bad
def initialize
@x ||= 1
end
# good
def initialize
@x = 1
end
----
== Comments
[quote, Steve McConnell]
____
Good code is its own best documentation.
As you're about to add a comment, ask yourself, "How can I improve the code so that this comment isn't needed?".
Improve the code and then document it to make it even clearer.
____
=== No Comments [[no-comments]]
Write self-documenting code and ignore the rest of this section. Seriously!
=== Rationale Comments [[rationale-comments]]
If the _how_ can be made self-documenting, but not the _why_ (e.g. the code works around non-obvious library behavior, or implements an algorithm from an academic paper), add a comment explaining the rationale behind the code.
[source,ruby]
----
# bad
x = BuggyClass.something.dup
def compute_dependency_graph
...30 lines of recursive graph merging...
end