mardi 23 juin 2015

How to design classes with different combinations of common functionality

I'm looking for some design suggestions. For example, let's say I want to create an abstract class for CRUD operations. I have my concrete implementations that inherit that base class. Some of my implementations are read-only. Some don't allow deletes. Some allow all CRUD operations. But at their core, all of these methods are the same between each implementation. And I want other classes that call these classes to be able to know what each implementation is capable of. My options that I can think of are:

  1. Put all code and public methods into the abstract class. Each implementation stores a list of what it can do {create, read, update} and expose a public method like AvailableMethods() which will simply return that list. In the implementation of these methods, it checks if that method is available and throws and exception if it is not. For instance, when create() is called, it checks to see if "create" is in the list of available methods. It doesn't seem right to do this for many reasons. The first of which, for me, is that I don't think any object should expose a method that will consistently throw an exception (assuming it's not an allowed method).

  2. Put all implementation into protected handler methods (handleCreate(), handleRead(), etc.) in the abstract class. Create interfaces for each method like ICanCreate has a single create() method, ICanRead has a single read() method. Concrete classes implement the needed interfaces and declare the public method that calls the handler. Calling classes can simply ask if the class implements the needed interface. This seems like a better solution but I feel like with hundreds of objects, and many different combinations, I'm going to be copy/pasting a thousand of the public methods. There will be a point where I'd want to consolidate into more base classes like ReadOnly, NoDelete, FullAccess or something like that. Which seems ok but even with only four choices, there are a lot of combinations. And this is just an example. I may have other functionality in which there are 6 or 8 methods.

Are there any other design options that I'm overlooking? I'm asking in a language agnostic way, but if there are any language specific ways of handling this better, I'm using PHP.

Aucun commentaire:

Enregistrer un commentaire