views:

76

answers:

2

i wonder if one should create a helper function in a class as a static function or just have it declared as a procedural function?

i tend to think that a static helper function is the right way to go cause then i can see what kind of helper function it is eg. Database::connect(), File::create().

what is best practice?

A: 

Singleton solves the confusion.

MyHelper.Instance.ExecuteMethod();

Instance will be a static property. Benefit is you get simple one line code in calling method and it reuses previously created instance which prevents overhead of instance creation on different memory locations and disposing them.

Ismail
but a static function gives you all that benefits. usage of a static method doesn't even create an instance.
never_had_a_name
Anyway still it may use memory from much before you want to use it.
Ismail
+1  A: 

IMO it depends on what type of helper function it is. Statics / Singletons make things very difficult to test things in isolation, because they spread concrete dependencies around. So if the helper method is something I might want to fake out in a unit test (and your examples of creating files and connecting to databases definitely would fall in that category), then I would just create them as instance methods on a regular class. The user would instantiate the helper class as necessary to call the methods.

With that in place, it is easier to use Inversion of Control / Dependency Injection / Service Locator patterns to put fakes in when you want to test the code and you want to fake out database access, or filesystem access, etc.

This of course has the downside of there theoretically being multiple instances of the helper class, but this is not a real problem in most systems. The overhead of having these instances is minimal.

If the helper method was something very simple that I would never want to fake out for test, then I might consider using a static.

jkohlhepp