Skip to content

Commit faaae80

Browse files
author
Bozhidar Batsov
committed
added a bunch of examples
1 parent efd39f7 commit faaae80

File tree

1 file changed

+70
-3
lines changed

1 file changed

+70
-3
lines changed

README.md

Lines changed: 70 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -664,10 +664,77 @@ mutators.
664664
```
665665

666666
* Consider adding factory methods to provide additional sensible ways
667-
to create instances of a particular class.
668-
* Prefer duck-typing over inheritance.
667+
to create instances of a particular class.
668+
669+
```Ruby
670+
class Person
671+
def self.create(options_hash)
672+
# body omitted
673+
end
674+
end
675+
```
676+
677+
* Prefer [duck-typing](http://en.wikipedia.org/wiki/Duck_typing) over inheritance.
678+
679+
```Ruby
680+
# bad
681+
class Animal
682+
# abstract method
683+
def speak
684+
end
685+
end
686+
687+
# extend superclass
688+
class Duck < Animal
689+
def speak
690+
puts 'Quack! Quack'
691+
end
692+
end
693+
694+
# extend superclass
695+
class Dog < Animal
696+
def speak
697+
puts 'Bau! Bau!'
698+
end
699+
end
700+
701+
# good
702+
class Duck
703+
def speak
704+
puts 'Quack! Quack'
705+
end
706+
end
707+
708+
class Dog
709+
def speak
710+
puts 'Bau! Bau!'
711+
end
712+
end
713+
```
714+
669715
* Avoid the usage of class (`@@`) variables due to their "nasty" behavior
670-
in inheritance.
716+
in inheritance.
717+
718+
```Ruby
719+
class Parent
720+
@@class_var = 'parent'
721+
722+
def self.print_class_var
723+
puts @@class_var
724+
end
725+
end
726+
727+
class Child < Parent
728+
@@class_var = 'child'
729+
end
730+
731+
Parent.print_class_var # => will print "child"
732+
```
733+
734+
As you can see all the classes in a class hierarchy actually share one
735+
class variable. Class instance variables should usually be preferred
736+
over class variables.
737+
671738
* Assign proper visibility levels to methods (`private`, `protected`)
672739
in accordance with their intended usage. Don't go off leaving
673740
everything `public` (which is the default). After all we're coding

0 commit comments

Comments
 (0)