0

I have something like this:

switch(type){
    case "CAR":
       return new Car();
    case "BIKE":
       return new Bike();
}

Now, there is a requirement, to add a common API for both to check if input type is valid, only when validateFlag is true.

Can you suggest some design here? What's the best to go with?

I am thinking of something like:

if(flag== true)
  return new Validator();
switch(type){
    case "CAR":
       return new Car();
    case "BIKE":
       return new Bike();
}```

3
  • What is the return type of the method? @Turtle seams to think it's a common superclass of Car and Bike, which makes sense, but returning a Validator doesn't make much sense if you can also return a Car or a Bike. Commented Nov 29, 2021 at 9:58
  • If it's not a type of car or bike, how do you think we should separate this, we can add a if else block while calling this itself, but the idea is to avoid if else's and instead use some design pattern Commented Dec 7, 2021 at 4:57
  • I don't understand your question Commented Dec 7, 2021 at 9:19

1 Answer 1

1

You might want to use inheritance here. Have a look at the sample code below.

class Vehicle {
    protected boolean mIsValid;
    
    public Vehicle() {}
    
    public boolean isValid() {
        return mIsValid;
    }
}

class Car extends Vehicle {
    public Car() {
        super();
        mIsValid = true;
    }
}

class Bike extends Vehicle {
    public Bike() {
        super();
        mIsValid = false;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.