Java是否可用public成員變量?


  《C++沉思錄》有個腳注提到作者本人在某種情況下出於實際考慮使用了public成員變量,為了嚴謹,我不應該用“有個腳注”這種說法,所以又特意翻了書,是《C++沉思錄》的第16頁的腳注,人民郵電出版社2002年第一版。

  這條腳注是這樣的:

細心的讀者可能會發現我把數據成員設為public,並為此驚訝。我是故意這樣做的:machine_status是一個簡單的類,其結構就是其接口。對於如此簡單的類來說,把成員設為private沒有任何好處。(從這個小小的腳注可以看到作者的實用主義態度,相對於后來很多人所奉行的教條主義,確實有很大的差別——譯者注)。

  是的,不僅原作者這么說,而且連譯者都表示了贊同。

  於是,這就在我腦海里埋下了一個種子,以至於后來寫Java的時候,對於一些小的類(那種通常命名為Element的類),也會使用public成員變量。然后有一天我開始懷疑這種做法,就到網上查,我是應該使用public成員變量?還是使用private成員變量,並給出getter和setter方法?

   http://www.cs.swarthmore.edu/~newhall/unixhelp/javacodestyle.html 這里說:

Data members should be private. Only under unusual circumstances should data members be public or protected; instead, you should create public and protected accessor/modifier methods to read/write an object's private data members. One exception to this rule is that static final data members can be public or protected.

  http://programmers.stackexchange.com/questions/143736/why-do-we-need-private-variables 這里還有一個關於private variable的討論,也是支持private而不是public。

  由此看來似乎應該使用private並給出getter和setter。

但是上面鏈接中有個人提到

  

  1. In traditional lanugages like C++ or Java, you usually make everything private and only accessible by corresponding getters and setters. No need to decide much really.

  2. Sometimes, f.ex. in a C++ struct, you need a class only as a way to group several things together. For example, consider a Vector class which has an x and a y attribute only. In those cases, you may allow direct access to these attributes by declaring them public. In particular, you must not care if some code outside modifies an object of your class by directly writing new values into x or y.

其中第2點就挺符合我的那種情況……

  但是最終我的結論還是傾向於用private,並用setter和getter,這個setter其實也是破壞了封裝性(而public成員變量是根本沒有封裝性),但是如果真的不需要的話,你可以選擇不要它。而且使用setter應該比直接將某個成員設為public更好,好處是你可以控制,比如添加驗證參數是否合法,如果暴露為public,是完全無法控制的。舉例來說,如果有個setNumberOfPeople(int num)方法,你就可以檢查num是否非負,負數就是非法的;如果暴露為public,是做不到這一點的。

   http://stackoverflow.com/questions/1568091/why-use-getters-and-setters 這個似乎回答的正是我的問題,被最多人認可的回答也是要setter和getter。這里提到了這樣做所帶來的更多的好處,雖然有些都沒接觸到。

  其中有這樣一個comment,雖然沒這么用過,但覺得不錯:

One thing that is bought by using a property setter, even in a well-designed framework, is the ability to have an object notify another when a property changes

   不過往下看的話,還是會發現有很多爭論和另一種看法的支持者……

Anyway,我比較傾向的結論是:用private成員變量,並只在必要的時候給出getter和setter方法;這種做法似乎沒有明顯的缺陷。

 

更多參考:

http://stackoverflow.com/questions/11071407/advantage-of-set-and-get-methods-vs-public-variable

http://stackoverflow.com/questions/565095/are-getters-and-setters-evil

http://www.javaworld.com/javaworld/jw-01-2004/jw-0102-toolbox.html (這個不錯)

http://typicalprogrammer.com/?p=23 (特別提到Java和python的對比,Java可能還是需要getter和setter,因為如果開始用public member,等你想改變主意用getter和setter,就有點遲了,因為可能已經寫了很多“classInstanceXXX.memberYYY = ZZZ”這種代碼)

Google “java public member vs setter getter”


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM