Prefix type of variable after the variable name

This one is pretty easy. Between suffixes (namespaces), roots (what a thing actually is), and suffixes and all that, I like to use a suffix (a word-final thing, something that goes at the end of the word) that denotes the type of the thing (name, variable) being used. It probably sounds more complicated than it really is so here are some clarifying examples.

The following examples are either variable names, or properties of an object, or fields of a model, or methods in a class, or keys in a hash. Hopefully you get the idea.

  • updated_at as in, article.updated_at . Denotes a timestamp.
  • updated_on as in article.updated_on . Denotes a date! You can clearly see the difference from the above, in fact you can imagina a conversion:
def updated_on()
  return updated_at.to_date()
end
  • _str or _s for strings, _h for hashes, _arr for arrays. You would think this is more work than it's work and that it would confuse the developer and the code reader - until you need to make a clear distintion between e.g. states = [ 'AK', 'AL', 'AR', ... ] and states_str = 'AK,AL,AR' and as soon as you do, the naming convention for type becomes useful indeed. An example of a use case is if you are accepting query value parameters (all strings) and converting them to objects, and then back to strings for using in a UI.
  • is_ is a prefix rather than a suffix for denoting a boolean: is_active, is_deleted. I've seen people use active_flag, deleted_flag as a suffix, but I think my personal preference is for something semantic, that flows like english as it is spoken, and that is a little bit shorter to type. 

    Of note here also is that a timestamp can be easily converted to a boolean, and in fact that is preferred as it increases information density without increasing code complexity:

    def is_deleted
      return !!self.deleted_at
    end
    def is_active
      return !self.deleted_at
    end

    This way you know when something was deleted, but you can still work with booleans. To un-delete, set the timestamp to nil/null: meaning it is not deleted, i.e. active.

Please login or register to post a comment.