Java as a Procedural Language

by Piotr Likus on November 20, 2015

Java is not a pure object-oriented language – I’m sure everybody agrees on this. But not many people say it loud that you can do a procedural programming in Java. In fact, you see it every day while working with Java – utility classes, math functions, random numbers, constant containers. Most obscure and painful to modify is utility class – see below.

Utility classes

Example of utility class:

public final class CalendarUtils {

    private CalendarUtils() {} 

    /**
     * Returns true if given date is Saturday or Sunday
     * @param date date to be verified
     * @return true if given date is in weekend, otherwise false.
     */
    public static boolean isWeekend(Date date) {
         Calendar calendar = Calendar.getInstance();
         calendar.setTime(date);
         int dow = calendar.get(Calendar.DAY_OF_WEEK); 

         return (dow == Calendar.SATURDAY) || (dow == Calendar.SUNDAY);     
    } 
}

Is this wrong? It depends – on few things:

  • if there will be any need to adapt the code to local site needs
  • if you need to mock-out this class or it’s method in your unit tests
  • if the code needs any configuration or state data
  • if the code will need any objects injected

Procedural code (especially in utility classes) cannot be replaced easy (without bytecode manipulation or .class file replacement), so even if you have full access to class code (or you successfully decompiled it) you will still need to copy some code if you decide to use replacement class (using different name or by putting it earlier on class path). But creating such a replacement leads to copy-paste anti-pattern and possible initialization issues. Also utility class does not implement any interface and is usually not injected, so during testing you will have a problem while trying to replace it by a mock object.

How to avoid this problem?

  • move common code to an existing, related non-static class
  • create normal class, use specific class name for your needs (like WeekendCalculator), inject it, limit responsibility of this class
  • write a wrapper function which calls utility method, this wrapper can be overridden by a derived class

Example of wrapper function:

public class MyClass {
    protected boolean calcIsWeekend(Date date) {
       return CalendarUtils.isWeekend(date);
    } 
}

Summary

Of course there will be always a need to use utility classes, but limiting it can make your code more flexible in the future. Do you know any other aspects of Java programming that make you feel like programming in C or Pascal? Please let me know.

Resources

Fonts by Google Fonts. Icons by Fontello. Full Credits here »