c++factory usually heapy

Java factory has little (any?) choice, but focus here is c++ factory techniques. I think it usually has to manufacture on heap.

In specialized cases, my factory can maintain a private pre-allocated object pool, carved out from heap, so the factory returns objects from this pool, without calling new().

To my surprise, some c++ factories actually return by value, as illustrated in both [[c++cookbook]] and https://herbsutter.com/2013/05/30/gotw-90-solution-factories/ RVO and move-sematics would likely kick in.

nonVirtual1() calling this->virt2() #templMethod

http://www.cs.technion.ac.il/users/yechiel/c++-faq/calling-virtuals-from-base.html has a simple sample code. Simple idea but there are complexities:

  • the given print() should never be used inside base class ctor/dtor. In general, I believe any virt2() like any virtual function behaves non-virtual in ctor/dtor.
  • superclass now depends on subclass. The FAQ author basically says this dependency is by-design. I believe this is template-method pattern.
  • pure-virtual is probably required here.

factory patterns explained graphically

https://vivekcek.wordpress.com/2013/03/17/simple-factory-vs-factory-method-vs-abstract-factory-by-example/ has nice block diagrams and examples.

  • CC) “Simple factory” is the most widely used one but not a widely known pattern, not even a named pattern. “SimpleFactory” is just an informal name

I mostly used simple factory and not the other factory patterns.

Any time I have a method that creates and returns polymorphic objects from a family (like different Trades), I would name the entire class SomeFactory. I often add some states and additional features but as a class or struct, it is still a simple manufacturer.

  • BB) factory method — a family of manufacturer classes. Each supports a virtual create() method. Each is responsible for instantiating just one specific type of object. NokiaFactory.create() only creates NokiaPhone objects.
  • AA) AbstractFactory — too complex and needed in very special situations only.

factoryMethod: based on arg ^ host object

I used to believe a factory method always relies on arg to tell it what type of instance to manufacture.

Now I know you can call myFactoryInstance.makeTrade(); // no arg, but the host object provides the clue as to what type of instance to manufacture. The factory method is virtual.

See https://stackoverflow.com/questions/5739611/differences-between-abstract-factory-pattern-and-factory-method


  • t_c++pattern — must be a named pattern
  • t_c++idiom — must be well-established small-scale
  • t_ECT and t_c++idiom are mutually exclusive
  • t_tecniq — higher than syntaxTips, less selective than t_c++idiom or t_c++pattern but Should NOT be dumping ground
  • t_implBestPractice is like gentmp

j4 factory: java^c++ #Wells

A Wells Fargo interviewer asked

Q6: motivation of factory pattern?
Q6b: why prevent others calling your ctor?

  • %%A: some objects are expensive to construct (DbConnection) and I need tight control.
  • %%A: similarly, after construction, I often have some initialization logic in my factory, but I may not be allowed to modify the ctor, or our design doesn’t favor doing such things in the ctor. I make my factory users’ life easier if they don’t call new() directly.
  • AA: more importantly, the post-construction function could be virtual! This is a sanctioned justification for c++ factory on the authoritative [[c++codingStd]] P88
  • %%A: I want to (save the new instance and) throw exception in a post-construction routine, but I don’t want to throw from ctor
  • %%A: I want to centralize the non-trivial business rule of selecting target types to return. Code reuse rather than duplication
  • %%A: a caching factory
  • %%A: there are too many input parameters to my ctor and I want to provide users a simplified façade

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 http://bigblog.tanbin.com/2008/01/dependency-rigid-fragile-oo-design.html

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 http://www.javaworld.com/javaworld/jw-01-2001/jw-0112-singleton.html

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?
A: http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

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.

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.

—-http://www.objectmentor.com/resources/articles/visitor.pdf 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.

pure VO wrapped in a domain object

why do Viktor and many java data modelers prefer to break a domain object into a pure VO and a wrapper object hosting the behavior or api methods?

Here’s a pratical reason. There’s negligible downside but increasing benefit as the object gets bigger. The one-class design can present hundreds (for a large object) of fields and methods, some belong to the VO, some obviously not. Hard to read. At some point you end up splitting the class anyway, for maintainability and readability. Why not adopt a coding standard?

A purist design is to have the VO as a public inner class of the wrapper. Argument — the VO should never exist outside.

A bad design is to make the wrapper a factory. The wrapper should still be a domain model. One instance represents one real-world instance.

composite pattern (complicated!) — keywords

tree —

apache tiles — a good eg of the tree concept

subtree — a subtree and a leaf are treated the same, as 2 “components” — a lifeless abstract jargon.

operations — an operation can be an instance method (polymorphism) of the component, or can be a method accepting an arg of the component’s type.

Now the most important keyword is …

transparency — clients can treat subtree or leaf uniformly. Simply put, they share a supertype (interface or superclass). Transparency is big in OO layer design. Transparency means separation of concern.

Once you wrap your mind around it, you may finally sigh a sigh of relief and realize Composite is a simple and practical device (like factory, template method, State)

