Thursday, May 10, 2012

Is "first" a Code Smell?

I was looking at some code the other day and noticed that it had a line like this:


And I cringed. Not because I knew it was wrong (it wasn't). But because using ".first" feels like a code smell. (I should note that this isn't specific to the particular syntax. Seeing product[0].price would be equally cringe-inducing.)

So is the use of .first (or equivalent) a code smell?

Arguments for:

  • "first" is arbitrary and not even necessarily in a consistent order. That means it's not deterministic, which is frequently a problem. If you really want random, then wouldn't it be better to use a randomizer explicitly?
  • first means you're working with a collection, and it's inefficient to get the whole collection if you only want one.
Arguments against:
  • if you have a collection in which every element is equivalent in some way, then getting information off the first one (or any random one) is just fine. You may later need it as a collection for something else.
  • some languages have quirks where if you want one then you get a collection of one element.

I'm still not completely sure, but my current thinking is that .first is pretty much always a bad idea except in cases where the language makes you. What do ya'll think?


  1. > "first" is arbitrary and not even
    > necessarily in a consistent order.

    that totally depends on the data structure you are using. First isn't arbitrary if you have a sorted list/array for example.

  2. Corey, that's true. Although the first one in the list may still be arbitrary in the business sense (why not the second?).

  3. I can think of reasons why that variable name might make sense, such as a comparative between two prices chosen by a user...

    Without the context of the surrounding code, it's rather difficult to say for certain.