interface, dependency&&loose coupl`

If all of YOUR instance/local vars are declared as interfaces, then

1) I can more easily reuse YOUR class in my new project. I can instantiate your object more easily.

2) I can compile it with just those interface source files, without the class source files.

3) Your class doesn’t “depend” on those classes. When those classes change, your class need not recompile.

equals() and improves on STL

The equality-equivalence inconsistency in STL (P84 [[Effective STL]]) is fixed in java collections due to the “consistency” between equals() and Comparable interface —

The natural ordering for a class C is said to be consistent with equals if and only if (e1.compareTo((Object)e2) == 0) has the same boolean value as e1.equals((Object)e2) for every e1 and e2 of class C. In STL, such a contract is not enforced, with multiple implications.

However, java condones/permits an implementation to deviate from this consistency. Consistency is “strongly recommended (though not required)”

It’s instructive to compare this consistency against the equals/hashcode contract in java.

heap-stack dual variable — ptr/ref

Common scenario — you declare a local ptr variable and assign it q(new int), you get a heap-stack var. The object lives on the heap but the ptr var lives on the stack (unless the variable itself is optimized away).

Unfortunately, when the ptr var goes out of scope, you lose the address forever and can’t free the memory.

One best practice is to always new() and delete() an object in the same func.

4 types of methods to instantiate a new object

1) constructor — invoked directly by client methods
2) factory
3) special instance[1] methods to return a new object of its own class. Could be public or private.
4) singleton’s getInstance(). Static

Example of (3): shortcut constructor method.

#1 key question: How do you control access to these methods?
3) you need to get an instance of this class before calling this method. Get a chicken, then an egg.
1) no control
4) no control due to staticity
2) a static factory method offers limited control.

[1] static? less common.