/java/

Grouping Java Utils

2015-04-04 12:53:21

Everybody have some utils in their code. And very often the number of this utils is quite big. If you have the same problem you can start grouping yours utils.

How to group utils ?

Assume you have something like this:

StringUtil

package pl.btbw.common;

public class StringUtil {

    public static void test() {
        System.out.println("string test");
    }
}

MapUtil

package pl.btbw.common;

public class MapUtil {

    public static void test(){
        System.out.println("test map");
    }

}

XmlUtil

package pl.btbw.common;

public class XmlUtil {

    public static void test(){
        System.out.println("xml test");
    }

}

Basically you use them by:

package pl.btbw;

import pl.btbw.common.*;

public class App {

    public static void main(String[] args) {
        StringUtil.test();
        MapUtil.test();
        XmlUtil.test();
    }

}

and OK, that works, but please consider this approach

package pl.btbw;

import pl.btbw.common.*;

public class App {

    public static void main(String[] args) {
        Util.string.test();
        Util.map.test();
        Util.xml.test();
    }

}

to implement this approach you have to create one more class

package pl.btbw.common;

public final class Util {

    public final static StringUtil string = new StringUtil();

    public final static MapUtil map = new MapUtil();

    public final static XmlUtil xml = new XmlUtil();

}

of course name "Util" for this class is only example

ok that is nice (for me), but still programer can use old approach. we can adjust this by adding default constructor and remove static keyword form method

StringUtil

package pl.btbw.common;

public class StringUtil {

    StringUtil() {
    }

    public void test() {
        System.out.println("string test");
    }

}

MapUtil

package pl.btbw.common;

public class MapUtil {

    MapUtil() {
    }

    public void test() {
        System.out.println("test map");
    }

}

XmlUtil

package pl.btbw.common;

public class XmlUtil {

    XmlUtil() {
    }

    public void test() {
        System.out.println("xml test");
    }

}