This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
This is not a "how to" question but a "best practices" question. Under what circumstances is it best to use a static class with static methods and when is it best to use a non-static class with non-static and/or static methods. I want to know from the point of view of program efficiency and memory conservation. This class does not have any variables in it. It is simply called by other classes and is passed paramaters in order to provide specific functionality to other classes. Will keeping the class to one instance actually help conserve memory, or will it increase the load on that particular class, given that many different instances of other classes are accessing it?
Classes like these are often called "utility classes," and they generally perform one or two purposes. One, like java.Math, is to offer services for which objects, overriding and subclassing add marginal, if any, value. Sure, someone may want to override Math.rand(), say, but the class writer doesn't bother changing thr nature of his interface to accommodate that. It's far better that Math functions be used as intended -- as a static resource. Factory methods -- which construct objects and return them to the caller -- also make good candidates for static invocation. You can read more about their intended uses from a wide variety of sources on design patterns. There's no question that static classes reduce the amount of memory required by a class, if only because they need no further allocated memory for object instances. There's no meaningful argument, I believe, that they add to the process footprint; they'd add the same overhead if they were non-static. ------------------ Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
Make visible what, without you, might perhaps never have been seen. - Robert Bresson