Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grouping static classes with the same behavior

Tags:

c#

I have groups of logic that consist of static classes such as:

static class A {
    static int mutate(int i) { /**implementation*/ };
    static double prop(double a, double b) { /**implementation*/ }; 
}

static class B {
    static int mutate(int i) { /**implementation*/ };
    static double prop(double a, double b) { /**implementation*/ }; 
}

In this case, A and B are static classes that implement the same behavior via a group of functions (e.g. mutate). I would like to use something like an interface for this pattern, however since static classes cannot implement interfaces I am not sure what to do. What is the best way to implement this type of behavior cleanly?

EDIT:

Here is an example of what I am currently doing. The classes have no state so normally I would make them static.

Interface IMutator {
    int mutate(int i);
}

class A : IMutator {
    int mutate(int i) { /**implementation*/ };
}

class B : IMutator {
    int mutate(int i) { /**implementation*/ };
}

class C {
    public List<IMutator> Mutators;
    public C(List<IMutator> mutators) { 
        Mutators = mutators;
    }
}

//Somewhere else...
//The new keyword for A and B is what really bothers me in this case.
var Cinstance = new C(new List<IMutator>() {new A(), new B() /**...*/});
like image 892
shell Avatar asked Jun 29 '16 04:06

shell


1 Answers

The stateless class doesn't have to be static. Moreover, static dependencies isn't a good choice, when you want to write unit tests, or when you want to extract some common interface (as in your case).

It's OK to have non-static classes, containing logic only. E.g., people build ASP .NET applications using stateless controllers.

So, just throw away static and extract an interface.

like image 50
Dennis Avatar answered Nov 03 '22 10:11

Dennis