Suppose for example, there could be multiple types of vehicles. And in this scenario, only the speed and how many people can seat in the vehicle matters.

Would it be better to have a concrete class, with vehicle type as an Enum, or should there be an vehicle interface and different types of vehicle implementing this interface?

  • 2
    Do your vehicle types differ in their behaviour (method implementation/s)? If so, different classes could be useful. If not, there's really nothing to be gained by creating a series of classes which do the same thing. If the values of data/attributes are the only difference then perhaps all you need is some kind of lookup table (map/dictionary) to distinguish between your different vehicle types, and in that case an enum or other kind of identifier would be just fine as a key for the dictionary/map. – Ben Cottrell May 30 '19 at 15:59
  • There is no difference in behaviour. So as you suggested, I would go with enum. – em-Jay May 30 '19 at 16:06
  • I don't see why you need an enum. It sounds like all you need is a single class with with capacity and speed attributes. – JimmyJames May 30 '19 at 16:07
  • The speed and seats depend on the kind of vehicle. If it is a bike then a certain speed and seat 2, if it is a car, then a certain speed and seat 4. – em-Jay May 30 '19 at 16:11
  • Great but if the type doesn't matter just instantiate the objects with the proper settings. I doubt it really doesn't matter. Also, there's no reason you can't use enums and interfaces together. – JimmyJames May 30 '19 at 16:29

It depends in many other requirements like,

  • is there any chance of introducing new vehicle types in near future? If so implementing obviously a better way because it will work like a plug and play.
  • how many vehicle types are required to be considered? If many then surely implementing so many classes does not make senses
  • is there other functional operations depends upon vehicle type? If yes interface wins. Moreover, respecting SRP single responsibility principle is always a good practice which inherently suggests to use interface rather making a larger class with type dependent functional operations.
  • etc.

Only type, speed and capacity are not enough to substantially distinguish between enum or interface.

|improve this answer|||||
  • Thanks, this seems comprehensive. – em-Jay May 30 '19 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.