nice builder pattern]%%apps#quant

For a given class, The more complex its construction, the more you need builders. Builders is probably the solution when you have the most complicated object construction logic. If builder can’t handle it then nothing else can.

Example 1: My quant object ForwardCurve construction takes a lot of inputs including yield curve, repo curve, dividend collection, dividend blending … Each of these inputs are non-trivial quant objects, so it’s sometimes cumbersome to pass all of them into a forwardCurve constructor. As an alternative, we use a builder class to _gather_ the inputs and then call myFwdBuilder.constructCurve().

Optional inputs with default values — (supported in c++ but) not supported in java constructors. Therefore, with 3 optional inputs you may need 8 constructors! With a nested builder class, we need just one, private, simple constructor.

Builder can even use a recursive algorithm.

Prepare, prepare, prepare, build — the last build() is quick and exception-safe. The complexity and error handling is all extracted into the builder class.

With this builder, we have the flexibility to call myFwdBuilder.getCurve() any number of time.

We can also query the builder to get attributes that we can’t put into the final product i.e. the constructed ForwardCurve object. For example, the raw dividend input data should not be part of the fwd object. They are digested, then absorbed into the fwd curve in “digested” form.

Note one builder instance holds one curve + all the building materials for that one curve.

With a builder, all the fields can be public final.

Example 2: The Libor yield curve construction takes at least 3 series of rates (ED deposits, ED futures, swaps). So we use builders to manage the complex construction.

Example 3: The volatility object construction is even more complex.


java visitor pattern – overloading vs overriding, again

In standard visitor, you have a hierarchy of visitable data classes (eg Product and 30 subclasses) + a bunch of visitor classes. In
this case, i have just one visitor class, which defines overloaded methods
Visitor.visit(Futures) etc

Now, I am given a random Product object myProduct. It might be an Option, a Bond, a Futures… but given the multitude of Product
subtypes, it’s too tedious to type-test.

I already have a myVisitor object, so I try calling myVisitor.visit(myProduct). I want it bound to the correct visit() among the
overloads, but guess what — this won’t compile because … (hold your breath)…. there’s no Visitor.visit(Product) defined.

Reason — overloaded method call is resolved at compile time based on declared type of myProduct

Solution — define
abstract Product.accept(Visitor)
Option.accept(Visitor v) {v.visit(this);}

Now, myProduct.accept(myVisitor) would bind the method call to the correct visit(). Why? Well, accept() is resolved at runtime and
binds to Bond.accept() assuming myProduct is a Bond. Inside Bond.accept(), visit(this) is always visit(Bond) — resolved at compile
time like all Overloaded methods.

In conclusion, Visitable.accept(Visitor) is resolved dynamically and Visitor.visit(Visitable) is resolved statically.

What if I create a FriendlyVisitor type? Is accept() dynamic-and-static?

Model dependent on view

See also

The longer version of the guideline is “model class source code should not mention views.” Model class should not be “implemented” using any speficic view. Instead, it should be view agnostic.

Import — view classes are usually in another package. Should not import them.

Reusable — Imagine MyModel uses MyView. MyModel is usable only with MyView and unusable otherwise.

Knowledge of MyView — The fact that MyModel uses MyView implies that MyModel methods need to “open up” MyView to use its members or to pass a MyView variable around. This means whoever using MyModel needs to know something about MyView.

Change/impact — Changes to MyView can break MyModel. It can happen at compile-time (good), or no impact at compile-time but fails silently at run-time. On the other hand, the change/impact from M to V is normal and expected.

Layering — (This is the best illustration of layering principal in OO.) M is at a lower layer below V. Lower layers should be free of higher-layer knowledg.

Separation of concerns — M author should not be concerned with (not even the interfaces of) upper layers. She should focus on providing a simple clean “service” to upper layers. This makes lower-layer classes easy to understand.

Coupling — This is also one of the good illustrations of tight coupling.

Two-way dependency — (This is the best illustration of two-way dependency.) If V is implemented using M, M should not “depend on” V. Basic principal. Two-way dependency is Tight coupling.

Command Object pattern brief notes

