Search code examples
javachaining

Java - Class Chaining


Assume that you have following Classes with static defined methods.

  • kubeUtils
    • KubeUtils
    • controllers
      • ConfigMapUtils
      • DeploymentUtils
      • ...
    • objects
      • PodUtils
      • NamespaceUtils
      • ....

each class has some methods like

public static void waitUntilServiceIsPresent(String serviceName){
  // implementation...
}

public static void waitUntilServiceDeletion(String serviceName){
  // implementation...
}

public static void waitUntilServiceIsUpdated(String serviceName){
  // implementation...
}

and so on...

So in the user view we need to call it like: ServiceUtils.waitUntilServiceIsPresent(serviceName);

What i need for syntax sugar will be using Class chaining but i have no idea how i can possibly do it. Example:

KubeUtils.ServiceUtils.waitUntilServiceIsPresent(serviceName)

or 

KubeUtils.getServiceUtils.waitUntilServicePresent(serviceName)

remember that i have only static methods in these classes and i do not want to use composition. My goal is to use this methods without creating an object. Hope, my explanation is clear.


Solution

  • I will go ahead and say that I don't think it's good practice, but as an exercise: You can achieve this by having inner classes:

    public class KubeUtils {
        public static class ServiceUtils {
            public static void waitUntilServiceIsPresent(String serviceName){
                ...
            }
        }
    }
    

    Calling:

    KubeUtils.ServiceUtils.waitUtilServiceIsPresent(...);
    

    For better practice, I would maybe use a package structure to structure your utility classes like so:

    com.domain.project
    ├── kube
    │   ├── ServiceUtil
    │   └── FooUtil
    └── bar
        └── BazUtil