HACKER Q&A
📣 taybrutal

How do you name your objects?


Moving from the comfortable procedural and functional paradigms, my code feels so much more structured with OOP. I find it very difficult to name something I would not consider an “object” as an object. How do you name your “hard-to-name” objects? Examples would be great.


  👤 overview Accepted Answer ✓
This is one of my favorite things about programming. I mentally define the context of the file, method and method segment, in that order. This allows me to focus my search for words which are accurate to the given scope / context i.e. method / method segment and file-level concepts. From there, it’s a matter of identifying overlap and reusing key terms.

I think one thing people subconsciously or consciously struggle with is how explicit to be. I tend to side towards explicit because I’ve found the biggest trade off to be character count, which is not a big deal. I’ve received several compliments from other programmers when following this approach. A crucial step is to go though everything at the end and simplify / cut-out words that don’t provide meaningful value. Keep it iterative and constantly refine. Once you get used to this natural process of it, it becomes less stressful and more fun - almost like an exploration of ideas and concepts.


👤 thedevindevops
Even Martin Fowler said naming things is one of the 2 hard things in Computer Science.

As long as you can tell roughly what an object does and there's documentation and comments to cover the rest, no one will mind if the name is a bit skewwhiff.


👤 dolni
If it is something that models a real-world thing, give it the real-world name, generally.

If it doesn't, it may model a well-known software pattern. Check out the list at https://en.wikipedia.org/wiki/Software_design_pattern.

You might call a factory that produces Foo objects a FooFactory. Or a proxy to Foo objects a FooProxy.

If it doesn't fit either of the above cases, don't sweat too much. Give the thing an accurate name that describes what it is or what it does. Sometimes consulting a dictionary or thesaurus can help. You can always rename it later.


👤 ffhhj
Name them in a way that gives a summary of what they do, even if it's a longer name that will be easier for others to understand and maintain. The extreme example is the way how tests are named in test driven development (TDD), verbosity makes it way easier to understand.