3

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?

Harke
  • 1,279
  • 4
  • 25
  • 30
  • 3
    Its called a static factory method – Vince Jan 17 '19 at 15:47
  • 1
    It is a static factory method. The private constructor forces you to rely on that method so you get instances that already have all values set (which come from a database). – f1sh Jan 17 '19 at 15:48
  • Thanks for the link. I also read the answer from [this link](https://stackoverflow.com/questions/929021/what-are-static-factory-methods). But is there a better solution for this scenario? – Harke Jan 17 '19 at 15:57

2 Answers2

1

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

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
-2

This looks like Factory method pattern, but implemented not so good. You can also use Abstract factory pattern. More context is required to get what pattern will be the best choice. You also can check if there is a similar kind of problem in your project and how this problem is solved there.

Igor Khvostenkov
  • 714
  • 5
  • 15