Static Helper Class and Static Instance Class Method vs Extension Method

I am looking for an optimal approach to the following problem.

I would like to see people's opinions on which method they will use, and why, in the following scenario:

I have a Class that is created by the factory when specifying a DateTime.

Which approach should be used?

static "helper" class: Class c = ClassHelper.GetClass(DateTime);
static method for instance type: Class c = Class.GetClass(DateTime);
static class / extension method: Class c = DateTime.GetClass();

Currently, I am more inclined towards a static helper class, since I have never used the static factory method method for an instance class before, but it seems advisable to do this with a static method on the class?

Are there any considerations I should make when it comes to unit testing or test organization?

For the time being, I avoided extension methods when I read that extension methods should be used sparingly, usually if you don't have access to the source that you are distributing?

Greetings

James

+4
source share
2 answers

I have a class that a factory creates when specifying a DateTime. Which approach should be used?

  • static "helper" class: class c = ClassHelper.GetClass (DateTime);
  • static method for instance type: Class c = Class.GetClass (DateTime);
  • static class / extension method: class c = DateTime.GetClass ();

My recommendation is to follow the principle of the simplest thing that can work and code cohesion .

This means that extensions and helper classes should be avoided, and just put the factory function in the definition of the Class class. In addition, factory functions are commonly used here.

+5
source

The problem with any of the static solutions is that other classes may be closely related to your class.

Saying ClassB requires an instance of the class. It calls the static method Class.GetClass(DateTime) in its method. Now say that you want to test ClassB regardless of class. (Or, if you are not testing, you want to reuse ClassB elsewhere with a different implementation of the class, and you do not want to reference the entire hierarchy.) How do you do this?

There are several solutions to this problem. IoC containers and abstract factory pattern are two. They are usually associated with interfaces (which are your friends). They can also be excessive; it depends on what your class does and how it will be used.

+3
source

All Articles