Java Method Names: useXxx () vs. setXxx ()

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

I tried calling the setDelimiter() method on the Scanner class, only to find it called useDelimiter() . JavaDoc describes this method as "Installs this scanner markup pattern ..."

So why useXxx() instead of setXxx() ?

+4
source share
5 answers

This is not a standard setter method. set it delimPattern object and return Scanner

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

The naming methods .setXxx() or .getXxx() is just a convention for JavaBeans . Unless you explicitly use your class as a bean (and Scanner , of course, is not one), you can name your methods as you like.

In addition, this .useDelimiter() method returns this , while JavaBeans installers return void . If this method complied with a bean, you could not write:

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

The only real convention with method names, unless you intend your class to be a bean, should be what they themselves explain.

+2
source

This is definitely inconsistent.

I usually expected accessors to be setX / getX (or isX for booleans). This is part of the JavaBeans agreement. Many frameworks and tools are explicitly encoded to work this way, and you will lose interoperability if you ignore it.

Please note that this is not true. But I would try to maintain the compatibility level independently.

0
source

"setXXX ()" and "getXXX ()" are more than "conventions" - names are also recognized as the "getter" and "setter" methods of Java Beans. If your class is a Java Bean. Class "Scanner" is not :)

Otherwise, it is just a question.

0
source

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

  public void setManagerID() { String managerID = null; managerID = JOptionPane.showInputDialog(null,"Input an ID:"); } 
0
source

All Articles