How Enums Spread Disease — And How To Cure It

Poorly handled enums can infect code with fragility and tight coupling like a digital Typhoid Mary.

Say you’re writing software that optimizes traffic flow patterns, and you need to model different vehicle types. So you code up something like this:

vehicle_type.h

enum VehicleType {
    eVTCar,
    eVTMotorcycle,
    eVTTruck,
    eVTSemi,
};

Then you press your enum into service:

route.cpp

if (vehicle.vt == eVTSemi || vehicle.vt == eVTTruck) {
    // These vehicle types sometimes have unusual weight, so we 
    // have to test whether they can use old bridges...
    if (vehicle.getWeight() > bridge.getMaxWeight()) {

Quickly your enum becomes handy in lots of other places as well:

if (vehicle.vt == eVTMotorcycle) {
    // vehicle is particularly sensitive to slippery roads

And…

switch (vehicle.vt) {
case eVTTruck:
case eVTSemi:
    // can't use high-occupancy/fuel-efficient lane
case eVTMotorcycle:
    // can always use high-occupancy/fuel-efficient lane
default:
    // can only use lane during off-peak hours
}

Diagnosis

The infection from your enum is already coursing through the bloodstream at this point. Do you recognize the warning signs?

  • Knowledge about the semantics of each member of the enum are spread throughout the code.
  • The members of the enum are incomplete. How will we account for cranes and bulldozers and tractors and vans?
  • Semantics are unsatisfying. We’re saying cars are never gas guzzlers or gas savers; what about massive old steel-framed jalopies and tiny new hybrids?

A vehicle that challenges our tidy enum. Photo credit: Manila Imperial Motor Sales (Flickr)

The infection amplifies when we want to represent the enum in a config file or a UI. Now we need to Continue reading

How to turn coding standards into epic fails — or not

Yes, a restaurant really displayed this sign. I doubt it influenced anybody’s behavior…

Some attempts to influence the behavior of other people succeed; others are doomed from the get-go.

Coding standards are usually written because we want to influence the structure or style of code produced by engineering teams. Sometimes they’re helpful; more often they’re ignored and forgotten; occasionally they provoke fireworks or bitter resentment.

I’m not sure there’s a guaranteed formula for success, but there’s a guaranteed formula for failure; let’s cover that first, and then see what helpful suggestions we can derive.

How to turn coding standards into epic fails

1. Micromanage.

Leave no room for personal style and creativity. Make no attempt to distinguish between meaty issues and utter trivialities. State all rules in absolutes; allow no exceptions. Announce enforcement in code reviews. Bonus points if you actually follow through on the threat, and double bonus points if you display some other developer’s code in front of the team as an example of egregious violations.

“Always put a space between an identifier and a curly brace, except in nested struct initializers where the first member is a string literal (other than NULL) or a #define’ed constant.”

“Begin every function with a comment that specifies the name of the coder, the date the function was last modified, the purpose of the function, an annotated history of how the function has evolved over time, a list of functions called by your function, your zodiac sign, and the names of all parameters. Make sure that parameters are listed alphabetically (case-insensitive), with a blank line between each, and the explanatory text after the param name indented 8 – (len(param name) mod 4) spaces.”

Continue reading

Six Learning Tips For Tech Folks

In Seven Habits of Highly Effective People, Stephen Covey reminds readers to periodically suspend their lumberjacking long enough to sharpen the metaphorical saw. In other words — take time to renew, to learn, to get better, to work smarter.

Sharpen the saw. Photo credit: ATsawyer (Wikimedia Commons).

Chances are, you’re nodding your head. We all recognize the truth of the principle, but we struggle to put it into practice. My friend who’s a voracious learner is an example we all need to emulate better.

Here are a few tried-and-true habits that help me.

1. Look it up.

If you’re like me, you constantly encounter new acronyms, technoslang, APIs, languages, buzz words… Years ago, the effort to track down the meaning of such items was substantial–a trip to the library, maybe. Now you can usually define a term with 10 seconds of googletime, and you can get the skinny on fatter topics with a 30-second scan of a wikipedia topic. We spend so much of our time in front of screens; resolve now to make a habit out of looking up what you don’t know. It will cost your schedule nothing, and keep you learning.

2. Read.

I’m not suggesting that you should spend hours every day devouring deep content. I subscribe to a number of blogs, newsletters, and industry publications, and I usually rip through all of them in just a few minutes each day. For subscriptions that arrive in my email, I often read subject lines or headlines only, then press Delete. This keeps me aware, and I can always dive in if something truly interesting comes up. I also use StumbleUpon, which has led me to delightful discoveries a few times.

Besides the digital equivalent of sound bites, it’s important to expose yourself to richer content. Ask people you respect for book recommendations. Set a goal to read an in-depth magazine article once a month…

3. Follow thought leaders.

All voices in the blogosphere are not created equal. Twenty or thirty years ago, the only way to get inside the mind of luminaries was to hear them present at conferences, and to buy their books. Now, barriers to silent up-close study (or even one-on-one dialog) are much lower. People like Linus Torvalds, Scott Meyers, Bjarne Stroustrup, Guido van Rossum, Yukihiro Matsumoto, Martin Fowler, RMS, Kent Beck, Don Box, Erich Gamma, and Grady Booch have web sites, podcasts, twitter accounts, google profiles, and the like. Connect and learn.

4. Keep track of questions.

I have a google doc where I record topics on my to-study list, things I want to memorize, experiments I want to try. I also take plain old pen and paper to meetings, and take notes not so much about content but about loose ends or questions that arise in my mind.

Of course, you need to revisit your questions and answer them now and then. Maybe while a build is running and you’re eating a sandwich…

5. Teach others.

The conventional wisdom that the teacher learns more than the students is not just trite sentimentality. Put yourself on the hook to teach something that you’ve learned. If you’re comfortable presenting, volunteer to train team members. If that makes you nervous, write up something you learned in a blog. Or write an email to someone at work, sharing a cool blog post that made you think. Or just capture your learning in insightful comments in your code. But get the ideas out to others, which will deepen and enrich their potency in your own mind.

6. Find a foil.

In literature, a foil is a character that, when placed beside the protagonist, provides significant contrast in personality, style, or motivation. Foils challenge tidy assumptions and deepen the character that the reader cares about the most.

We all need to be challenged. We need to learn about other viewpoints–not at some surface level, so we’ll have talking points to contradict, but in depth, so we appreciate the contributions that other human beings can offer. Nothing is more certain than that the aggregate wisdom of others will always exceed our private insight.

Chances are, you’ll regularly encounter viewpoints different from your own, with no particular effort. So set yourself the task of thoroughly understanding and articulating such a viewpoint now and then, to the point where its proponent would nod with satisfaction and agree that you’ve nailed their thinking. Good things will happen.

Action Item

Pick an item or two from the suggestions above–or find some ideas of your own, that work for you–and start today to turn them into habits. Slow and steady is better than inconsistent bursts…

Extra credit: Tell others about the goals you set. This commits you, and might stimulate some worthwhile conversations. Or add a comment here, sharing other ideas you have. (Remember the value of teaching… :-)