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);
static method on the instance type : 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 extending?
Cheers,
James
The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.
Instance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls . Static methods don't have access to cls or self .
Instance method can access static variables and static methods directly. Static methods can access the static variables and static methods directly. Static methods can't access instance methods and instance variables directly. They must use reference to object.
They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.
I've got a Class which is instantiated by a factory when a DateTime is specified. Which approach should I use?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With