Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating static utility methods should not be overused however ? how to avoid it? [closed]

Tags:

java

oop

static


With the time ...lots of utility method are introduced in java project for more complex and simple task.

When using static methods we introduce tight coupling in our code and it make our code more difficult to test, especially if the utility methods are quite complex.

I am just thinking that it now difficult to manage and test these utilities. please guide me in avoiding these utilities methods and how can i organize existing project to remove all STATIC utilities.

Can you help me avoiding static method ?

like image 646
Sanjiv Avatar asked Jun 29 '13 12:06

Sanjiv


2 Answers

There is nothing wrong with having lots of static methods.

Static methods are (or should be, read on) stateless, which makes them the easiest methods to test - there's no setup, just call them.

You don't need mocking, because there is no state to deal with.

Regarding being stateless, technically static methods can be stateful if they use static variables to store state. If this is the case, from a good-design perspective they should be converted to instance methods using instance variables to store state, employing the singleton pattern if required.

like image 84
Bohemian Avatar answered Oct 01 '22 01:10

Bohemian


To contradict the other answers currently available: Static methods are bad!

They do introduce strong coupling. Yes there are cases where it is acceptable. Yes you can make a seam for inside a static method, by making the strategy used inside exchangeable. But as a rule of thumb static are still bad.

To answer the question, how to get rid of static methods. Simple: put them on a proper Object. All statics are gone. Have we improved our code? not much yet. If we replace

callToStaticMethod()

with

new X().callToNoLongerStaticMethod()

we replaced a static call with a constructor call which is essentially just another static method. But now your X is just another dependency, so you can inject it:

class A{
    private final X x;
    A(X aX){
        x = aX;
    }
} 

Note: there is no need to use Spring or any other framework for this. If you feel like it provide a constructor which uses the default implementation. If you are a purist, introduce an interface for X.

Testing A without relying on the implementation of X becomes trivial and obvious. Same for replacing X in any way.

like image 42
Jens Schauder Avatar answered Oct 01 '22 00:10

Jens Schauder