Skip to content

Commit fae7eda

Browse files
author
Bozhidar Batsov
committed
added an example about attr
1 parent d677d44 commit fae7eda

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

README.md

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -610,11 +610,12 @@ syntax.
610610
## Classes
611611
612612
* When designing class hierarchies make sure that they conform to the
613-
[Liskov Substitution Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle).
613+
[Liskov Substitution Principle](http://en.wikipedia.org/wiki/Liskov_substitution_principle).
614614
* Try to make your classes as
615615
[SOLID](http://en.wikipedia.org/wiki/SOLID_(object-oriented_design))
616616
as possible.
617-
* Always supply a proper `to_s` method.
617+
* Always supply a proper `to_s` method for classes that represent
618+
domain objects.
618619
619620
```Ruby
620621
class Person
@@ -632,7 +633,36 @@ syntax.
632633
```
633634

634635
* Use the `attr` family of functions to define trivial accessors or
635-
mutators.
636+
mutators.
637+
638+
```Ruby
639+
# bad
640+
class Person
641+
def initialize(first_name, last_name)
642+
@first_name = first_name
643+
@last_name = last_name
644+
end
645+
646+
def first_name
647+
@first_name
648+
end
649+
650+
def last_name
651+
@last_name
652+
end
653+
end
654+
655+
# good
656+
class Person
657+
attr_reader :first_name, :last_name
658+
659+
def initialize(first_name, last_name)
660+
@first_name = first_name
661+
@last_name = last_name
662+
end
663+
end
664+
```
665+
636666
* Consider adding factory methods to provide additional sensible ways
637667
to create instances of a particular class.
638668
* Prefer duck-typing over inheritance.

0 commit comments

Comments
 (0)