Practical Object-Oriented Design in Ruby
All of code snippets below are examples from POODR and come from this repository.
Part 1 of those notes is here.
Here are hints on how to write better Ruby code I noted down. They are short and might be meaningless when out of context, but they may still bring some value or refresh your memory if you read the book.
OpenStruct in place of simple classes. Main difference is that
Struct takes initialization arguments
in order, and
OpenStruct accepts a hash from which it derives attributes.
attr_reader or private method in objects instead of instance variables.
It turns data into behaviour at once and by doing so it hides data:
fetch(args[:something], default) can be more handy than
args[:something] || default because
only when key wasn’t found.
default also when
Template Method Pattern
Template Method Pattern consists of a method that is used as default value. It is then overwritten in classes that inherit or include it:
Using hook methods allows subclasses to optionally override behaviour. This way you can remove
super calls and achieve less coupling:
Bicycle can be composed of
Parts which respond to
Parts holds many
Enumerable for classes like
Parts to make it act similar to Arrays.
I know that I’m praising POODR once again, but as you can see it contains not only design and architecture tips. There’s also a lot of practical advice on writing Ruby code. I noted down only those that were important for me at the time of reading, there are a lot of other hints that can’t be shortened to a note and are worth reading yourself.
You can find Part 1 of those notes here