Alex Rivera | Logout

Tips for avoiding Static Method Overuse

Asked 2010-01-29T22:20:35.547
9

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.

Edit
Report

1 Answer

2

IMO static methods are not useful for the purpose you've described is common at your workplace. Disadvantages of this method:
- what's the point of creating an object that represents a file in order essentially just to call one method on it?
- cannot use interface-based polymorphism

To answer your question, here are some cases where I would use a static method:
- a utility method that does something related to the functionality of the class, but not to any one object. Perhaps it takes an array of objects and compares them. Perhaps it does some generic data manipulation (conversions, etc.).
- where you need to do class-related stuff with class variables
- where you want to implement a singleton design pattern

answered 2010-01-29T22:29:45.227

Your Answer