Reputation: 157
If I have a class which all the functions in it need to pass a check first, which of the following is more preferred
1.
class check{
public check(Status){
if(CheckFunc(Status)){
// Passed the Check function and return a class instance
return new UpdateClass();
}
}
class UpdateClass{
public void Func1(){
// Do the stuff
}
// Other functions...
}
OR
2.
class UpdateClass{
boolean passedCheck = false;
public UpdateClass(Status){
if(checkFunc(Status)){
this.passedCheck = true;
}
}
public void Func1(){
if(this.passedCheck){
// Do the stuff
...
}
}
// Other functions...
}
Also, is it a good way to use a class/function to decide which class to be instantiated?
for example:
public Animal decideWhichClass(Status){
if(Status == StatusA){
return new Dog();
}
else if (Status == StatusB){
return new Cat();
}
}
Animal a = decideWhichClass(CurrentStatus);
Upvotes: 0
Views: 47
Reputation: 131346
First question) The check is a requirement for the update processing.
In the first way, you don't have this guarantee as UpdateClass
may be created and used without passing the check.
The second one is so better as it prevent to bypass the check:
public UpdateClass(Status){
if(checkFunc(Status)){
this.passedCheck = true;
}
}
Also, is it a good way to use a class/function to decide which class to be instantiated?
The example is broad but it is acceptable to have a factory
of objects which the instantiated subclass depends on a specific parameter.
Note that to avoid if/elseIf
, the function could rely on a Map structure.
Here is an example in Java (but you could get a similar thing in any Object language):
public class AnimalFactory{
private static Map<Status, Supplier<Animal>> map = new HashMap<>();
private AnimalFactory(){
}
static {
map.put(Status.A, Dog::new);
map.put(Status.B, Cat::new);
}
public static Animal ofAnimal(Status status){
return map.get(status).get();
// of course you should also handle the error case : no association found
}
}
//Client code
Animal a = AnimalFactory.ofAnimal(Status.B);
Upvotes: 1