[英]When is it appropriate to assign values to an instance variable in Java?
這是一個關於最佳實踐的問題。 在采用面向對象的方法時,我想出了三種不同的方法來做同樣的事情。 在我未經訓練的眼中,它們似乎都沒有“錯誤”,但我知道每種語言和風格都有其最佳實踐,我想知道這三種方式中的任何一種是否違反了我尚未學習的某些“最佳實踐”。
方式1:(聲明,然后在構造函數中賦值)
public class CCipher {
private String alphabet;
private String shiftedAlphabet;
private int mainKey;
public CCipher(int key){
mainKey = key;
alphabet = "abcdefghijklmnopqrstuvwxyz";
shiftedAlphabet = alphabet.substring(mainKey)
+ alphabet.substring(0, mainKey);
}
方式二:(同時聲明和賦值)
public class CCipher {
private String alphabet = "abcdefghijklmnopqrstuvwxyz";
private String shiftedAlphabet;
private int mainKey;
public CCipher(int key){
mainKey = key;
shiftedAlphabet = alphabet.substring(mainKey)
+ alphabet.substring(0, mainKey);
}
方式 3:(有些東西在非 get/set 方法中初始化)
public class CCipher {
private String alphabet;
private String shiftedAlphabet;
private int mainKey;
public CCipher(int key){
mainKey = key;
alphabet = "abcdefghijklmnopqrstuvwxyz";
}
public String encrypt(String input){
shiftedAlphabet = alphabet.substring(mainKey)
+ alphabet.substring(0, mainKey);
// ... code to encrypt input ...
}
public String decrypt(String input){
shiftedAlphabet = alphabet.substring(26 - mainKey)
+ alphabet.substring(0, 26 - mainKey);
// ... code to decrypt input
}
}
就我個人而言,對於這個特定的家庭作業,我真的很喜歡第三種方式,因為它符合我試圖解決的問題的邏輯。 但這是錯誤的,這是錯誤的......
第二個版本好像還行。 但與常量確實作為靜態最終字符串。
public class CCipher {
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
private final String shiftedAlphabet;
private final int mainKey;
public CCipher(int key) {
mainKey = key;
shiftedAlphabet = ALPHABET.substring(mainKey)
+ ALPHABET.substring(0, mainKey);
}
Christopher Schneider 指出,在加密和解密中使用了不同的 shiftAlphabets。 作為現實中的 CCipher 對象可能會加密或解密,請將其設為局部變量。
需要兩個不同的非最終延遲初始化字段,這很麻煩。
public class CCipher {
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
//private final String shiftedEncryptAlphabet;
//private final String shiftedDecryptAlphabet;
private final int mainKey;
public CCipher(int key) {
mainKey = key;
shiftedAlphabet = ALPHABET.substring(mainKey)
+ ALPHABET.substring(0, mainKey);
}
public String encrypt(String input){
String shiftedAlphabet = alphabet.substring(mainKey)
+ alphabet.substring(0, mainKey);
// ... code to encrypt input ...
}
public String decrypt(String input){
String shiftedAlphabet = alphabet.substring(26 - mainKey)
+ alphabet.substring(0, 26 - mainKey);
// ... code to decrypt input
}
關於alphabet
- 如果永遠不會改變,第二個片段可能最接近最佳實踐,但它仍然不完全存在 - 它應該是一個private static final
“常量”:
public class CCipher {
private static final String alphabet = "abcdefghijklmnopqrstuvwxyz";
// ...
}
關於shiftedAlphabet
- 第三個片段肯定不太有利(盡管技術上不是“錯誤”) - 在每次encrypt
或decrypt
調用時,您都會重新計算shiftedAlphabet
,它不會以任何方式受到input
影響。 這可能沒有錯,但很浪費(換句話說 - 作為一名老師,我肯定會為此扣分,即使代碼確實有效)。
總而言之 - 第二個片段可能是所有三個片段中最好的,但我會將alphabet
的修飾符修復為private static final
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.