Static Helper Class vs Static Method on an Instance Class vs Extension Method
I'm looking for a best practice approach to the following problem.
I'd like peoples opinion's on which method(s) they would use, and why, to the following scenario:
I've got a Class
which is instantiated by a factory when a DateTime is specified.
Which approach should I use?
static "helper" class : Class c = ClassHelper.GetClass(DateTime);
Class c = Class.GetClass(DateTime);
static extension class/method : Class c = DateTime.GetClass();
Currently I'm leaning more towards the static helper class as I've never taken the approach of having static factory methods on an instance class before, but it seems to make sense for me to do it with a static method on the class?
Are there any considerations I should be making when it comes to unit testing or organising tests?
I've steered clear of extension methods at the moment as I read that extension methods should be used sparingly, usually if you don't have access to the source you're ext开发者_C百科ending?
Cheers,
James
I've got a Class which is instantiated by a factory when a DateTime is specified. Which approach should I use?
- static "helper" class : Class c = ClassHelper.GetClass(DateTime);
- static method on the instance type : Class c = Class.GetClass(DateTime);
- static extension class/method : Class c = DateTime.GetClass();
My recommendation is to follow the principle of the simplest thing that could possibly work and code cohesion.
This means avoid extensions and helper classes, and just put the factory function in the Class
class definition. Besides this is where people usually put factory functions.
The problem with any of the static solutions is that other classes may become tightly coupled to your Class.
Say ClassB wants an instance of Class. It calls the static method Class.GetClass(DateTime)
in its method. Now say you want to test ClassB independently of Class. (Or, if you're not into testing, you want to reuse ClassB elsewhere with a different implementation of Class and you don't want to reference the entire hierarchy.) How do you do it?
There are multiple solutions to this problem. IoC Containers and abstract factory pattern are two. Generally they involve interfaces (which are your friends). They can also be overkill; it depends on what your Class does and how it will be used.
精彩评论