W18A
Defensive Programming
- Proactively identify and handle problematic situations to prevent software failures.
- In practice, this means having a lot of checks before the actual logic is executed (Eg. input checks, null checks etc)
- Trust no one! 😤
Pros: higher safety
Cons: redundant checks, more complex, harder to spot errors due to unclear responsbilities
Design By Contract
- Establish clear responsibilities via a contract (eg. expected input, expected output) at design time. All parties abide by the contract to guarantee correct behaviour.
- In practice, this means clearly documenting preconditions, postconditions and class invariants.
- Trust me bro🗿
Pros: cleaner, reduces redundant checks, faster
Cons: code crashes if contract is broken
Providing an interface for others to use with clear preconditions, postconditions and invariants which, when adhered to, guarantees correct and expected behaviour.
A contract generally consists of these 3 components:
The main logic of LSP:
Give an example of a real-life subclass that would violate the given contract:
public class Bird {
/**
* Make the bird fly to the given height
* @precondition given height must be >= 0
*(birds cannot burrow into the ground)
**/
public void fly(float height) {}
}Note: by real-life subclass, I mean some kind of creature that is a type of Bird.
interface Flying {
/**
* Make the creature fly to the given height
* @precondition given height must be >= 0
*/
public void fly(float height);
}
// Not all birds can fly
class Bird {}
// We implement it directly for the birds that can
class Hummingbird extends Bird implements Flying {}
// And don't implement it otherwise
class Penguin extends Bird {}
// And we can apply the interface to other creatures,
// even if they're not birds
class Pterosaur extends Reptile implements Flying {}Exceptions in Java fall under 2 categories:
There's a third category to represent serious and usually irrecoverable conditions like a library incompatibility, infinite recursion, or memory leaks. These are called Errors.
All exceptions and errors in Java extend Throwable.
Thank you for attending!