1/55
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
precondition
a condition that must be true right before executing the code
defensive programming
The practice of writing code that anticipates and safely handles incorrect, unexpected, or misuse scenarios to make the software robust
Always assume the consumer (user / caller) of your code is a rookie
In case preconditions are not satisfied, implementer should do a null-check at the beginning of the method
postcondition
A condition that must be true right after executing the code, provided that the preconditions were satisfied
Class invariant
A condition that should ALWAYS be true
Right after creation of the object
Before and after any operation in the object
java assertion - when to use it
When the “precondition” is violated, you should check it and warn the user right away
java assertion syntax
assert condition;
assert condition : explanation;
Enable assertions:
-enable assertions
Short form: -ea
if assertion is true
the rest of the code executes
if assertion is false
an AssertionError exception is thrown, and a message will be shown on the console (includes class name and line number)
(no further code is executed)
exception - when to use
To catch a failure (eg precondition violation), it is also common to throw an exception
root of Exception hierarchy
“Throwable” class
Exception tree

Types of exceptions in java (2)
checked
unchecked
unchecked exceptions
the compiler does not check them at compile time
all subclasses of RuntimeException are unchecked
NullPointerException & IndexOutOfBoundsException
Checked exception
The compiler checks them at compile time
We need either catch them by try-catch block or list them in the throws clause of the method
Try-catch: a catch clause gains the control of the program’s execution if …
A statement inside the try-block throws an exception
A method called from inside the try-block throws an exception
finally block (after try-catch)
The code in the finally block will always be executed; we usually put cleanup code inside finally block
how to order the catch block (parameters)
Order exceptions from most restricted to the least restricted
Creating a new Exception class
It must extend Exception class
It should have at least one constructor
The constructor should have an argument of String type
The string is used to signify the reason for the exception
In the constructor, just call the constructor of the super-class

When to use Precondition / Postcondition / Class Invariant vs Exceptions
In private methods, using preconditions/postconditions/class invariants is OK
In public methods, throwing exceptions is more appropriate
Liskov Substitution Principle (LSP)
Derived classes must be substitutable for their base classes
aka Subclasses must be substitutable for their superclass

❤ Precondition of the subclass should be …
either the same as the superclass or weaker
Interface Segregation Principle (ISP)
Make fine grained interfaces that are client specific
aka Make smaller interfaces that are customized to a specific client.

Added the new animal sparrow and two features walk and fly
What is the issue with this and how do you fix?
Animal interface is too “big” or “polluted” for the concrete classes
Instead:
Segregate (split) the big interfaces into smaller ones
We can split Animal interface into 3 smaller interfaces: WalkableAnimal, FlyableAnimal, Animal

Java Object Class
All java classes are directly or indirectly subclasses of “Object class”
If your class doesn't extend another class, it extends directly Object class, even though you don't mention it
toString Method - goal and default behavior
Goal: creating a descriptive string to represent the object’s STATE
Default behavior: returns a string containing the object’s package name, class name, and a hash key in hex format
Equals Method - goal and default behavior
Goal: checking equality of two objects
Default behavior: uses ==
what does x == y mean in Java?
it checks whether x and y are references to the same object, called the identity test
clone method - goal and default behavior
Cloning means copying/pasting an object
Default behavior: shallow copy
Class needs to implement Cloneable interface in order to clone (otherwise, JVM throws an CloneNotSupportedException)
reference variable copy
Objects share a reference, it is the same object
Shallow copy
Shallow copy: If X and Y are objects, and Y is a shallow copy of X, then:
All primitive attributes of X are copied into Y
Both X and Y share the non-primitive instance variables
If an immutable object changes, a new object will be created
If a mutable object changes, it remains shared
Note: Static attributes remain shared
deep copy
If X and Y are objects, and Y is a deep copy of X, then:
All attributes are copied into Y
how to deep copy
override the clone method
call object’s default clone method for shallow copy
clone only instance variables that are mutable
Java type
A type is defined as:
A set of values (objects)
A set of operations (visible methods or behavior) that can be carried out with those values
Ex. int (primitive type) or Employee class (Java type)
type violation
When you assign / pass a value to the wrong type variable / argument
Example: int x = “Hello”;
Compile or runtime detection of type violation (which is better)
Compile-time, the sooner we catch the error, the lower the cost
Most rules for Java types are validated in compile time
Java types (5)
Primitive, class, interface, array, null
Interface type
Interface type is only used for declaration, not instantiation
Interface type can be used for:
Variables (local, instance)
Method arguments
Return types
Values in Java
Any value in Java is one of the following:
A value of a primitive type
A reference to an object
A reference to an array
null
type-subtype relationship is used for
polymorphic relationships
Why did java create wrappers?
in some cases, we need the primitive types fulfill as an object

instanceOf operator
It returns true if emp refers to an object of Employee or one of its subtypes
A good place to use instanceof operator is before casting to make sure that the casting won’t fail
Class Class
JVM associates an internal object of Class type to each class in your app
So class object holds all needed data about all objects of a class
access Class object (3 methods)
Use getClass() method of Object class
Employee emp = new Employee();
Class c1 = emp.getClass();
Using Class literal
Employee emp = new Employee();
Class c2 = Employee.class;
class literal is a static reference to Class object (which is why we use Employee class name, not emp object)
Using Class.forName(String className) - not reccommended
Class c3 = Class.forName(“package.Employee”);
How to precisely check object type of a variable
if (emp.getClass() == Employee.class) {}
checking returns true if emp is exactly Employee object
Enumerated types
special data type in programming that defines a fixed set of named constants
In java, enum is a class type

generics
generic type (general purpose) for any kind of classes
is there type subtype relationship between generic types?
no
generic method
a method with one or more type variables
Example: write a generic method, called printList that prints elements of an ArrayList of any type
generic class
A generic class is a class with one or more type-variables
Example:
Write a generic Box class that simulates a box of any type of objects such as Integer, String, Cat, etc…
We can put some objects into it, remove some objects, and print its contents
To get familiar with a useful Java collection, we use Java HashSet as the underlying data structure
Type bound
a restriction applied to generic type parameters
Wildcards (3 flavors)
? = any type
? extends E = all subtypes of E including E itself
wild card with upper bound
? super E = all supertypes of E including E itself
wild card with lower bound

Law of Demeter
A class should only call direct members of the other classes
Example (bad): SomeType foo = objA.getObjB().doSomethingB();
Loose Coupling
ClassA is loosely coupled with ClassB if the only information ClassA has about classB is whatever classB exposes through its interface
LoD tries to keep the degree of coupling at the loose-coupling level
Tight Coupling
ClassA is tightly coupled with ClassB if ClassA has some information about how ClassB is implemented (i.e more than just interface)
ClassA depends on B’s internal implementation, meaning if ClassB changes, classA is likely to break!
Solutions for LoD
Remove the dependency of ClassA
If your class has dependency on ClassA, then write a wrapper in ClassA to hide ClassB
Serialization
The mechanism of converting objects (states) into stream of bits