The other day I thought I thought wanted an ||+= operator.
You see, in Ruby, there's this "if x is not defined, define x" idiom that goes like this:
x ||= 1
I was sick of seeing that followed by
x += 1
every time I used it.
I wanted to combine it
into one line of
x ||+= 1
. I spent a little time trying to figure out how to do that, or
some acceptable alternative.
Then I realized that a ternary operator would get the job done on one line.
But I didn't really want the redundancy. On top of that, I think ternary operators require too much
thought to process, and I avoid them in favor of spelling it out.
Tim Pope had an obvious and simple suggestion: define your hash with the default value of 0.
If you do that, then each time you write
hash[key] += 1
it will define a new key into the hash
if
key
did not exist there before (and the value there will be defaulted to 0, then incremented),
or it will increment it if it's already there. Perfect!
Except that the objects I wanted to have that power didn't have control of the hashes passed to them. And I wanted
to be able to receive strings and arrays with similar behavior in the same object.
Or so I thought.
The real problem was just that my thinking was attached and working within the particular object model I had already
constructed. The more I thought about it, the more I realized it was just wrong - this object should
be constructing its own data structures, and it should be encapsulating them, and it should be providing
methods to allow the outside world to use and manipulate.
This is not that new a concept:
It's called object orientation. Perhaps you've heard of it.
Anyway, it (re)taught me a lesson that I see others forgetting (or having never learned) quite often:
Before deciding that the language needs fixing, first consider if you're just trying to do something stupid or useless or redundant.
Sometimes the language is not what is broken. I surmise that more often, it's your programming that is
in need of repair. It's such an obvious point, but one that seems so easily and often forgotten.
Hey! Why don't you make your life easier and subscribe to the full post
or short blurb RSS feed? I'm so confident you'll love my smelly pasta plate
wisdom that I'm offering a no-strings-attached, lifetime money back guarantee!
Leave a comment
There are no comments for this entry yet.
Leave a comment