Sean O'Malley
Sean O'Malley

Reputation: 51

Java method names: useXxx() vs. setXxx()

Is there a general guideline for prefixing Java method names with useXxx() vs. setXxx()?

I tried to call the setDelimiter() method of the Scanner class, only to find it was named useDelimiter(). The JavaDoc describes this method as "Sets this scanner's delimiting pattern..."

So, why useXxx() instead of setXxx()?

Upvotes: 4

Views: 2310

Answers (5)

Joseph Farrugia
Joseph Farrugia

Reputation: 327

In Java setXxx() method, 'set' is used to set a value, for example to set the ID of a manager:

 public void setManagerID()
 {
      String managerID = null;

    managerID = JOptionPane.showInputDialog(null,"Input an ID:");

  }

Upvotes: 0

fge
fge

Reputation: 121710

Naming methods .setXxx() or .getXxx() is just a convention for JavaBeans. If you don't explicitly use your class as a bean (and Scanner certainly isn't one), you can name your methods however you like.

Also, this .useDelimiter() method returns this, whereas JavaBeans setters return void. If this method did follow the bean convention, you could not be able to write:

Scanner scanner = new Scanner(System.in).useDelimiter(xxx);

The only real convention to method names, except if you do intend your class to be a bean, should be that they are self explanative.

Upvotes: 2

someone
someone

Reputation: 6572

it is not the standard setter method. its set the delimPattern and return Scanner object

 public Scanner useDelimiter(Pattern pattern) {
    delimPattern = pattern;
    return this;
}

Upvotes: 2

paulsm4
paulsm4

Reputation: 121649

"setXXX()" and "getXXX()" are more than "conventions" - the names are also recognized as "getter" and "setter" methods by Java Beans. If your class happens to be a Java Bean. Class "Scanner" isn't :)

Otherwise, it's just a matter preference.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272277

That's definitely inconsistent.

I would normally expect accessors to be of the form setX/getX (or isX for booleans). This is part of the JavaBeans convention. A lot of frameworks and tools are coded explicitly to work this way and you'll lose interoperability if you ignore it.

Note that it's not incorrect, however. But I would try to maintain a level of interoperability regardless.

Upvotes: 0

Related Questions