开发者

Constructor takes two Integers and they must not equal, whats the best way to implement this?

public MyClass(Integer userId, Integer otherId) {
  if(!userId.equals(otherId)){
    this.userId = userId;
    this.otherId = otherId;
  }
}

Thats as far as I got, I want开发者_如何学Python to ensure an instance if never created with matching id's ?


If you can't allow the two values to be equal then pretty much your only option it to raise an exception in that case.


I created another method and made the constructor private, it returns null if matching ids

private MyClass(Integer userId, Integer otherId) {
 {
    this.userId = userId;
    this.otherId = otherId;
  }
}
public static  MyClass getInstance(Integer userId, Integer otherId) 
  if(!userId.equals(otherId)){
    return new MyClass(userId,otherId);
  }

  return null;
}


I might be completely missing the point of your design, but if you want to create instances of an object with unique ID's that never clash consider using a UUID. Your instances should never have to do a 'circle-jerk' of ID comparisons to make sure none of them are violating the uniqueness constraints.

Documentation on UUID.


I use another approach, I keep a registry of newly created instances (in an HashSet) and allow instatiation of Objects via a static factory.

class User {
  private int _id;

  private static HashSet _instanced = new HashSet();

  public static User getInstance(Integer id) {
    if (_instanced.contains(id)) {
      return null;
    }
    return new User(id);
  }

  private User(Integer id) {
    _id = id.toInt();
  }

  // Getter/Setter for ID
}

Since the constructor is private, none will instantiate another User with the same id.

in your methods you could then write

User x = User.getInstance(1);

Of course this will add one more level to your solution. Still I prefer this kind of approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