Raj Rao
Raj Rao

Reputation: 9138

Method naming convention

If a method takes a class/struct as an input parameter, what is the best way to name it?

Example:

class Person{}
class Address{}

class Utility{
  //name **style 1** - use method overloading
  public void Save(Person p){}
  public void Save(Address a){}

  *//name **style 2** - use unique names that define what they are doing
  //or  public void SavePerson(Person p){}
  //and public void SaveAddress(Address a){}*
}

I personally like style 1 (Use the languages features - in this case overloading). If you like style 1, can you point me to any "official" documentation, that states this to be a standard?

Upvotes: 1

Views: 1180

Answers (3)

Fredrik Mörk
Fredrik Mörk

Reputation: 158299

I would say your challenge is not in the field of method naming, but rather type design. A type that is responsible for saving both Person objects and Address objects seems like a type with more than one responsibility. Such a type will tend to grow and grow and grow and will eventually get hard to maintain. If you instead create more specialized types, method naming may automatically become a simpler task.

If you would still want to collect these methods in the same type, it's mostly a matter of style. One thing to perhaps think about is whether this type may be consumed by code written in another language, and that does not support method overloading. In such cases the longer names is the way to go. Otherwise just stick to what feels best (or whatever is the ruling convention at your workplace).

Upvotes: 3

Oded
Oded

Reputation: 498914

It is a matter of style.

If you don't like long method names, go with 1.

If you don't like long overload lists, go with 2.

The important bit is to keep consistent, so do not mix the two styles in one project.

If you are seeing that you have many such methods, you may need to rethink your design - perhaps a solution involving inheritance would be more appropriate.

Upvotes: 2

Andy Thomas
Andy Thomas

Reputation: 86381

Distinct names avoid entirely any problems associated with method overloading. For example:

  • Ambiguity is avoided if an argument's type matches more than one of the candidates.
  • In C++, overloaded methods can hide those of the same name in a superclass.
  • In Java, type erasure prevents overloaded methods differing only by type parameterization.

It would also be worthwhile to ask whether polymorphism could be used instead of overloading.

Upvotes: 0

Related Questions