javastaticinstanceencapsulationinstance-variables

How can I determine when is more convenient to use static methods instead of instance ones? Encapsulation is the preferable choice?


I am basically writing static methods that perform work on a list of strings but I can't quite determine if it would be better to create instance variable and do all the work internally. In case my question isn't clear: what needs to be accounted for when makes this decision? If encapsulation needs to be always the first choice, then I guess I would be better in choosing instance variables and methods.

Methods:

public static List<String> split(String string)
{
    List<String> list = new ArrayList<>();
    ...
    return list;
}

public static int count(List<String> stringBlocks)
{
    ...
    return counter;
}

private static List<String> createList(List<String> stringBlocks, int currentCap, int lastCap)
{
    List<String> list = new ArrayList<>();
    ...
    return list;
}
    
public static List<List<String>> makeJoinedLists(List<String> stringBlocks)
{
    List<List<String>> lists = new ArrayList<>();
    ...
    return lists;
}

public static List<String> performWork(List<List<String>> lists)
{
    List<List<String>> lists = new ArrayList<>();
    ...
    return lists;
}

Solution

  • What you are showing in your code is a Utility Class. It consists solely of static methods and has no own member fields. Ensure that you set its constructor to private, so that it cannot be instantiated by accident and you are fine.

    But this does not have to do with encapsulation. Encapsulation means that you access the member fields of a class only via its methods. It does not mean that the methods of the class call other methods of other classes (static or not doesn't matter) with their own member fields as parameters. In fact I think that a program without such calls would not be useful.

    What you should think about is testing: if you want to unit test the code that uses your utility class, it will be hard to test just the calling code without actually running the utility classes code as well (but then it's not a real unit test anymore). It is possible to have the static methods "mocked", but it is not very clean and hard to understand how that works so it could easily confuse a reader of the code and test.

    So to design for testability you should not make those methods static, but regular methods of the object - so it will become easier to create a mock object of your class and use that in unit tests.