简体   繁体   中英

Java Getter Setter Codestyle

Outside of the context of beans, reflection, introspection or any other often referenced nonsense, is there an important reason that Java Getter/Setter are always notated as Type getAttribute() and void setAttribute(Type a) ?

I read and wrote a lot of C++ code in recent times and when coming back to Java, I suddenly felt the urge to use Type attribute() and void attribute(Type a) as signatures for getters and setters as they somehow feel more comfortable to use all of a sudden. It reminds me of functional programming, having the attribute as a method of the object instead of having a method explicitly change or access the attribute.

You can use the methods the way you are comfortable with;

Type attribute() and void attribute(Type a)

The reason it is as you first example

Type getAttribute() and void setAttribute(Type a)

is used is to make it obvious what the method is to be used for. For example and new developer to a project can pick up and understand the flow of code without moving between different classes to see what that method does.

Getters & Setters are usually only one line functions. If a function is to do some data manipluation, it with usually use a descriptive name rather have a get or a set.

Summary: Getters & Setters are mainly used for entity objects, where no data manipluation should be done, NOT saying that it can't be done.

The shorter style is the one I use. AFAIK Those in low level Java programming tend to use it possibly because it's more like C++, or because it's less like EJB's.

The problem with the JavaBean getter/setter style is it assumes an implementation of just setting and getting the variable, however this is not always the case.

The Java Naming Conventions state that " Methods should be verbs ", which is commonly generalized by the community to " Methods should start with a verb ". It is a question of consistency. You may very well use attribute , but I can guarantee you that people will confuse it. So if you expect other people to read and change you code, I strongly suggest to go for getAttribute and setAttribute . This argument is supported by Robert C. Martin in his book Clean Code (Section "Method Names"). It explicitly deals with your case.

That being said, the Java-API itself violates this rule sometimes (for example with the method size() in Collections). This is a known problem but shouldn't stop you from doing it better.

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