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.
In general, if your situation requires encapsulation of state or an organizational structure, then you will be using classes.
On the other hand, if you have something that is a cross-cutting concern, and can be used broadly across your application, you might consider methods in a static utility class.
System.Mathin the .NET framework (and Java) is an example of this.In your example, HFile is probably an object with state, so I would not generally use a static method to save it. It’s simpler just to make a method call on the specific HFile object, rather than having to pass the entire object to a static method for saving. Whether that makes sense or not in your particular application depends on whether your application’s paradigm sees HFile objects as things to be passed around and acted on by outside methods, or as standalone objects capable of saving themselves.