DEV Community

Cover image for Don't name objects for what they are used for but for what they represent
Christian Wolf
Christian Wolf

Posted on

Don't name objects for what they are used for but for what they represent

When reviewing, I often come across code with a, let's say 'dubious' naming.

When looking at the places where this code is integrated in, it becomes clear that the programmer had a concrete necessity and created a tool for it.

Say, at one point we need to keep track how many foos the user entered for a given bar:
Well, I need to count the foos in a bar so I'll just create a FooCounter, it'll have an addBars() method and, of course, a countFoos() method.
Oh, and I only need to count foos of certain bars, so I'll need a hasBarBlurb() method to check if a certain bar is available.

Ready. It all works. Great job done.

Except, you really didn't create a FooCounter. It's more of a BarCollection, isn't it?

I specifically noticed it when I saw the countCurrentFoo(): FooCounter method. Why would a count() method return anything else than an int?

Just rename FooCounter to BarCollection. The methods now make more sense (FooCounter::countFoos(), a counter that counts? BarCollection::countFoos(), yeah, count things in a collection, I've seen that!)

Naming is hard.

It's totally fine starting to name things for what they are used for. Maybe you still have no clear idea where things are going with this new Object, so you gotta start somewhere.

But later on, you should make sure things sound semantically correct and start renaming objects and methods.
Be as close to spoken language as possible.

Top comments (0)