15. Making the Parts more like an Array
▸ Add size method in to Parts class manually
▸ How about each, sort and more…
▸ Let Parts inherit Array
▸ Some behaviors may not be expected !!
▸ There is no perfect solution
16. A middle ground between complexity and usability
1 require 'forwardable'
2 class Parts
3 extend Forwardable
4 def_delegators :@parts, :size, :each
5 include Enumerable
6
7 def initialize(parts)
8 @parts = parts
9 end
10
11 def spares
12 parts.select(&:needs_spare)
13 end
14 end
17. Knowledge leakage
1 chain = Part.new(name: 'chain', description:
2 '10-speed')
3 road_tire = Part.new(name: 'tire_size',
4 description: '23')
5 tape = Part.new(name: 'tape_color', description:
6 'red')
7
8 road_bike = Bicycle.new(
9 size: 'L',
10 parts: Parts.new([chain,
11 road_tire,
12 tape])
13 )
Need knowledge of how to create part
Need to know road bike’s all parts
18. Manufacturing parts
▸ Everything would be easier if you could describe the
different bikes and then use your descriptions to magically
manufacture the correct Parts object for any bike.
▸ 2-dimensional array
▸ Unlike a hash, this simple 2-dimensional array provides
no structural information.
23. Inheritance: What will happen when I’m wrong?
▸ That is, Incorrectly modeled hierarchy
▸ Making small changes near the top of hierarchy break
everything.
▸ You will be forced to duplicate or restructure code.
▸ Impossibility of adding behavior when new subclasses
represent a mixture of types.
▸ Might be used by others for purposes you did not anticipate
24. Using Inheritance when satisfied …
▸ Reasonable
▸ Big changes in behavior can be achieved via small
changes in code.
▸ Usable
▸ Easily create new subclasses.
▸ Exemplary
25. Drawbacks of Mixin
▸ Too powerful, so its easy to abuse.
▸ Refactoring anti-pattern: God object
▸ You still have one object with the same number of
public methods.
▸ The rules of coupling and cohesion start to come into
play
26. How about composition
▸ Small objects, SRP, transparent.
▸ Simple and pluggable objects that are easy to extend and
have a high tolerance for change.
▸ Cost of management small parts collection, but relatively
easy to control.
27. Concepts
▸ Inheritance
▸ Subclass Is-A specialization of Superclass.
▸ Mixin
▸ Class A take A Role Of Module B (Module B is Adjective)
▸ Composition
▸ Class A Has-A class B
28. Conclusion
▸ Can't figure out what to do? Use composition.
▸ The key to improving your design skills is to attempt these
techniques, accept your errors cheerfully, remain detached
from past design decisions, and refactor mercilessly.
29. Reference
▸ Re-use in OO: Inheritance, Composition and Mixins.
▸ Composition over Mixins
▸ Factory pattern - Design patterns in ruby