Grouping static classes with the same behavior

I have logic groups 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 using a group of functions (e.g. mutate). I would like to use something like an interface for this template, however, since static classes cannot implement interfaces, I'm not sure what to do. What is the best way to implement this type of behavior?

EDIT:

Here is an example of what I'm doing now. Classes have no state, so 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() /**...*/}); 
+6
source share
2 answers

The stateless class should not be static. Moreover, static dependencies are not a good choice when you want to write unit tests or when you want to extract some kind of common interface (as in your case).

It is good to have non-static classes containing only logic. For example, people create ASP.NET applications using stateless controllers.

So just throw away static and extract the interface.

+5
source

Besides the answer of @Dennis (which I have + 1'ed, and that really is the way to go), another approach that can work has a set of functions ( Func<> ) and / or actions ( Action<> ) and allow them using reflection . The code would not be particularly elegant and functional, but it works.

I made a quick example in dotnetfiddle

+2
source

All Articles