Methods Flashcards
1
Q
Explain how to check parameters for validity and why this is important
A
- At the very beginning of every method, check that the parameters passed in are valid and throw the appropriate exception if one of them is not valid. Make sure to document this in the javadoc.
- This means we fail at the first point of failure instead of somewhere completely unrelated, making the source of error hard to track down. The type of error thrown is also appropriate.
- If the method is not public, you should do assert instead, which throws AssertionError if a problem is found. This allows checking to be turned on and off at will.
- In some cases where checking for validity is expensive, the check maybe skipped.
2
Q
Explain why defensive copies are sometimes necessary
A
- Java is generally a safe language - buffer overflows and accessing out of bound array will not affect a class accidentally. However, a class may still accidentally provide access to its fields, allowing clients to modify the fields outside of the class, causing class invariants to be invalid. This is why there’s a need for defensive copying.
- Every time client pass in an object, remember that client will still hold reference to the same object and is free to do whatever they want with the object afterward. Make sure you make a defensive copy of the object if this is not desirable.
- In addition, if you provide getter, make sure to return a defensive copy if you don’t want client to mess with internals or the object.
- If the class is not public or modifying the underlying object will only hurt the client, you may opt to not do defensive copying, but this should be documented.
- If the passed in object is immutable, there’s no need to do any of this, so prefer immutable whenever possible.