jeudi 17 janvier 2019

Is it wise to have a static method be responsible for creating the object of the class it resides in?

I came across this type of code recently:

final class OnlyMe {
 private int a;
 private int b;

 //setter and getters for a and b.

 private OnlyMe(){}

 public static OnlyMe getOnlyMeObj(int c) {
 // use c value to connect to database
 // to populate a and b     
 if(rs.next()) {
  OnlyMe onlyMe = new OnlyMe();
  onlyMe.a = rs.getInt(1);
  onlyMe.b = rs.getInt(2);

  return onlyMe;
 } 

 // return null for everything else.
 // assume the code is under try-catch block.
 return null;
}

So, its seems like the 'getOnlyMeObj(int)' could be extracted out to another class. But it seems like the developer wanted this class to be only created by that method depending upon the input to that method.

What would be a reason for that?

Is this some type of pattern or anti-pattern or no pattern?

Is there a better solution?

Aucun commentaire:

Enregistrer un commentaire