I'm doing code review and came across a class that uses all static methods. The entrance method takes several arguments and then starts calling the other static methods passing along all or some of the arguments the entrance method received.
It isn't like a Math class with largely unrelated utility functions. In my own normal programming, I rarely write methods where Resharper pops and says "this could be a static method", when I do, they tend to be mindless utility methods.
Is there anything wrong with this pattern? Is this just a matter of personal choice if the state of a class is held in fields and properties or passed around amongst static methods using arguments?
UPDATE: the particular state that is being passed around is the result set from the database. The class's responsibility开发者_运维技巧 is to populate an excel spreadsheet template from a result set from the DB. I don't know if this makes any difference.
Is there anything wrong with this pattern? Is this just a matter of personal choice if the state of a class is held in fields and properties or passed around amongst static methods using arguments?
Speaking from my own personal experience, I've worked on 100 KLOC applications which have very very deep object hiearchies, everything inherits and overrides everything else, everything implements half a dozen interfaces, even the interfaces inherit half a dozen interfaces, the system implements every design pattern in the book, etc.
End result: a truly OOP-tastic architecture with so many levels of indirection that it takes hours to debug anything. I recently started a job with a system like this, where the learning curve was described to me as "a brick wall, followed by a mountain".
Sometimes overzealous OOP results in classes so granular that it actually a net harm.
By contrast, many functional programming languages, even the OO ones like F# and OCaml (and C#!), encourage flat and shallow hiearchy. Libraries in these languages tend to have the following properties:
- Most objects are POCOs, or have at most one or two levels of inheritance, where the objects aren't much more than containers for logically related data.
- Instead of classes calling into each other, you have modules (equivalent to static classes) controlling the interactions between objects.
- Modules tend to act on a very limited number of data types, and so have a narrow scope. For example, the OCaml List module represents operations on lists, a Customer modules facilitates operations on customers. While modules have more or less the same functionality as instance methods on a class, the key difference with module-based libraries is that modules are much more self-contained, much less granular, and tend to have few if any dependencies on other modules.
- There's usually no need to subclass objects override methods since you can pass around functions as first-class objects for specialization.
- Although C# doesn't support this functionality, functors provide a means to subclass an specialize modules.
Most big libraries tend to be more wide than deep, for example the Win32 API, PHP libraries, Erlang BIFs, OCaml and Haskell libraries, stored procedures in a database, etc. So this style of programming is battle testing and seems to work well in the real world.
In my opinion, the best designed module-based APIs tend to be easier to work with than the best designed OOP APIs. However, coding style is just as important in API design, so if everyone else on your team is using OOP and someone goes off and implements something in a completely different style, then you should probably ask for a rewrite to more closely match your teams coding standards.
What you describe is simply structured programming, as could be done in C, Pascal or Algol. There is nothing intrinsically wrong with that. There are situations were OOP is more appropriate, but OOP is not the ultimate answer and if the problem at hand is best served by structured programming then a class full of static methods is the way to go.
Does it help to rephrase the question:
Can you describe the data that the static methods operates on as an entity having:
- a clear meaning
- responsibility for keeping it's internal state consistent.
In that case it should be an instantiated object, otherwise it may just be a bunch of related functions, much like a math library.
Here's a refactor workflow that I frequently encounter that involves static methods. It may lend some insight into your problem.
I'll start with a class that has reasonably good encapsulation. As I start to add features I run into a piece of functionality that doesn't really need access to the private fields in my class but seems to contain related functionality. After this happens a few times (sometimes just once) I start to see the outlines of a new class in the static methods I've implemented and how that new class relates to the old class in which I first implemented the static methods.
The benefit that I see of turning these static methods into one or more classes is, when you do this, it frequently becomes easier to understand and maintain your software.
I feel that if the class is required to maintain some form of state (e.g. properties) then it should be instantiated (i.e. a "normal" class.)
If there should only be one instance of this class (hence all the static methods) then there should be a singleton property/method or a factory method that creates an instance of the class the first time it's called, and then just provides that instance when anyone else asks for it.
Having said that, this is just my personal opinion and the way I'd implement it. I'm sure others would disagree with me. Without knowing anything more it's hard to give reasons for/against each method, to be honest.
The biggest problem IMO is that if you want to unit test classes that are calling the class you mention, there is no way to replace that dependency. So you are forced to test both the client class, and the staticly called class at once.
If we are talking about a class with utility methods like Math.floor() this is not really a problem. But if the class is a real dependency, for instance a data access object, then it ties all its clients in to its implementation.
EDIT: I don't agree with the people saying there is 'nothing wrong' with this type of 'structured programming'. I would say a class like this is at least a code smell when encountered within a normal Java project, and probably indicates misunderstanding of object-oriented design on the part of the creator.
There is nothing wrong with this pattern. C# in fact has a construct called static classes which is used to support this notion by enforcing the requirement that all methods be static. Additionally there are many classes in the framework which have this feature: Enumerable
, Math
, etc ...
Nothing is wrong with it. It is a more "functional" way to code. It can be easier to test (because no internal state) and better performance at runtime (because no overhead to instance an otherwise useless object).
But you immediately lose some OO capabilities Static methods don't respond well (at all) to inheritance. A static class cannot participate in many design patterns such as factory/ service locator.
No, many people tend to create completely static classes for utility functions that they wish to group under a related namespace. There are many valid reasons for having completely static classes.
One thing to consider in C# is that many classes previously written completely static are now eligible to be considered as .net extension classes which are also at their heart still static classes. A lot of the Linq extensions are based on this.
An example:
namespace Utils {
public static class IntUtils {
public static bool IsLessThanZero(this int source)
{
return (source < 0);
}
}
}
Which then allows you to simply do the following:
var intTest = 0;
var blNegative = intTest.IsLessThanZero();
One of the disadvantages of using a static class is that its clients cannot replace it by a test double in order to be unit tested.
In the same way, it's harder to unit test a static class because its collaborators cannot be replaced by test doubles (actually,this happens with all the classes that are not dependency-injected).
It depends on whether the passed arguments can really be classified as state.
Having static methods calling each other is OK in case it's all utility functionality split up in multiple methods to avoid duplication. For example:
public static File loadConfiguration(String name, Enum type) {
String fileName = (form file name based on name and type);
return loadFile(fileName); // static method in the same class
}
Well, personnally, I tend to think that a method modifying the state of an object should be an instance method of that object's class. In fact, i consider it a rule a thumb : a method modifying an object is an instance method of that object's class.
There however are a few exceptions :
- methods that process strings (like uppercasing their first letters, or that kind of feature)
- method that are stateless and simply assemble some things to produce a new one, without any internal state. They obviously are rare, but it is generally useful to make them static.
In fact, I consider the static keyword as what it is : an option that should be used with care since it breaks some of OOP principles.
Passing all state as method parameters can be a useful design pattern. It ensures that there is no shared mutable state, and so the class is intrinsicly thread-safe. Services are commonly implemented using this pattern.
However, passing all state via method parameters doesn't mean the methods have to be static - you can still use the same pattern with non-static methods. The advantages of making the methods static is that calling code can just use the class by referencing it by name. There's no need for injection, or lookup or any other middleman. The disadvantage is maintanability - static methods are not dynamic dispatch, and cannot be easily subclassed, nor refactored to an interface. I recommend using static methods when there is intrinsicly only one possible implementation of the class, and when there is a strong reason not to use non-static methods.
"state of a class is ...passed around amongst static methods using arguments?" This is how procedual programming works.
A class with all static methods, and no instance variables (except static final constants) is normally a utility class, eg Math. There is nothing wrong with making a unility class, (not in an of itself) BTW: If making a utility class, you chould prevent the class aver being used to crteate an object. in java you would do this by explictily defining the constructor, but making the constructor private. While as i said there is nothing wrong with creating a utility class, If the bulk of the work is being done by a utiulity class (wich esc. isn't a class in the usual sense - it's more of a collection of functions) then this is prob as sign the problem hasn't been solved using the object orientated paradim. this may or maynot be a good thing
The entrance method takes several arguments and then starts calling the other static methods passing along all or some of the arguments the entrance method received. from the sound of this, the whole class is just effectivly one method (this would definatly be the case is al lthe other static methods are private (and are just helper functions), and there are no instance variables (baring constants)) This may be and Ok thing, It's esc. structured/procedual progamming, rather neat having them (the function and it's helper)all bundled in one class. (in C you'ld just put them all in one file, and declare the helper's static (meaning can't be accesses from out side this file))
if there's no need of creating an object of a class, then there's no issue in creating all method as static of that class, but i wanna know what you are doing with a class fullof static methods.
I'm not quite sure what you meant by entrance method but if you're talking about something like this:
MyMethod myMethod = new MyMethod();
myMethod.doSomething(1);
public class MyMethod {
public String doSomething(int a) {
String p1 = MyMethod.functionA(a);
String p2 = MyMethod.functionB(p1);
return p1 + P2;
}
public static String functionA(...) {...}
public static String functionB(...) {...}
}
That's not advisable.
I think using all static methods/singletons a good way to code your business logic when you don't have to persist anything in the class. I tend to use it over singletons but that's simply a preference.
MyClass.myStaticMethod(....);
as opposed to:
MyClass.getInstance().mySingletonMethod(...);
All static methods/singletons tend to use less memory as well but depending on how many users you have you may not even notice it.
精彩评论