Is it okay to have a class with just methods

Question from davidv7#2315

would it be ok to just have a class with methods, no class parameters?

aka

class Thing{
    public Thing(){
        
    }
method1(args..)
method2(args...)
}

in java

So specifically if you want to do that you have a few considerations.

Java kinda obscures this, but first consider "Does this method perform a side effect" meaning, does it read from a db, write to a db, print something out, load a file, etc.

If the answer is NO then you can make a "Utils" class

class Utils {
    private Utils() {} // We don't need to construct this class so just disallow it

    // This is a pure function so it is perfectly fine to put it into a helper method like this
    public static absoluteValuePlusOne(int num) {
        return Math.abs(num) + 1;
    }
}

If the answer is YES then there is some value in a class with no parameters. Namely, that class can implement an interface.

Lets say this was your behaviour

MyDataSource dataSource = new MyDataSource();
List<OrderItem> items = dataSource.getItems();

If you wanted to make that behaviour customizable you can put that in an interface.

(IF being a word I want you to notice: When you "abstract" you make code a little harder to understand so always consider if you actually want that)

public interface DataSource {
    // Does a thing
    List<OrderItem> getItems();
}

And use a class with an empty constructor to implement it

public class MyDataSource implements DataSource {
    public MyDataSource() {}
    public List<OrderItem> getItems() {
        // ... Some implementation goes here ...
    }
}

Which provides you the benefit of being able to swap in how that behaviour is done later on or in different places in your code

DataSource dataSource = new MyDataSource(); // Can be any implementation
List<OrderItem> items = dataSource.getItems();
public someMethodInSomeClass(DataSource dataSource, String userId) {
    // ... can do some hoopla and not have to be changed if your method of retrieving data changes
    // (the example is kinda contrived, I know, but basically every programming example is)
}

Using an interface in key places also has implications for how you test your code, but I won't get into that now.


<- Index