OOP design pattern - add, edit and delete - oop

Assuming I have to handle the adding, editing or deleting of something.
Is better to create three class like:
class AddSomething{}
class DeleteSomething{}
class EditSomething{}
or a class with three methods like:
class Something{
public function add(){}
public function delete(){}
public function edit(){}
}
Another alternative is abstract class, but these three functionality have very little in common, such as add and remove (practically nothing).
What is the best alternative according to the rules of OOP?

...or three interfaces like: IAddSomething, IEditSomething and IDeleteSomething? Then your classes can choose what roles they take on.

Add, Edit and Delete would be methods. Something sounds like the subject of the verb, so I would make it an argument to the methods. What's the object of the verb - who's doing the adding, editing or deleting? I would represent that actor as a class.

Related

OOP approach name when you override only private methods

Could someone tell me the OOP approach name when you override only private methods? I would like to read more on it, but I do not know what to look for since I forgot the name of the approach.
The approach is about having only a single entry point in the base class in public methods, which in turn call virtual private methods which are overwritten by the children classes.
Template method design pattern (or, as Herb Sutter calls it, Non-Virtual Interface Idiom)

Interface Segregation Principle and Convenience/Helper Methods

How does the Interface Segregation Principle apply to convenience/helper methods? For instance:
I want to create an interface that represents business partners. The bare minimum that I would need would be a setter and a getter method that would set or get the entire list of partners:
Interface Partners {
method getList();
method setList();
}
I also want to have a contains() method to tell me if a certain person was included in the list of partners. I consider this a helper or convenience method, because all it does it call getPartners() and then check if the given person is in that list.
My understanding of the Interface Segregation Principle is that I should separate my contains() method into a separate interface, since someone might want to implement my Partners interface without providing an implementaiton for this unnecessary helper method. In my example, its not a big deal, but the list of helper methods can quickly grow long (addPartner, addPartnerByID, addPartnerByUserid, etc.), so this is a practical problem.
My concern is that I'm finding it quite difficult to pick a name for an interface to hold my contains() method that does not sound cumbersome, and I think any time you have this much trouble naming something, it is a red flag that there is something wrong in your design. It does not seem right to have an interface named PartnersSupportingSetInclusionChecks, nor does it seem good to have an interface just named PartnerHelperMethods.
How do I apply the Interface Segregation Principle to such methods?
since someone might want to implement my Partners interface without providing an implementation for this unnecessary helper method
emphasis mine
Please by all means have a contains() method if you think it's important to have in your API. Especially if all your client code currently use one.
The Interface Segregation Principle is to keep totally unrelated methods out of the interface. It looks like you are trying to implement a Repository which should have a get, contains etc methods to see what elements are in the repository and a way to retrieve them.
If you had other kinds of methods that had nothing to do with getting or setting Partners, then the ISP should be applied to make a different interface for that.
However, you may want to think about separating your getting/contains methods from your setting/adding methods if you think you will have clients that treat this repository as read-only and should not be allowed to modify it, but you don't have to.
The following answer is based on C# language. It might not be valid in another language.
I want to create an interface that represents business partners
This first sentence tells me that you probably don´t need an interface, but a top-level abstract class. And it is very important to distinguish whether we need an interface or an abstract class.
Abstract classes represent hierarchies, where each descendant of that hierarchy is a specialization, therefore you can adding more members in order to enrich the family. In this case, the relationship describes “This X is a Y”
Interfaces represent a set of characteristics and behavior not linked to any hierarchy. Therefore, the main intention is to link different kind of classes that will have the same features or behaviors. The relationship describes “This X can do Y”
So, assuming that what fits better with your description is an abstract class, I suggest the following:
One option could be set the methods "getList()" and "setList()" as non-abstract methods and provide into the abstract class a field to store the list
public abstract Partner
{
List<Partner> list;
public void SetList(List<Partner> list)
{
list = list;
}
public List<Partner> GetList(Partner partner)
{
return list;
}
}
So, the method "Contains" can be non-abstract aswell, so you don't force the descendant classes to provide an implementation.
public bool Contains(Partner partner)
{
return list.Contains(partner);
}
And let's suppose that in the future you want to add new helpers methods. Those methods can be new non-abstract methods into the base class, so you will not affect your current descendants of "Partner".
If you need to modify the implementation of helpers methods, you can set it as "virtual" so that the descendant classes can override the base implementation.
public virtual void AddPartner(Partner partner)
{
list.Add(partner);
}

