简体   繁体   中英

Is Java breaking its own rules with setter methods that have non-void return types?

I was given to understand that the standard convention was for setters not to return anything. However, the NIO.2 API has a few methods like setOwner, setLastModifiedTime and setAttribute that return Path instances. Are these methods not true setters, or else do not all setters have to have void return types?

The obsolete JavaBean standard (which was meant to help with tooling so that JavaBeans could be automatically handled) may have said something about void setters, but Fluent Builder is aimed at making things easier.

Allowing method chaining makes for nicer code, and as there's no good reason for requiring a void return type from setters, they've chosen to get with the program (no they haven't see comments):

path.setOwner(foo).setLastModifiedTime(bar).setAttribute(baz);

The JDK does have examples of fluent interface in classes like StringBuilder and ProcessBuilder , but they avoid using the setXXX nomenclature (possibly to avoid confusion) even when it would make sense. StringBuilder.append() obviously wouldn't be named setMoreText() , but ProcessBuilder.directory(File) is less obvious than setWorkingDirectory(File) IMHO.

A setter is usually used as an accessor method to change the state of an object. As Kayaman mentioned it can be useful to return the object itself to create a fluent api instead of void - see it as syntactical sugar, when working with these objects.

Nevertheless, in the NIO case, it is a static method of the class "Files" that changes the state of the Path that is given as first argument - so in this case it's no accessor but a "normal" method that has "set" in its name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM