Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface for classes that have nothing in common

Lets say I want to make few classes to determine behaviour of agents.
The good practice would be to make some common interface for them, such interface (simplified) could look like this:

interface IModel
{
     void UpdateBehaviour();
}

All , or at least most, of such model would have some parameters, but parameters from one model might have nothing in common with parameters of other model.
I would like to have some common way of loading parameters.

Question

What is the best way to do that?
Is it maybe just adding method void LoadParameters(object parameters) to the IModel?
Or creating empty interface IParameters and add method void LoadParameters(IParameters parameters)?
That are two ideas I came up with, but I don't like either of them.

like image 763
Tomek Tarczynski Avatar asked Feb 28 '23 07:02

Tomek Tarczynski


2 Answers

It only makes sense to use a common interface when you are going to use common code to work against that interface.

In this situation, by definition, there is something in common between the classes.

Remember, interfaces are a contract, but they (conceptually) provide a different contract than inheritance. Instead of forming an object hierarchy, and defining that an object is some concrete form of another object, with interfaces, you're providing a contract that says that the object is usable in a specific way, or acts in specific manner.

In your case, an IParameterBag or similar interface may make sense. Compare this to ISerializable in the base class library. There, you have an interface that can be implemented by anything -but always treated in a single manner.

like image 188
Reed Copsey Avatar answered Mar 29 '23 02:03

Reed Copsey


  • you can have your parameters in a Map, but this is not compile-time safe.
  • you can have a setParameters(..) method which takes IParameters (which doesn't define methods), and use downcasting in each specific implementation

An example for the 2nd option is (Java) CertPathValidator, which takes CertPathParameters as an input, which does not define any methods (apart from clone())

like image 36
Bozho Avatar answered Mar 29 '23 03:03

Bozho