To subclass or not to subclass

I have three objects; Action, Issue and Risk. These all contain a nunber of common variables/attributes (for example: Description, title, Due date, Raised by etc.) and some specific fields (risk has probability). The question is:
Should I create 3 separate
classes Action, Risk and Issue each
containing the repeat fields.
Create a parent class "Abstract_Item"
containing these fields and
operations on them and then have
Action, Risk and Issue subclass
Abstract_Item. This would adhere to
DRY principal.
My Perspective
Let's say, if you used inheritance. Over a period you have new attributes that are common to only Action and Issue but not Risk. How will you handle this? If you put them under parent then Risk is inheriting stuff that is irrelevant (Liskov Substituon Principle knocking?). If you put then in Action and Risk separately then you are breaking DRY, the initial reason why you started inheritance. Point is Inhertence for re-use is bad. If there is no "is-a" then better not use it and when you are in doubt then there is no real "is-a".
My Preference
There are other ways of achieving DRY as shown in below example code. With this addition of new properties my be another Common2, addition of new behavior is new CommonBehavior2 if they are not applicable to all 3 classes; if they are then just change existing Common and CommonBehavior
public class Common implements CommonBehavior
{
String Description;
String title;
public void f() {}
}
public interface CommonBehavior
{
void f();
}
public class Action implements CommonBehavior
{
private Common delegate;
public void f()
{
delegate.f();
}
}
Also look at my answer to a similar question with another practical example Design pattern to add a new class
Yes, adhering to DRY is usually a very good idea except if the classes have very, very different uses (i.e. both apples and cars may be red, still I wouldn't derive both of them from a base class called ProbablyRed). In your case, however, I'd definitely go for a base class since the implementations you describe (Action, Issue, Risk) all seem to be some kind of business rule with very similar semantics.
You seem to be answering this yourself. As you say, DRY.
The abstract parent class sounds like the way to go. It will also make it possible or easier (depending on your language) to implement and use functions which act on any of the three items. For example, you could have a "Get a list of all items raised by {user}" function.
Another facet may become visible if you look at the use cases, probably dealing with different subgroups of the properties.
If for example "label", "due date" and "raised" are used in a todo like application and other properties of "Action" and "Risk" will be prevalent when working on that task, you might consider an aggregation of lets say Task (label, due date,...) and Topic which is a polymorphic reference to things like Action, Issue or whatever will come up someday
I guess I have answered the same question here
When to create a class vs setting a boolean flag?
Don't subclass just because objects share some data or operations. Consider composition as the default way to follow DRY.
In your particular case, only create a parent class if your objects are actually related, i.e. there's a semantic "is a" relationship to the parent class. For example, if Action, Issue, and Risk are all Ticket objects.

Object Orientation - Where to place this Interface Declaration

I have a few questions for you wise people involving OO design with Interfaces and abstract base classes. Consider the following scenario:
I have an abstract bass class "DataObjectBase" and a derived class "UserDataObject." I also have an interface "IDataObject." The interface of course exposes all of the public methods and properties that my Data Objects must expose, and you can probably guess that the abstract base implements the methods and properties common to all Data Objects.
My question is, if the abstract bass class DataObjectBase implements everything specified in the interface IDataObject, should the interface be declared on the base class, or on the derived classes(s)?
In C# interfaces declared on the base class are implicity applied to the derived classes, but is this the best practice? It seems to me that implementing the interface on the base class makes it less obvious that the derived class implements the interface, but then again requires the Interface to be specified for each derived class.
Additionally, if the base class was NOT abstract, would the reccomendation change?
A second sub-question: If the base class implements all of the methods/properties of the IDataObject interface, is the interface even needed? The base class typename can simply be used in place of the interface name, ie:
private DataObjectBase _dataObject;
private IDataObject _dataObject;
In the above example (where again the base implements everything exposed by the interface) both can be assigned the same derived types. Personally I always use the interface in these situations, but I am intrested in hearing peoples thoughts.
Thanks in advance.
My way of thinking about such problems is to consider the different people reading the code, the "roles" if you like. Also consider the overall maintainability of the system.
First there is some code expecting to use the Interface. It's written in terms of the interface, the author has (should have) no interest in the implementation. That's why we provide the Interface class. From that perspective the Abstract Base Class is just one of many possible implementation hierarchies. Don't tell this role about implementation details. Keep the Interface.
Then we have the role who is designing an implementation. They come up with one possible approach and discover some variations, so they want to pull common code together. Abstract Base Class - fill in the common stuff here, let detailed implementers fill in the gaps. Help them by providing abstract methods saying "your code goes here". Note that these methods need not only be the ones in the Interface. Also note that this Abstract Base Class might even implement more that one Interface! (eg. It's CleverThingWorker but also a IntermediateWorkPersister.)
Then we have the role who actually do the fine detailed implementation. Fill in the gaps here. Dead easy to understand. In this case you don't even need to consider the Interface as such. Your job is to make that abstract class concrete.
Bottom line ... I use both Interfaces and Base classes. You put the Interface on the Base Class. We don't add value by adding it to the implementation class.
If your user classes will always inherit from one base class, then you don't need the interface. If there is a possibility that you will have classes that match the interface but are not derived from the base class, then use the interface.
As for the interface being hidden in the base class and hence not immediately visible in the user class, this is normal and can be dealt withg by the compiler. This is also where good naming conventions come in - your UserDataObject has a name that matches IDataObject, as does DataObjectBase. You could add a comment to the class file that says it inherits from IDataObject, but it will be visible that it inherits from DataObjectBase, which in turn looks like it inherits from IDataObject by its name.
The other thing that needs to be mentioned is that the use of interfaces makes it easier to implement automated tests.
Say, for example, that one of the methods of the interface is supposed to throw a exception - such as 'DatabaseConnectionLostException' - and you want to test client code to check that it behaves correctly in such a situation.
It is a simple matter to provide an implementation of the interface that throws the exception, allowing the test to be written.
If you used the abstract base class instead of the interface, this operation would be quite a bit trickier (OK, you can use Mocks, but the interface solution is much cleaner)

A use for multiple inheritance?

Can anyone think of any situation to use multiple inheritance? Every case I can think of can be solved by the method operator
AnotherClass() { return this->something.anotherClass; }
Most uses of full scale Multiple inheritance are for mixins. As an example:
class DraggableWindow : Window, Draggable { }
class SkinnableWindow : Window, Skinnable { }
class DraggableSkinnableWindow : Window, Draggable, Skinnable { }
etc...
In most cases, it's best to use multiple inheritance to do strictly interface inheritance.
class DraggableWindow : Window, IDraggable { }
Then you implement the IDraggable interface in your DraggableWindow class. It's WAY too hard to write good mixin classes.
The benefit of the MI approach (even if you are only using Interface MI) is that you can then treat all kinds of different Windows as Window objects, but have the flexibility to create things that would not be possible (or more difficult) with single inheritance.
For example, in many class frameworks you see something like this:
class Control { }
class Window : Control { }
class Textbox : Control { }
Now, suppose you wanted a Textbox with Window characteristics? Like being dragable, having a titlebar, etc... You could do something like this:
class WindowedTextbox : Control, IWindow, ITexbox { }
In the single inheritance model, you can't easily inherit from both Window and Textbox without having some problems with duplicate Control objects and other kinds of problems. You can also treat a WindowedTextbox as a Window, a Textbox, or a Control.
Also, to address your .anotherClass() idiom, .anotherClass() returns a different object, while multiple inheritance allows the same object to be used for different purposes.
I find multiple inheritance particularly useful when using mixin classes.
As stated in Wikipedia:
In object-oriented programming
languages, a mixin is a class that
provides a certain functionality to be
inherited by a subclass, but is not
meant to stand alone.
An example of how our product uses mixin classes is for configuration save and restore purposes. There is an abstract mixin class which defines a set of pure virtual methods. Any class which is saveable inherits from the save/restore mixin class which automatically gives them the appropriate save/restore functionality.
But they may also inherit from other classes as part of their normal class structure, so it is quite common for these classes to use multiple inheritance in this respect.
An example of multiple inheritance:
class Animal
{
virtual void KeepCool() const = 0;
}
class Vertebrate
{
virtual void BendSpine() { };
}
class Dog : public Animal, public Vertebrate
{
void KeepCool() { Pant(); }
}
What is most important when doing any form of public inheritance (single or multiple) is to respect the is a relationship. A class should only inherit from one or more classes if it "is" one of those objects. If it simply "contains" one of those objects, aggregation or composition should be used instead.
The example above is well structured because a dog is an animal, and also a vertebrate.
Most people use multiple-inheritance in the context of applying multiple interfaces to a class. This is the approach Java and C#, among others, enforce.
C++ allows you to apply multiple base classes fairly freely, in an is-a relationship between types. So, you can treat a derived object like any of its base classes.
Another use, as LeopardSkinPillBoxHat points out, is in mix-ins. An excellent example of this is the Loki library, from Andrei Alexandrescu's book Modern C++ Design. He uses what he terms policy classes that specify the behavior or the requirements of a given class through inheritance.
Yet another use is one that simplifies a modular approach that allows API-independence through the use of sister-class delegation in the oft-dreaded diamond hierarchy.
The uses for MI are many. The potential for abuse is even greater.
Java has interfaces. C++ has not.
Therefore, multiple inheritance can be used to emulate the interface feature.
If you're a C# and Java programmer, every time you use a class that extends a base class but also implements a few interfaces, you are sort of admitting multiple inheritance can be useful in some situations.
I think it would be most useful for boilerplate code. For example, the IDisposable pattern is exactly the same for all classes in .NET. So why re-type that code over and over again?
Another example is ICollection. The vast majority of the interface methods are implemented exactly the same. There are only a couple of methods that are actually unique to your class.
Unfortunately multiple-inheritance is very easy to abuse. People will quickly start doing silly things like LabelPrinter class inherit from their TcpIpConnector class instead of merely contain it.
One case I worked on recently involved network enabled label printers. We need to print labels, so we have a class LabelPrinter. This class has virtual calls for printing several different labels. I also have a generic class for TCP/IP connected things, which can connect, send and receive.
So, when I needed to implement a printer, it inherited from both the LabelPrinter class and the TcpIpConnector class.
I think fmsf example is a bad idea. A car is not a tire or an engine. You should be using composition for that.
MI (of implementation or interface) can be used to add functionality. These are often called mixin classes.. Imagine you have a GUI. There is view class that handles drawing and a Drag&Drop class that handles dragging. If you have an object that does both you would have a class like
class DropTarget{
public void Drop(DropItem & itemBeingDropped);
...
}
class View{
public void Draw();
...
}
/* View you can drop items on */
class DropView:View,DropTarget{
}
It is true that composition of an interface (Java or C# like) plus forwarding to a helper can emulate many of the common uses of multiple inheritance (notably mixins). However this is done at the cost of that forwarding code being repeated (and violating DRY).
MI does open a number of difficult areas, and more recently some language designers have taken decisions that the potential pitfalls of MI outweigh the benefits.
Similarly one can argue against generics (heterogeneous containers do work, loops can be replaced with (tail) recursion) and almost any other feature of programming languages. Just because it is possible to work without a feature does not mean that that feature is valueless or cannot help to effectively express solutions.
A rich diversity of languages, and language families makes it easier for us as developers to pick good tools that solve the business problem at hand. My toolbox contains many items I rarely use, but on those occasions I do not want to treat everything as a nail.
An example of how our product uses mixin classes is for configuration save and restore purposes. There is an abstract mixin class which defines a set of pure virtual methods. Any class which is saveable inherits from the save/restore mixin class which automatically gives them the appropriate save/restore functionality.
This example doesn't really illustrate the usefulness of multiple inheritance. What being defined here is an INTERFACE. Multiple inheritance allows you to inherit behavior as well. Which is the point of mixins.
An example; because of a need to preserve backwards compatibility I have to implement my own serialization methods.
So every object gets a Read and Store method like this.
Public Sub Store(ByVal File As IBinaryWriter)
Public Sub Read(ByVal File As IBinaryReader)
I also want to be able to assign and clone object as well. So I would like this on every object.
Public Sub Assign(ByVal tObject As <Class_Name>)
Public Function Clone() As <Class_Name>
Now in VB6 I have this code repeated over and over again.
Public Assign(ByVal tObject As ObjectClass)
Me.State = tObject.State
End Sub
Public Function Clone() As ObjectClass
Dim O As ObjectClass
Set O = New ObjectClass
O.State = Me.State
Set Clone = 0
End Function
Public Property Get State() As Variant
StateManager.Clear
Me.Store StateManager
State = StateManager.Data
End Property
Public Property Let State(ByVal RHS As Variant)
StateManager.Data = RHS
Me.Read StateManager
End Property
Note that Statemanager is a stream that read and stores byte arrays.
This code is repeated dozens of times.
Now in .NET i am able to get around this by using a combination of generics and inheritance. My object under the .NET version get Assign, Clone, and State when they inherit from MyAppBaseObject. But I don't like the fact that every object inherits from MyAppBaseObject.
I rather just mix in the the Assign Clone interface AND BEHAVIOR. Better yet mix in separately the Read and Store interface then being able to mix in Assign and Clone. It would be cleaner code in my opinion.
But the times where I reuse behavior are DWARFED by the time I use Interface. This is because the goal of most object hierarchies are NOT about reusing behavior but precisely defining the relationship between different objects. Which interfaces are designed for. So while it would be nice that C# (or VB.NET) had some ability to do this it isn't a show stopper in my opinion.
The whole reason that this is even an issue that that C++ fumbled the ball at first when it came to the interface vs inheritance issue. When OOP debuted everybody thought that behavior reuse was the priority. But this proved to be a chimera and only useful for specific circumstances, like making a UI framework.
Later the idea of mixins (and other related concepts in aspect oriented programming) were developed. Multiple inheritance was found useful in creating mix-ins. But C# was developed just before this was widely recognized. Likely an alternative syntax will be developed to do this.
I suspect that in C++, MI is best use as part of a framework (the mix-in classes previously discussed). The only thing I know for sure is that every time I've tried to use it in my apps, I've ended up regretting the choice, and often tearing it out and replacing it with generated code.
MI is one more of those 'use it if you REALLY need it, but make sure you REALLY need it' tools.
The following example is mostly something I see often in C++: sometimes it may be necessary due to utility classes that you need but because of their design cannot be used through composition (at least not efficiently or without making the code even messier than falling back on mult. inheritance). A good example is you have an abstract base class A and a derived class B, and B also needs to be a kind of serializable class, so it has to derive from, let's say, another abstract class called Serializable. It's possible to avoid MI, but if Serializable only contains a few virtual methods and needs deep access to the private members of B, then it may be worth muddying the inheritance tree just to avoid making friend declarations and giving away access to B's internals to some helper composition class.
I had to use it today, actually...
Here was my situation - I had a domain model represented in memory where an A contained zero or more Bs(represented in an array), each B has zero or more Cs, and Cs to Ds. I couldn't change the fact that they were arrays (the source for these arrays were from automatically generated code from the build process). Each instance needed to keep track of which index in the parent array they belonged in. They also needed to keep track of the instance of their parent (too much detail as to why). I wrote something like this (there was more to it, and this is not syntactically correct, it's just an example):
class Parent
{
add(Child c)
{
children.add(c);
c.index = children.Count-1;
c.parent = this;
}
Collection<Child> children
}
class Child
{
Parent p;
int index;
}
Then, for the domain types, I did this:
class A : Parent
class B : Parent, Child
class C : Parent, Child
class D : Child
The actually implementation was in C# with interfaces and generics, and I couldn't do the multiple inheritance like I would have if the language supported it (some copy paste had to be done). So, I thought I'd search SO to see what people think of multiple inheritance, and I got your question ;)
I couldn't use your solution of the .anotherClass, because of the implementation of add for Parent (references this - and I wanted this to not be some other class).
It got worse because the generated code had A subclass something else that was neither a parent or a child...more copy paste.