Defensive copy of Calendar

前端 未结 7 1395
面向向阳花
面向向阳花 2021-01-04 00:38

Been trying to find the best way to implement a method that makes a defensive copy of a Calendar object.

eg:

public void setDate(Calendar date) {
            


        
相关标签:
7条回答
  • 2021-01-04 01:13

    I know this is old but I thought I'd put in my two cents.

    If you program by contract, an object isn't responsible for another object's mistakes. Calendar implements Cloneable, which means the subclasses do too! If a subclass of Calendar breaks the Cloneable contract, it is the subclass that needs to be corrected, not the class calling clone.

    In OO programming, an object should only care about classes & contracts it is involved with. It complicates the design greatly, by factors, when you ask "what if a subclass breaks it?" Whenever an object takes an object as a parameter, there is always the chance the object is a subclass and breaks everything. Do you program defensively when you call getX() that it doesn't throw a ArithmeticException exception for subclasses?

    Jon Skeet provided a great answer too, better than mine, but I thought that a potential stumbler onto this question may benefit from hearing a minor bit of 'Design By Contract'. While the approach is near dead, the methodology has helped my designs quiet a lot.

    0 讨论(0)
提交回复
热议问题