Home > Software design >  Interface method with different parameters
Interface method with different parameters

Time:01-26

I have assign subjects to certain group, there's multiple algorithms to do this but they need various of method parameters to calculate output.

For example we can have

interface Algorithm {
   randomize(???) : int
}

class A implements Algorithm {
   randomize(int, int) : int
}

class B implements Algorithm {
   randomize(int, int, string) : int
}

The idea is to add another method for the Algorithm interface, setup() and create structure like this

abstract class Configurer {
   private __constructor;

   // for which subject we need to take info. from db 
   init(int $subjectId) : Configurer
   setup(Algorithm) : void;
}

interface Algorithm {
   randomize() : int
   setup(Configurer) : void
   isConfigured() : bool
}

It solves problem of parameters which are stored in db but i still don't know how to handle additional parameters passed by users in form. Should i pass also form parameters as array to Configurer::init ?

CodePudding user response:

You can have variable amount of parameters passed in:

interface Algorithm {
    public function randomize(mixed ...$params): int;
}

then when using it:

$a = new A();

// Call in different ways:
$a->randomize(someParameter: 1, anotherParameter: 2);
$a->randomize(...['someParameter' => 1, 'anotherParameter' => 2]);
$a->randomize(1, 2);

CodePudding user response:

It sounds like you're trying to design a system for configuring and running algorithms that take various parameters. One approach you've proposed is to add a setup method to the Algorithm interface, which takes an instance of a Configurer class that is responsible for fetching the parameters from the database and passing them to the algorithm.

One way to handle additional parameters passed by users in a form would be to pass those parameters as an array to the Configurer::init method, along with the subject ID. The Configurer class can then use the subject ID to fetch the parameters from the database, merge them with the additional parameters from the form, and pass the combined set of parameters to the algorithm using the setup method.

Alternatively, you could create another method in the Configurer class to handle the additional parameters, such as initWithFormParams(int $subjectId, array $formParams), which could then merge the form parameters with the parameters from the database and call the setup method on the algorithm with these parameters.

It all depends on how you want to handle the additional parameters and what makes most sense in the context of your application.

  • Related