dev ツ dev ツ - 1 year ago 73
Java Question

Non static methods vs Utilty with static methods

I am creating an application in Java which performs data movement task (like copy, move, etc.)

At the higher level, I can provide these operations on object level.

Sample code:

public class DataSource {

public boolean copy(DataSource dsDestination);

public boolean copy(DataSource dsDestination, Filter filter);

public boolean move(DataSource dsDestination);

public boolean exists();

// some other 10-15 methods


Or I can provide a utility with static methods:

public class DataSourceUtil {

public static boolean copy(DataSource dsSource, DataSource dsDestination);

public static boolean copy(DataSource dsSource, DataSource dsDestination, Filter filter);

public static boolean move(DataSource dsSource, DataSource dsDestination);

public static boolean exists(DataSource dsSource);

// some other 10-15 methods


Which one is better approach in terms of memory management?

Answer Source

The golden rule is: static is an abnormality within good OO design. You only use it if there are good reasons to do so.

You see, static leads to direct coupling between your classes. And it makes testing harder. Of course, the static methods themselves can be easily tested, but what would happen if you want to test a method that calls those static methods (and you have the need to influence what the static method is doing)? Then you might be tempted to turn to Powermock in order to mock those static calls. Which is not really a great idea.

If you insist on separating functionality, you better use interfaces, like:

public class DataSource {
 ... ctor, equals, ... methods

public interface DataSourceCopyAbility {
  public void copy(DataSource source, DataSource destintion);

plus corresponding impl class.

EDIT: of course, convenience can be a valid reason to use static methods; for example I am using Objects.requireNonNull() all the time in code. But: those are standard API calls. When I am using them in my code, I really dont mind them to be running. I know that will never ever want to "mock" around such kind of static method invocations!

Finally: I assume you want to return true when your operations passed. Bad idea: booleans should only be used to distinguish between true and false. They are not return codes!

If such a complex operation as copying a DataSource fails - then throw an exception! Or if you really want to go without exceptions, define your own specific ReturnCode class that gives you insight into failing operations!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download