Smart Nodes all the time!
With Ruby, one of the topics/strategies that keeps coming up is the idea of pushing logic as far down the object tree as possible.
If you have an object tree in your program such as:
/---- Child Node Parent ----/
The parent is probably creating the child node to store information or in the case of some sort of linked list, to reference other nodes. When this happens I have found it to be extremely useful to use the child node as much as possible to perform logic and information processing. The parent will then just be calling methods on the child to get information.
For one of our projects at Turing we needed to traverse a Trei (Search tree). Instead of having the parent look through each of its children and grand children and grand grand children, I had the parent ask its
@head if it had the necessary information, then that same method on the
@head was asked the same question and on down the chain. Using recursive methods for this type of search allowed the results to roll back up the chain with all the info I was looking for.
In another project, we were recreating the game Battleship. While a straightforward way of storing the board was an array of arrays:
I used smart squares on the board. So instead of my board (
parent) knowing about the whole board, it only knew about
A1 knew about
B1 and so on and so forth (each knew its up, down, left, and right neighbors).
While creating this board the first time was somewhat complicated, it changed my AI’s move method from ~15 lines to two: