tags:

views:

1358

answers:

16

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.

+4  A: 

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.

Anders Abel
+3  A: 

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.

Andy Shellam
Isn't Singleton pretty much an obsolete pattern since IoC?
Christopher Oezbek
IoC? I don't see how it can be obsolete - there are plenty of uses where you only ever need one instance of a class, and IMO the singleton pattern is the best way to ensure this.
Andy Shellam
+1  A: 

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
}
Bozho
+1  A: 

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 ...

JaredPar
+1  A: 

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.

Riduidel
+2  A: 

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.

Jennifer Zouak
+17  A: 

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.

Thomas Pornin
Exactely, there is nothing intrinscally bad with doing structured programming in a OO language. But one is essentially wasting a lot of potential such as using the class and implementation as base cases for more specialized behavior using inheritance, etc.
Christopher Oezbek
+1, just because you have a chainsaw doesn't mean that every single problem is best solved with a chainsaw. Sometimes you really just need a hammer. Sometimes it's just easier to keep it simple.
wasatz
+1 for stating that the question is simply structured programming. Plumbing between Excel and a, let me guess, relational DB? That ain't OO. As long as you don't need OO and you don't call that OO, there's no issue.
Webinator
A: 

"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))

Oxinabox
+1  A: 

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();
Brian Scott
Pedantic note - should it be "return source < 0" as intVal is the type? (And brackets aren't strictly necessary although useful for readability.)
Andy Shellam
oops, I typed too quickly :-) , ammended accordingly.
Brian Scott
A: 

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.

FosterZ
A: 

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.

Striker
+3  A: 

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.

Adriaan Koster
"probably indicates misunderstanding of object-oriented design"... or, they just don't believe all code has to be OO.
John
Traditionally you'd pass in all the dependencies you'd need into a static class, so methods may have more parameters, but you can unit test any dependencies easily. Good module based programming discourages tight module coupling, so you usually don't have modules calling other modules -- but in case you do, you'd rewrite `static void A(someState) { B.HandleState(someState) }` as `static void A(somestate, handleState) { handleState(someState) }`, so can substitute you handler function with any implementation you want, including a call to the original handler module or a mock.
Juliet
@Adriaan Koster: +1... Unit testing that class or needing a mock of that "abstraction" would prove really hard.
Webinator
@John: or they just don't believe all code has to be OO *and* they don't believe in proper testing *and* they're misunderstanding both OO and testing.
Webinator
Because you can't test static methods? Stateless methods can be tested for correctness as long as your testing framework can test non-public methods.
John
-1: because defining a class containing only static methods without any data *does not* mean you can't instanciate it and pass it around or make it part of some class hierarchy.
kriss
@John: #1 - IMO Java coders who don't believe all code their code has to 'be OO' are either working on a small hobby project, or wasting a lot of time swimming upstream. #2 - I was not claiming static methods cannot be tested? I said classes calling static methods in other classes are hard to unit test because you cannot easily mock the dependency.@Juliet: I don't know how to pass methods as arguments in Java (yet). This is currently being considered as Java 7 feature I believe.@kriss: What you say is possible, but terrible OO design IMO.
Adriaan Koster
+2  A: 

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.

Waylon Flinn
+11  A: 

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.

Juliet
Your last point speaks to me. I suppose one can write OOP in procedural languages and procedural in OOP languages and maybe even attempt to write a functional or dynamic style in a OOP or procedural language. In all cases it would be writing code that is fighting the framework it's in and going to be harder to read for a programmer who's expecting OOP in a java or C# program.
MatthewMartin
The large applications you describe probably do not suffer from overzealous OOP, but from bad design. Good OOP design is NOT subclassing everything, although most OOP courses tend to come up with terrible Animal-Mammal-Cow examples which lead you to believe the contrary. Good design IMO is about splitting complexity in a useful way, which allows expected changes in the future without breaking down.
Adriaan Koster
+1 "a brick wall, followed by a mountain"
Mo Flanagan
+2  A: 

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).

bloparod
+1  A: 

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.

mdma