Naming of a method that creates a list with new instances

1.1k Views Asked by At

There's a method that creates a list of new instances from some parameters. I would call it this way:

List<NewType> createNewTypeInstances(OldType1 value1, OldType2 value2);

But I've also often seen it named in such a manner:

List<NewType> getNewTypeInstances(OldType1 value1, OldType2 value2);

My question is now: Should every method, that creates (or more generally: returns) something, be named with the prefix get?

3

There are 3 best solutions below

0
On BEST ANSWER

It is poor style, and misleading, to have getters that:

  • are not in fact "getters" (ie don't return a field of the instance)
  • have side-effects (make any changes, to anything)

Your method fails on both points.

Calling it create... is a better choice, and a prefix often used for factory methods, to which your method is closely aligned.

1
On

No. You should choose the name that best describes what the method does. Using get/set prefixes is an accepted convention to access properties of an object, but this method is not a getter.

I personally would use create, since the method creates things, and doesn't simply get them. But I would drop the "Instances" suffix, which adds needless noises. Every object is an instance of a class. Given what I know, I would thus probably name the method createNewTypes().

That said, and without knowing anything about your software, OldType and NewType aren't really descriptive names.

0
On

I think this method should be named createNewTypeInstances, because it is creating something. Method with get are by convention getters (accessor methods) and is job to return existing value, not to create new one.