Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design question: Java Class with single method ok?

Tags:

java

class

I need the following functionality

Given two sorted lists, merge them

I have this skeleton Java code:

public class MergeLists{
   public List merge(List l1, List l2){
      List l3;
      // merge l1, l2 in to l3
      return l3;
   }

   public static void main(){
      // populate list1 and list2
      MergeLists ml = new MergeLists();
      List l3 = ml.merge(l1,l2);
   }
}

Is this single method class the right approach? I feel like the almost-empty class is staring at me to say that this is bad design. I initially had List L3 as private member of MergeLists but then I thought, merge(l1,l2) can be called multiple times with the same object, which required l3 to be local to merge(l1,l2). I read that using static method is even worse for code re-usability. Please advise. Thank you.

like image 692
snk Avatar asked Sep 08 '10 17:09

snk


People also ask

Can you create a class with only static methods?

Classes with only static methods is a common pattern in Java for utility methods. Examples in the standard library include Files, Collections, and Executors. For such utility classes, it's a good idea to make sure that your class cannot be instantiated, to make the intent of the class clear.

Can a class contain methods only?

Classes without methods (data class) are often accompanied with classes that contain only methods. A typical name for these classes with nothing but methods is SometingService. So you will see a User data class and a UserService class that contain methods to do operations on User objects.

Can you have two of the same methods in one class?

Having two or more methods named the same in the same class is called overloading. It's not overloading if you have the same method name in two different classes.

Can two classes have method with same name?

Yes, we can define multiple methods in a class with the same name but with different types of parameters.


1 Answers

You can do this, but I think you want the merge method to be static. This will make sure that you don't have to instantiate it before calling the method. You can just do this:

List l3 = MergeLists.merge(l1,l2);

Additionally, if this is the only method and it's static, you can make the class abstract which means it cannot be instantiated.

like image 131
Erick Robertson Avatar answered Sep 26 '22 21:09

Erick Robertson