This is a question on best practice. When taking an object oriented approach, I've come up with three different ways that I might do the same thing. To my untrained eye, none of them seem "wrong", but I know every language and style has its best practices, and I want to know if any of these three ways violate some "best practice" that I haven't learned yet.
Way 1: (declare, then assign in constructor)
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);
}
Way 2: (declare and assign at the same time)
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);
}
Way 3: (Some things get initialized in a non get/set method)
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
}
}
Personally, for this specific homework assignment, I really like the third way best, because it flows with the logic of the problem I'm trying to solve. But it it's wrong, well it's wrong...
shiftedAlphabetasnullwhen theCCipherobject is initialized; this may end up causing issues for whoever uses it and expects the value to not benull. The other two are mostly personal preference.shiftedAlphabetis only ever used internally in the method which assigns to it, so there is no need for it to be a field; better to make it a local variable.alphabet = "abcdefghijklmnopqrstuvwxyz";asprivate static final String? Is there any chance it changes later?