When to hard-code

Hard-coding is generally considered an anti-pattern and abhorred by experienced developers. Input and configuration data should be externalized from the code, or at the very least parametrized to a language constant.

While working at Wellmo, I’ve come to reconsider this pattern. In fact, I now often advocate hard-coding special cases when first encountering them. I have written and tested production code reading

// TODO: Hard-coded logic
if ("myGroupId".equals(group.getGroupId())) {
    // do stuff
}

and I’m fine with it.

The rationale comes from lean principles. You shouldn’t build something that you don’t know is needed. Especially in a startup, uncertainty is the often norm. New, very specific features are often required without full knowledge how it will fit into the grand scheme of things.

The above example code is from a case where a certain group of users needed to see a group that is hidden from others. I knew that showing / hiding groups is something we need in the future, but I wasn’t exactly sure what the conditions would be.

Instead of creating some generic mechanism for configuring group visibility, I hard-coded that case. Several months down the road, we now have more insight into what the proper logic is, and we are currently implementing that. It’s radically different from what I would have implemented at the time. Premature configurability would have been a waste of time.

Another example is a case where an item needed to be branded differently for certain customers. Instead of designing a way to configure the branding, we simply wrote an if-condition that selected between the two options. Half a year later the alternative branding was removed, and we simply removed the few lines of code. No generic logic was ever needed.

My suggestion is to hard-code cases when:

  • there is uncertainty on how the generic logic would work
  • only a single, short portion of code is affected
  • the proper, generic logic can later be introduced without affecting other code

It is imperative that hard-coded logic is replaced when more similar special cases arise. This requires good communication and understanding between management and the developers. Otherwise it may be difficult to explain why a third similar case is slower to implement than the first two.

Advertisements
This entry was posted in Coding and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s