Doug Lea (Page 64) said there are many variants of CO. Simplest is a passable object wrapping a single method. Any time you see an (anonymous class) “new Runnable(){” it’s a Command Object. Sooooooo much simpler than the strict CO definition below.

Command object “knows” the receiver — ie HAS-A reference to the receiver
Command object “knows” exactly how to work with the receiver —
Command’s method would call the receiver’s methods.

Q: List the key objects (excluding interfaces) of the pattern? Command, receiver, invoker… Client? could be a non-object, like the main() method.

Q: List the key methods of the pattern? createCommand, setCommand, invoke,

Q: how are the key objects related via HASA or arg-passing or … ?

Q: List exactly at which junctures each object is created? too complicated

— keywords
* decoupled — so much knowledge is in the Command object that the
invoker or receiver need not know each other
* encapsulation — so much knowledge is private in the Command object that the invoker knows none.
* least knowledge — invoker only knows (a group of) command objects, and knows no receiver objects.
* thread pool

This pattern (like many others) treat a “verb” as a noun. It models an action/behaviour as an object.

Adapter pattern demystified

Doug Lea (P59) seems to suggest that an adapter is a wrapper. He also said proxy ,delegate and Composite patterns are all based on this wrapper idea. I find this simplicity refreshing and liberating, in contrast to the long-winded, strict and formal definitions.

I think “delegate” and “adaptee” are synonyms. I think “delegate”, “wrapper”, “adapter” are usually interchangeable. “Proxy” has a more specific meaning in java — reflection, web services …

Key words of Adapter pattern:
* forward — an adapter forward method calls to the adaptee object. Also known as delegating.
* HasA
* single — just a single adaptee in an adapter. Multiple adaptee is … another design.

singleton Q&&A — somewhat contrived

Some answers are found in

q: why not just use a static var?
a: see the article

q: name 2 ways to end up with multiple singletons
a: see the article
A: deserialize
A: reflection

Q: lock-free lazy singleton?

Q: is there no way to subclass a singleton class?

What if i create a nested class inside the singleton? Yes i modify its source code but keeping the private constructor private. Will i get away with an anon inner class that extends the singleton host class?

Q: is it one instance per class loader in a given JVM? Consider eager singleton.
A: i think so

Q: how about lazy singleton?
A: same thing. one instance per class loader.

factory implementations

— these common practices aren’t necessariy following the GoF —
Standard practice inside a factory is a static createXXX() method. I think it doesn’t have to be static.
Another standard type of factory is a one-class factory which is its own factory. Such a class often provides factory methods as static methods.
* constructors must be privatized, to avoid other classes calling it directly.

vistor pattern — my code ^ literature

My GS xml serializer is very close —
* my formatter objects {the visitors?} have overLOADED format(TradeGC) or format(SITradeGC).
* TradeGC and SITradeGC {the visitables?} both have a this.myFormatter.format(this) method. This IS the   entry point.

* double dispatch
* passing “this” around
* formatting logic belongs in the visitor classes.
* overLOADed methods resolved at compile time, based on arg declared type 

—- given a Family of visitable data classes + a family of visitor classes, you want to implement a full matrix. In every combination of visitor/visitable class, there’s special logic. Will the logic live in visit() or accept()? Will see.

Dynamic dispatch can be used only once (not sure why). The other dispatch is static dispatch — A key feature of visitor pattern. By convention, visit() is name of the static dispatch and accept() is the name of the dynamic dispatch ie virtual function.

We always have a visitor instance and a visitable instance waiting in the wings before the show starts. The typical show starts with theVisitable.accept(theVisitor). Entire show runs on a thread, with one method calling another in a call stack. Remember accept is resolved by dynamic dispatch. Within accept(), we see theVisitor.visit(this). This is a funny way of saying theVisitor.visit(theVisitable). This call is resolved by static dispatch.

The specific logic is implemented in a specific visit() method. If there are 3 x 2 combinations, then that many visit() methods.

Note the family of visitable data classes must implement public virtual method Accept(IVisitor)
Note the family of visitor classes should share a common base like IVisitor. IVisitor should declare abstract overload methods like visit(VisitableA) visit(VisitableB) etc.

—- is a simple example using modems. —
* visit(visitable) — defined in the visitor object
** visit(visitable) method is overLOADED — visit(Type1_inFamily), visit(Type2_InFamily), visit(Type3_InFamily). resolved at compile time based on arg declared type. Static dispatch
** myVisitor.visit(this) called by a method in visitable — theVisitableObject.accept(theVisitor)

( This is the confusing part of visitor pattern)
* visitable.accept(visitor) — Ignore until you are clear about the above. Defined inside each visitable object, but usually very thin and adds nothing but confusion.
** I believe accpet(visitor) is usulaly a virtual method resolved at run time by dynamic dispatch

* double-dispatch — passing “this” around
** “double” refers to accept(..) and visit(..). One static one dynamic dispatch
* family — of visitable data-objects
* family — of visitors
* ==> matrix of 2 type hierarchies (see article)

I feel there’s tight coupling between visitable CLASSES and the visitor CLASSES

chain-of-responsibility keywords

#1 lookup — compare: exception handler lookup and method lookup

Compared to jvm’s method lookup, COR lookup can be modelled against business logic, IMO. polymophism is lookup across classes; COR is across objects.

# aggregation — most usages of COR occur on aggregation of objects, where A has a B1, B2 which has a C1…. A request comes to a child object, which can pass it on to the parent, similar to exception/method lookup.

#9 “responsibility” implies multiple objects elect among themselve one to service a client request.