Smart constants

I've been really enjoying James Edward Gray II's Rubies in the Rough articles. Every couple of weeks, he publishes something that is guaranteed to get me thinking about some aspect of coding I hadn't considered before.


His latest article is part I of an exploration of an algorithm for the Hitting Rock Bottom problem posed by  by Gregory Brown & Andrea Singh. At its core, the problem asks you to simulate pouring water into a 2D container, filling it using a simple set of rules.


As I was coding up my solution, I found I had code like



Here " " is a cell containing air, and "~" a watery cell. So clearly we should create some named constants for that:



But it occurred to me that we could use Ruby's singleton methods to give AIR and WATER a little smarts:



Now you could argue that the cave object should do this: cave.watery?, or that the individual elements in the cave should be objects that know their moisture content, rather than simply characters. I don't agree with the first (simply because the cave is the container, and the water/air is the separate stuff that goes into that container). I have a lot of sympathy for the second, and I'd probably end up there given a sufficiently large nudge during a refactoring. 


But, for the problem at hand, simply decorating the two constants with a domain method seems to result in code that is a lot more readable. It isn't a technique I'd used before, so I thought I'd share.


(And remember to check out Rubies in the Rough…)

 •  0 comments  •  flag
Share on Twitter
Published on February 02, 2012 15:30
No comments have been added yet.