Coding pattern for using an instance member
Suppose I have a class called CommandLineOperation
. This class accesses api resources. Thus, I have defined one instance of the type APIAccessor
.
class CommandLineOperation {
APIAccessor apiAccessor;
void create() {
apiAccessor = new APIAccessor(email,password);
//do work for creation
}
void update() {
apiAccessor = new APIAccessor(email,password);
//do work for update
}
}
class APIAccessor {
String email;
String password;
APIAccessor(email,password) {
this.email = email;
this.password = password;
}
}
The operations in the CommandLine are infrequent, this is the best approach to instantiate APIAccessor
under each operation, or instantiate once using the class constructor CommandLineOperation
. eg
CommandLineOperation(String email,String password) {
this.apiAccessor = new APIAccessor(email,password);
}
Please let me know or suggest a good coding design sample. Or can you suggest me any reference so that I can improve my coding standard based on analysis. Thanks in advance.
source to share
Answer: it depends on your context / requirements.
Benefits of creating ApiAccessor once while instantiating CommandLineOperation:
- you can create immutable objects (by making this field final). This has various advantages - since you always know that this field has been initialized (ideally, you can even check that the ApiAccessor is indeed valid and does not contain incorrect information).
- your other methods can focus on their direct responsibility - instead of worrying if this field has already been initialized
- as a consequence, unit testing is also easier - if you need to mock, you need to provide the ApiAccessor object once - instead of having to deal with it every time you call one of the "real" "CommandLineOperation methods
Disadvantages:
- you cannot "toggle" the ApiAccessor for a given CommandLineOperation object
- If you have millions and millions of these objects hanging around without being yours, you are losing your memory.
But when you think about it: these flaws are not a real-world problem anyway.
Regarding the comments about the required credentials coming from parsing files: it boils down to dependency injection!
Value: The CommandLineOperation class must not contain any code to create an ApiAccessor instance. This object must either be injected (via the dependency injection framework) or provided via a constructor, for example.
source to share