In the following sample, the writer of the derived class will be expected to call base.Add(). If it happens 1st, the base can do one sort of code. If it happens last, the base can do another kind of logic (see sample). I doesn't seem possible to have it both ways. And easy fix would be do stop calling the base method at all because the base will never know if its being called first, last or in the middle or twice!
What is the object oriented way to deal with this? Should I just plain stop putting code into base methods because I will never know the pre and post-conditions?
EDIT: The goal is to have a business object class that does CRUD operations. The repetitious code would be moved to the base class. For example, checking to see if before adding a record, the business object's id is 0 and checking that after saving, the business object's id is >0.
namespace StackOverFlowSample
{
class BusinessObjectBase
{
private bool _isNew;
private int _id;
public virtual void Add(string newAccount)
{
//Code that happens when subclasses run this method with the
//same signature
//makes sense if base is called 1st
if(_isNew && _id>0) throw new InvalidOperationException("Invalid precondition state");
//makes sense if bae is called 2nd
if (!_isNew && _id == 0) throw new InvalidOperationException("Invalid post condition state");
}
}
class BusinessObject : BusinessObjectBase {
public override void Add(string newAccount)
{
//doesn't make sense, because base will need to be called again.
base.Add(newAccount);//pre validation, logging
//Save newAccount to database
//doesn't make sense, because base has already been called
base.Add(newAccount); //post validation, logging
}
}
}