Thomas Thomas - 4 months ago 9
Pascal Question

Add Fields and Methods to classes that inherit from same base without modifying base class

In my application i need to add some extra functionality to 3rd party controls.

An example would be TcxLabel and TcxDBLabel (from DevExpress).
Both inherit from the the same base class.

For those controls i would like to add some fields and methods.

The way i do it today:

TMycxLabel = class(TcxLabel)
private
FMyField1: string;
FMyField2: Integer;
public
procedure DoSomething;
end;


 

TMycxDBLabel = class(TcxDBLabel)
private
FMyField1: string;
FMyField2: Integer;
public
procedure DoSomething;
end;


So basically i have to write everything twice.

One way to achieve it would be modifying the base class those 2 controls inherit from.
But that is not an option - the DevExpress classses / packages should not be modified.

Is there a way to add achieve this?

Answer

Is there a way to add achieve this?

No there is not. Any viable solution is going to be essentially equivalent to your current approach. Since you want the state associated with the instance, you realistically need it to be part of the instance. Which leads you to the solution that you have.

You could contemplate hijacking a field like Tag to store that state, but that would be wrong because Tag is reserved for use by the consumer of the type. Other plausible solutions might involve maintaining a separate list which mapped instance to this additional state. You could make that work but in my view it would be so unwieldy as to be worse than the alternative.

The most effective approach would be to add the fields to a common base class but you have ruled that out since it involves modifying third party code.