I feel like static method's encourage behavior like this. In this case we have a global class with a static function. We are hiding the fact that Foo
depends on StaticWorker.DoWork()
.
Static Method
public class Foo
{
public void Bar()
{
StaticWorker.DoWork();
}
}
On the other hand, instance-level methods encourage passing the dependent object. Which is better than reaching into a global.
Instance Method
public class Foo
{
Worker Worker;
public Foo(Worker worker)
{
this.Worker = worker;
}
public void Bar()
{
this.Worker.DoWork();
}
}
Now of course you could pass in a function, but I still like the abstraction I get with objects.
Another huge benefit of instance-level methods is that the class can implement an interface which you cannot do for a static method.
This is similar to the singleton argument. Singleton's themselves don't cause damage if used properly, but it makes it easier for people to call the singleton all over their code without passing it, once again creating invisible dependencies and global state.
There are exceptions to the rule. Sometimes you have a small, lightweight method. It will never change, and is not a dependency for anything else, I might make it static. You have to use your best judgement on a case by case basis, but I would say favor instances, especially if you have any doubts.
I feel like there are several benefits to using instance methods and all I have to do is instantiate an object. A small price to pay for the rewards.