Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips for avoiding Static Method Overuse

I'm refactoring some code and I'm looking at a class called HFile. HFile has all private constructors so that you can't actually create instances of it. Instead of creating instances of HFiles as follow:

var file = new HFile('filename')
file.Save()

all HFile interaction is handled via static methods. So if I wanted to save a file I would call:

HFile.save('filename')

and then internally an instance of HFile would be created and then saved. Obviously without knowing the whole story any reader must reserve judgment, but it seems like using static methods has become very fashionable at my place of work. So I'm wondering if there are good principles/best practices for usage of static methods that can helpful for a group of guys sitting down and reviewing their usage of static methods.

like image 872
Daniel Avatar asked Jan 29 '10 22:01

Daniel


1 Answers

Lots of static methods/static classes is a symptom of proceduralitis -- writing procedural code in an object-oriented language. The best way that I know of to eliminate this kind of thinking is a thorough understanding of object-oriented principles and practices. Using test-driven development and forcing code to be testable will help, because it is much harder to write tests for static classes. Eventually, if you use TDD you naturally gravitate towards more decoupled, OO architectures, if only to ease the testing pain.

like image 120
tvanfosson Avatar answered Sep 28 '22 05:09

tvanfosson