简体   繁体   中英

Should i use an abstract class or an interface for my doctrine model?

In Doctrine, assuming I want to implement different types of vehicles. Maybe a car, a plane, a bicycle and so on ... all these vehicles have many different properties but also very common things like they are all made of a material.

So if i want to get this material ... should i implement a abstract class Vehicle with a property material and implement getter/setter or should i define a interface IVehicle and define the getter/setter in there to be sure there is really a method for getting and setting the material? Or should i even use both in combination?

It feels "professional" using the interface ... but it feels wrong to define getter/setters in interfaces, so my personal feeling is:

Don't use an interface, just use the abstract class.

But is the abstract class approach protected against misuse? For example on another place i definitely expect a Material type returning from the getMaterial function ... is the abstract class approach also save for not returning complete unexpected things (like the interface does)?

So if i extend this vehicle for another concrete class, a developer should not be able to return unexpected things, but should also be able to change the logic in the particular method if needed.

My 2 cents:

You can write an abstract class with methods that return null (or some other predetermined value) that would require you to implement them in every derived class.

This approach would still require you to write some boilerplate code to check against your conditions in every class.

I would personally go with an interface here as the nature of your classes seem to be quite diverse and can only be partially generalized to a single abstract class. However, I don't see anything wrong with going the abstract class way either. In this case, the devil is in the details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM