Tuesday 18 December 2012 21:01
When exploring unfamiliar ideas, the best approach is often to take them to the extreme. For instance, suppose you're trying to follow the principle "tell, don't ask". I've often found it tricky to know where to draw the line, but as an exercise, try writing your code without a single getter or setter. This may seem ludicrous, but by throwing pragmatism completely out the window, you're forced to move outside your comfort zone. While some the code might be awful, some of it might present ideas in a new way.
As an example, suppose I have two coordinates which represent the top-left and bottom-right corners of a rectangle, and I want to iterate through every integer coordinate in that rectangle. My first thought might be:
def find_coordinates_in_rectangle(top_left, bottom_right): for x in range(top_left.x - 1, bottom_right.x + 2): for y in range(top_left.y - 1, bottom_right.y + 2): yield Coordinate(x, y)
Normally, I might be perfectly happy with this code (although there is a bit
of duplication!) But if we've forbidden getters or setters, then we can't
y values from each coordinate.
Instead, we can write something like:
def find_coordinates_in_rectangle(top_left, bottom_right): return top_left.all_coordinates_in_rectangle_to(bottom_right)
The method name needs a bit more thought, but the important difference is that we've moved some of the knowledge of our coordinate system into the actual coordinate class. Whether or not this turns out to be a good idea, it's food for thought that we might not have come across without such a severe constraint as "no getters or setters".
Topics: Software design