The Artima Developer Community
Sponsored Link

Agile Buzz Forum
Smart constants

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Dave Thomas

Posts: 85
Nickname: pragdave
Registered: Mar, 2003

Dave Thomas is...
Smart constants Posted: Feb 9, 2012 6:34 PM
Reply to this message Reply

This post originated from an RSS feed registered with Agile Buzz by Dave Thomas.
Original Post: Smart constants
Feed Title: PragDave
Feed URL: http://pragdave.blogs.pragprog.com/pragdave/atom.xml
Feed Description: The 'Practices' section of Dave Thomas's blog, including stuff on design, architecture, and the Code Kata exercises.
Latest Agile Buzz Posts
Latest Agile Buzz Posts by Dave Thomas
Latest Posts From PragDave

Advertisement

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…)

Read: Smart constants

Topic: Come to the Open Source Bridge conference Previous Topic   Next Topic Topic: Pair Programming Benefits

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use