text
stringlengths 0
444
|
|---|
Person.ancestors
|
# => [Person, Data, Object, (...)]
|
----
|
=== Duck Typing [[duck-typing]]
|
Prefer https://en.wikipedia.org/wiki/Duck_typing[duck-typing] over inheritance.
|
[source,ruby]
|
----
|
# bad
|
class Animal
|
# abstract method
|
def speak
|
end
|
end
|
# extend superclass
|
class Duck < Animal
|
def speak
|
puts 'Quack! Quack'
|
end
|
end
|
# extend superclass
|
class Dog < Animal
|
def speak
|
puts 'Bau! Bau!'
|
end
|
end
|
# good
|
class Duck
|
def speak
|
puts 'Quack! Quack'
|
end
|
end
|
class Dog
|
def speak
|
puts 'Bau! Bau!'
|
end
|
end
|
----
|
=== No Class Vars [[no-class-vars]]
|
Avoid the usage of class (`@@`) variables due to their "nasty" behavior in inheritance.
|
[source,ruby]
|
----
|
class Parent
|
@@class_var = 'parent'
|
def self.print_class_var
|
puts @@class_var
|
end
|
end
|
class Child < Parent
|
@@class_var = 'child'
|
end
|
Parent.print_class_var # => will print 'child'
|
----
|
As you can see all the classes in a class hierarchy actually share one class variable.
|
Class instance variables should usually be preferred over class variables.
|
=== Leverage Access Modifiers (e.g. `private` and `protected`) [[visibility]]
|
Assign proper visibility levels to methods (`private`, `protected`) in accordance with their intended usage.
|
Don't go off leaving everything `public` (which is the default).
|
=== Access Modifiers Indentation [[indent-public-private-protected]]
|
Indent the `public`, `protected`, and `private` methods as much as the method definitions they apply to.
|
Leave one blank line above the visibility modifier and one blank line below in order to emphasize that it applies to all methods below it.
|
[source,ruby]
|
----
|
# good
|
class SomeClass
|
def public_method
|
# some code
|
end
|
private
|
def private_method
|
# some code
|
end
|
def another_private_method
|
# some code
|
end
|
end
|
----
|
=== Defining Class Methods [[def-self-class-methods]]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.