Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 397
Harke Avatar asked Dec 03 '25 10:12

Harke


1 Answers

This is a static factory pattern. The idea is to create instances of an object via a static (class-level) method and return it. There are several possible uses of this pattern:

  • there might be several possible constructors and you might want to avoid letting the code which needs a new instance choose the constructor
  • if there are multiple factories, confusion can be reduced by their naming
  • this way you have the option of validating some parameters and instantiate only if they are valid
  • you can have factories, which might return subclasses, not necessarily the best thing to do, but still an option

see: see: https://www.youtube.com/watch?v=sOpbAOX5nJs

like image 181
Lajos Arpad Avatar answered Dec 05 '25 22:12

Lajos Arpad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!