Morten Nørgaard
Morten Nørgaard

Reputation: 2809

How can I avoid writing an empty template pattern hook method?

I'm trying to apply the template pattern with a 'hook', that's activated by a boolean 'true' value from a virtual method that defaults to false. So my implementing classes can override this to activate the hook. However, the functionality within the hook has to be virtual because not all implementing classes need implement it. The below implementation is not aesthetically pleasing to me - is there a better way, to avoid the default exception throw?

// template pattern applied in this function
    public virtual Tobject CompileEntityFromDocument<Tobject>(document document)
    {
        Tobject dummyObject = CreateEntity();
        SetAttributesForEntity(dummyObject, null, null);
        if (MustSetRelationsForEntity())
        {
            SetRelationsForEntity(dummyObject, null);
        }
        return (Tobject)dummyObject;
    }

    public abstract void SetAttributesForEntity(object entity, document mainDocumentToCompileFrom, List<vfield> documentFieldRecords);
    public abstract Tobject CreateEntity<Tobject>();

    public virtual void SetRelationsForEntity<Tobject>(Tobject entity, List<vfield> documentFieldRecords)
    {
        throw new NotImplementedException("This must be overridden in implementing classes");
    }

    public virtual bool MustSetRelationsForEntity()
    {
        return false;
    }

Upvotes: 0

Views: 340

Answers (1)

MarkO
MarkO

Reputation: 2233

Why don't you simply leave it empty in the base, and let the derived classes override when Relations must be set?

Like this:

// template pattern applied in this function
public virtual Tobject CompileEntityFromDocument<Tobject>(document document)
{
    Tobject dummyObject = CreateEntity();
    SetAttributesForEntity(dummyObject, null, null);

    SetRelationsForEntity(dummyObject, null);

    return (Tobject)dummyObject;
}

public abstract void SetAttributesForEntity(object entity, document mainDocumentToCompileFrom, List<vfield> documentFieldRecords);
public abstract Tobject CreateEntity<Tobject>();

public virtual void SetRelationsForEntity<Tobject>(Tobject entity, List<vfield> documentFieldRecords)
{
    //Do nothing in base
}

Upvotes: 1

Related Questions