See [[head first design patterns]] for a simple eg.

singletons complicate unit tests@@

http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial gave 2+1 /indictments/ against singletons in general. The first indictment is testability.

Not easy to introduce a mock/stub for the singleton.

xp: in %% FTTP parser, I saw no real problem. The “user” is LoaderFactory.java. I could be wrong but don’t think it and my singleton are tightly coupled, and complicating unit test.

DAO study notes

Data Access Objects can be used in Java to insulate an application from the underlying Java persistence technology, which could be JDBC, JDO, EJB CMP, TopLink, Hibernate, iBATIS. Using Data Access Objects means the underlying technology can be upgraded or swapped without changing other parts of the application.

j4: The DAO completely hides the data source implementation details
from its clients.
j4: Because the interface exposed by the DAO to clients does not
change when the underlying data source implementation changes, this
pattern allows the DAO to adapt to different storage schemes without
affecting its clients
if (dao == null) dao = CatalogDAOFactory.getDAO();
return dao.getProducts(categoryId,…)
comprehensive but simple sample code

justification for using factories ] FTTP parser

* Justification for moving scan4Uplink() from FTTPCktLoader.java into UplinkFactory.java:
* Indeed it was proven functionally acceptable to leave scan4Uplink() in FTTPCktLoader. However, this new design offers several potential benefits and follows a few design principles.
* – encapsulating changes. Lots of potential changes are now isolated to this class. Look at the “business logic” in this factory, and you may agree it can change.
* – cohesion. It’s best to make one class responsible for one thing only. This factory is relatively high-cohesion — responsible for instantiating UplinkPort and nothing else. FTTPCktLoader is low-cohesion — already responsible for many things, and do not need to take care of UplinkPort instantiation. If a class is responsible for 2 relatively unrelated things, we can get too many changes.
* – readability. Thanks to cohesion, this class is clearly self-contained, not entangled. Left in FTTPCktLoader.java, this code would appear to be interdependent with other methods.
* – testability. Left in FTTPCktLoader.java, you can test this code too, but not as a unit-test.
* – extensibility. It’s easy to add functionalities into this factory.

1 singleton 2 instances

Hi guys,

I think we have a few methods like this, which could produce 2 instances of the singleton.

public static FTTPCktLoader getInstance() { 
1) if (_instance != null) { 
2)   return _instance; 
3) } 
4) synchronized (FTTPCktLoader.class) { 
5)   _instance = new FTTPCktLoader(); 
6) } 
7) return _instance; 

Thread A goes through 123 and gives way to other threads
Thread B goes through 123, since _instance is still null
B gets the lock and goes through 4567 and returns a new object to its caller method
B gives way to other threads
A gets the lock and goes through 4567 and returns a second object to its caller method

Now, the caller method (probably in LoaderFactory) may be synchronized, but that would not be a safe design. Another programmer may write another caller method that calls getInstance() without acquring any lock.

I’ll find a new version later, hopefully more thread-safe.

Decorator pattern keywords

#1 key phrase:
java.io — uses decorators. P100 [[ head first design patterns ]]

hasa AND isa — at the same time. MyDecorator instance both HAS-A and IS-A MyDecoratee

Adding features — decorating, while adhering to original interface ie IS-A. MyDecorator.java often adds non-private[1] fields and methods to fulfill the duty of decoration.

Onion — “decoratee” could be abstract or concrete (onion) or an
interface. This onion is very similar if not the same as the RAM-onion
described in other blog posts. P89 [[ head first design patterns ]]

collections Synchronized view — of HashMap is adapter or decorator? I
would say Decorator — interface not changed.

complexity — Compared to straight HAS-A or IS-A, Decoration adds
complexity^flexibility. Due to the added complexity, decorate only
when warranted.

[1] Private /memebers/ are insigificant in this and many patterns.
Private members are invisible to other objects.

facade: loose coupling && fewer dependencies

One j4 facade — loose coupling and fewer “dependencies”.

Without a facade, a client object may need 5 instance variables to access 5 “services” either hosted in the same or hosted in a different JVM [2]
– logger “service”
– authentication service
– authorization service
– status-check service
– connection-pool or dataSource
– transaction manager
– sessionFactory’s static “services”
– StudentDAOFactory, ProfessorDAOFactory….

Basic OO principle lets each subject expert author (and maintain) her object, and require all client objects to get a reference [1] (a dependency) to her object.

[1] either static field or instance field
[2] perhaps through JNDI lookup

Factory pattern keywords

* dependency and new() — factory to replace new()

See also post on eclipse’s factory refactor.
see [[ head first design patterns ]]

* delegating — Abstract-Creator object delegates instantiation to concrete subclasses, because of “knowledge” and “responsibility”

* knowledge — about a specific concrete class is usually with one developer

* responsibility — ideally each developer should be owner of a small, well-defined API. Other developers write client objects

* decouple — ideally different interacting objects should not break each other when one /invariably/ undergoes a change.