Skip to content

Commit

Permalink
Add a bit of module advice
Browse files Browse the repository at this point in the history
  • Loading branch information
Bozhidar Batsov committed Mar 27, 2013
1 parent b3034cb commit 4d1f83e
Showing 1 changed file with 61 additions and 3 deletions.
64 changes: 61 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -911,7 +911,7 @@ at all.
* Use other custom annotation keywords if it feels appropriate, but be
sure to document them in your project's `README` or similar.
## Classes
## Classes & Modules
* Use a consistent structure in your class definitions.
Expand Down Expand Up @@ -951,6 +951,64 @@ at all.
end
```
* Prefer modules to classes with only class methods. Classes should be
used only when it makes sense to create instances out of them.
```Ruby
# bad
class SomeClass
def self.some_method
# body omitted
end
def self.some_other_method
end
end
# good
module SomeClass
module_function
def some_method
# body omitted
end
def some_other_method
end
end
```
* Favor the use of `module_function` over `extend self` when you want
to turn a module's instance methods into class methods.

```Ruby
# bad
module Utilities
extend self
def parse_something(string)
# do stuff here
end
def other_utility_method(number, string)
# do some more stuff
end
end
# good
module Utilities
module_function
def parse_something(string)
# do stuff here
end
def other_utility_method(number, string)
# do some more stuff
end
end
```

* When designing class hierarchies make sure that they conform to the
[Liskov Substitution Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle).
* Try to make your classes as
Expand Down Expand Up @@ -1415,11 +1473,11 @@ strings.
heroes.fetch(:supermann)
```
* Use `fetch` with second argument to set a default value
```Ruby
batman = { name: 'Bruce Wayne', is_evil: false }
# bad - if we just use || operator with falsy value we won't get the expected result
# bad - if we just use || operator with falsy value we won't get the expected result
batman[:is_evil] || true # => true
#good - fetch work correctly with falsy values
Expand Down

0 comments on commit 4d1f83e

Please sign in to comment.