fitnesse Q&&A

(We will intermix “fix” and “fixt” and “fixture.)

fitness runs with 2 JVM
* a long term infra jvm
* a jvm launched for the system under test

FIT system interprets HTML inbound and outbound. Fitnesse wraps FIT.

set commission rate -> setCommissionRate() will be called.

Q: automated build?
A: ant can trap the fit failures

Q: cvs?
A: fitness has versions for each page

Q: books on fit tricks
A: it may not sell, since the fitness guys did good documentation(?)

— 5 types of colors
* green: expected = actual
* red: obvious
* yellow: a broken (not found) fixture — Thanks to blog reader comment below.
* grey background: See the top summary saying “5 ignored” meaning “5 table cells ignored”. nothing-to-run. expected will show ……………
good for comments
We should leave “expected” output header empty.

* grey text: expected — we don’t care. Actual will show.
Good for debugging.
We should leave “expected” output header empty.

Q: Just want to execute a method and the result is not important (or the method is void)?
A: use the SetUpFixture instead (see http://www.fitnesse.info/fixturegallery:fitlibraryfixtures:setupfixture).
A: The ColumnFixture will also allow you to just print the result of the calculation, not testing it.
A: empty cell in a fitnesse table? Try it

—- various fixtures —-
one table => one fixture class. For doFixture, one page => one fixt class. Stateful fix

column/row fixt need one fixt class per TABLE; do fixt need a fixt class per PAGE. That’s the norm. However, a doFix can also instantiate a rowFix, like Peter Walker showed.

— col fixt —
one input column => one field
one output column => one method
————-

— testing
Q: How do I know what type of ‘error’ matched my expected ‘error’?
A: provide another method that opens the exception…

Q: how to share an object between 2 column fixtures on a page, so that first fixt populates it for 2nd fixt?
A: use a new class to hold a static instance to the object

Q: other output columns for an error row?
A: leave blank

Q: how to say expected = null?
A: just spell out n u l l

Q: what if an “expected” is in camel case and confuses fitness
A: escape it with ! or “!-…-!”

Q: use fit to test non-public stuff?
A: not designed for that. try parallel tree

— wiki
Q: save the editor?
A: alt-S

Q: collapse or hide a table?
A: http://localhost/FitNesse.QuickReferenceGuide

Q: comment?
A: see notes on grey-background

Q: comment at end or elsewhere?
A: yes

!contents // will render to a table of links

Advertisements

has-a vs is-a — a fine point clarified

People say “Mortgage is-a Loan” — fine. You may say a HashMap has-a Entry — you mean a HashMap instance has-a Entry instance. The distinction between Class and Instance becomes critical when you study inner classes.

Generally, it’s more accurate to say an object (of class A) has-a pointer to another object (of class B). Usually, such a relationship is defined at compile time Before instance creation.

Therefore, we could afford to be imprecise as to say “class A has-a class B”.

In summary,
* is-a could be said of classes OR instances.
* has-a should be said of instances.

boost shared_ptr implementation choices

http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smarttests.htm
describes linked list was once considered in Boost team, but the boost shared_ptr authors said in
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2351.htm :

“The default behavior of shared_ptr is to allocate its control block
using new.” No linked list.

However, it was then argued that op-new is not always appropriate to allocate memory for the ref counter.

treat verb as noun(OO design

So many OO patterns and designs model a verb as a noun that we don't even notice them — we model an operation as an object, an
action, a process, a behaviour as a thingy….

In my projects, verb objects out-number nount objects. Bulk of business logic is in verb objects, so we often need to break each
into many objects and perhaps apply patterns.

* command pattern
* strategy pattern
* visitor pattern
* observer pattern
* factory pattern — object-creation
* processor objects
* loader objects
* controller in MVC
* message routers
* DAO — read operations and writes
* logger
* MessageDrivenBean
* listener, publisher, consumer

margin account, briefly

By definition, an account holds securities. A margin account can hold long securities, short securities, long cash and short cash.

When you short 500 of IBM, sales proceeds go into margin account to cover the short position, since you are expected to buy back the stock.

The *equity* of the margin account is simply what is left when the debit balance is paid in full or the shorted stocks have been bought back and returned to the lender. Equity doesn’t mean stock. It probably means the total value of stocks and cash. For long accounts, Equity = long MV – DR ie debit balance.

The amount of margin (available to investor, calculated by House every day) will depend on the price of the securities. If margin is used to buy securities, then the amount of margin increases with price, but if the margin is used to short securities, then the amount of margin is inversely related to the price of the shorted securities, and vice versa.

stackVar^heap object

In a C++ program, there is exactly
* one heap
* one stack — locals (ie auto variables) and static locals.
* one global space — globalVar is defined outside all functions.

An object (float, int, user-defined…) lives in one of the 3

In terms of cleanup, heap objects need delete (never automatically deallocated); global var lives forever; auto var has automatic cleanup. static locals live forever. [[ absolute c++]]

You can reasonably seat your ptr at
* globals
* static locals
* autos in main()
* heap objects

core java iview 18/9/09

Q: what’s inside a hashmap? Give me some details.

Q: have you ever written a hashCode()?
I simply said “never” but didn’t take the chance to explain what i know about hashCode().

Q: what’s the search time complexity in a list? What if it’s sorted?

Q: which is fatest when adding an item — Vector, List or Set?

Q: how do you create a thread?

Q: how do you use a factory?

Q: what must you implement if your object is to be used in a collection?

java enum differences from regular classes

How is an enum class E different from regular classes?

* static field? ok
* inst field? ok
* static method? ok
* inst meethod? ok
* static methods returning an instance of E? ok
* inst methods returning an instance of E? ok

#2 difference — flat tree. enums can’t form a class hierarchy. All enum classes are on the same level — all leaf-nodes under the same parent.

* can an enum E extend ..? E’s superclass is always java.lang.Enum
* subclasse E? no
* E implementing interfaces? ok

#1 difference — constructor:

* constructors? private only => not subclass-able
* how many instances of the class can be created in a JVM? If there are 5 enum values declared, those are the only instances. All the pointers of type E point to one of the 5 instances.
* constructor with arg? ok
* no-arg constructor? ok

Prime Brokerage Risk technology IV #GS 30Hudson

Q: How do you see memory usage by a given unix process?

* I said “ps”. Indeed Linux ps command reports memory usage. See http://linux.die.net/man/1/ps.
** Sometimes ps -ef doesn’t show it, but ps aux does.

* I said “/proc has process id directories. In each directory there are many details about that process, including memory”. This is supported on linux. See http://www.redhat.com/docs/manuals/linux/RHL-9-Manual/ref-guide/s1-proc-directories.html

AA: ps # SZ = virt mem used; RSS = real mem used
AA: use top. http://www.unixtop.org/man.shtml says

M      Sort display by memory usage.  Shorthand for "o size".

Q: when do you use static
A: I said “I don’t use static unless …”. In most OO designs, there are far more non-static than static members. Encapsulation, inheritance and polymorphism need non-static.

high leverage = low margin requirement

forex: typically leverage of 100 ie margin requirement of 1%. (I traded copper and soybean in first half of 1997 using margin
account and leverage.)

You need to put $1K into your margin account to buy $100K of a currency. Your gains and losses are magnified 100 times. High
leverage, high risk.

When market moves against you to reduce your margin to below the required minimum, you get a margin call from the House. If you
don’t top up, the “House” liquidates your position.

“House” is the broker who lends you 99% of the money.

For stocks, typically 10%. With a 10% requirement, you can buy $10K worth of IBM using $1k, borring the rest from your broker.

financial jargon: debit balance is a loan amount

When buying on margin, investors borrow funds (the amount is the DB) from their broker and then combine those funds with their own to purchase a greater number of shares than they would have been able to purchase with their own funds.

The debit amount (interest charge + any fee) recorded by the brokerage in an investor’s account represents the cash cost of the transaction to the investor.

http://www.investopedia.com/terms/d/debitbalance.asp. Also see “Credit Balance”.

lockfree and compare-and-swap in my project

A simple race condition – If 2 threads update the same object in the same clock cycle, how do we avoid lost update?

Traditional solution is synchronization, i.e. locking. There’s huge interest in lockfree, but I feel either it’s impossible or requires hardware support like xchg or cmpxchg(?).

while (!done) {
final PositionMark oldMark = getRegion().get(key);
newMark = producer.producePrice(key);
final PositionMark replaced = getRegion().put(key, newMark); // atomic?
// The following ensures consistency given concurrent updates to the same key
done = (replaced == oldMark);
}

Idea is to first get old value of object, then update it and get the replaced value in one sweep. (Perhaps using xchg). If old != replaced, then keep retrying. This is probably swap-and-compare, not to be confused with the more complex compare-and-swap hardware feature [1].

Challenge is the atomicity of the xchg. Without hardware support, can u guarantee atomicity without locking? I doubt it.

In this code, getRegion returns a gemfire region, backed by a concurrent hash map, whose put() is actually synchronized with lock striping. If you were to use a hash map, I would assume put() is completely thread unsafe. 2 threads can both get the same replacedMark, and put in their new marks and overwrite each other — lost update.

[1] compare-And-Swap does the swap conditionally — safer.

How long to hold a position – eq der sell-side trader

In facilitation (match-maker??), a bank trader doesn’t need to hold position. Client makes the request. Trader finds a quote from the market and marks up, then makes a 2-leg trade. Same as TMC virtual trades. Not sure how widespread this practice is. For listed instrument, client probably gets the exact listed price, but pays a commission to the broker. In FX spot trading, some say there’s no commission — brokers mark up the upstream bid/ask and profit from the wider spread. However, I believe many FX ECN’s do charge commission. Their business model is price transparency, never-hold-position, pure MATCH-maker, never MARKET-maker.

If the deal is tailor made for a client, then the trader may have to be the counter party and therefore hold the position for the full life time of the deal.

Prop traders? no “client request”. Can hold very long.

Which of the 2 quote prices (bid/ask) can I get? An easy rule

When working out pricing scenarios, always remember there’s the bid and ask; always remember whether you are market maker or taker.
* only the dealer can buy low sell high
* both dealer and client can trade with another dealer by accepting the inferior prices.


Say you see a quote for a commodity like silver at 1.2345/47. Treat the base currency as a base/precious metal like Silver or Gold (strictly qualifies as Commodity). Clearly the market maker is bidding at the lower 1.2345 price and offering at the higher 1.2347 price.

   Market makers always want to buy-low, sell-high

You can’t do that, because you are market taker. Market takers have to buy-high, sell-low. More simply,

  Client get the worse of the 2 prices quoted.

This is so that the market maker can make a profit to cover her risk/cost of making the market. If client take the other price, then it would be a free lunch for all.

* if clients buy, clients buy at the higher (worse) of the 2 price quoted
* if clients sell, clients sell at the lower (worse) of the 2 price quoted

This Easy Rule is relevant in FX, commodities, stocks, futures, IRS, bonds..

Now, after a dealer gets a position (say long  EUR, short  USD), she could close it by calling another market-maker, but giving up her market-making advantage and accepting the worse prices proposed by the counter dealer. The better alternative for her is price shading. This way she still enjoys her market-maker advantage.

subverting java private constructor #some c++

Private constructor is not watertight. Among the consequences, singletons must be carefully examined.

  • reflection
  • ObjectInputStream.readObject() — see other posts
  • de-serialization can instantiate the class without constructors (or field initializers).
    • RMI, EJB, JMS, Web service all use serialization
    • any time we copy an object across 2 jvm processes
  • if you see a private constructor, don’t feel safe — the class may be a nested class. In that case the enclosing class can call the private constructor. Worse still, another nested class (sister class) can also call the private constructor. And enclosed classes too. In summary all of these classes can call my private ctor —
    • ** my enclosing class
    • ** my “sister” classes ie other classes enclosed by my enclosing class
    • ** my “children” ie enclosed class including anonymous classes
    • ** my “grand-children” classes

— in c++

  • Friend function and friend class can call my private ctor.
    • Factory as friend
  • static method is frequently used by singletons

writeObject() invoked although never declared in any supertype

Usually, a common behavior must be “declared” in a supertype. If base type B.java declares method m1(), then anyone having a B pointer can invoke m1() on our object, which could be a B subtype.

However, writeObject(ObjectOutputStream) [and readObject] is different. You can create a direct subtype of Object.java and put a private writeObject() in it. Say you have an object myOb and you serialize it. In the classic Hollywood tradition, Hollywood calls myOb.writeObject(), even though this method is private and never declared in any supertype. Trick is reflection — Hollywood looks up the method named writeObject —

writeObjectMethod = getPrivateMethod(cl, “writeObject”, …

tibrv-CM session, again

A tibrv Transport is like a JMS session. 2 Main actors in a CM conversation are the transports (“sessions”).
* sending CM transport
* listening CM transport
P 155 of [[rv concepts]] says

The sending CM transport is responsible to record each outbound message on
that subject, and to retain the message in its ledger until it receives
confirmation of delivery from the listener (or until the time limit of the
message elapses).

In return, the listening CM transport is responsible for confirming delivery of
each message.

Since the sender is a CM sender, i would assume receiver can’t be non-CM.

To send or receive messages using certified delivery features, a program must first
create a CM transport (also called a delivery-tracking transport). Each CM
transport employs an ordinary transport and adds some additional capabilities, such as a ledger.

Changi(citi)c++IV #onMsg dispatcher, STL, clon`#done

I feel this is more like a BestPractice (BP) design question.

void onMsg(Price& const price){ // need to persist to DB in arrival order
// Message rate is very high, so I chose async producer-consumer pattern like
  dispatch(price);
}

// sharding by symbol name is a common practice

// %%Q: should I dispatch to multiple queues?
// A: Requirement says arrival order, so I decided to use a single queue.

// The actual price object could be a StockPrice or an OptionPrice. To be able to persist the option-specific attributes, the queue consumer must figure out the actual type.

// Also, price object may be modified concurrently. I decided to make a deep copy of the object.

// Q: when to make a copy, in onMsg or the consumer? I personally prefer the latter, but let’s say we need to adopt the former. Here’s a poor solution —

//Instead of dispatch(price)
dispatchPBClone(price); // slicing a StockPrice down to a Price. Here’s my new solution —

dispatchPBPointer(price.cloneAndReturnPtr());

// clone() is a virtual method in StockPrice and OptionPrice.
//Q: clone() should allocate memory on the heap, but where is the de-allocation?
//A: Use smart ptr.

java DB entity object HAS-A DAO?

Say you have an Account.java representing one row in Account table. You have an AccountDAO.java that read/write the table.

Q: Shall Account.java HAS-A AccountDAO instance?
A: I feel Account.java should not import AcountDAO at all. Acocount.java should be compilable without AccountDAO.java. Assumption is, Account.java is a more generic class. It should be usable in other projects (web, xml serialization, file-based …) without database.

Bottom line — If you want AccountDAO to be compile-time dependent on Account.java, then don’t have the reverse-dependency. DAO is one layer above the DB entity objects.

If Account table relates to Customer and Branch tables, it’s perfectly legitimate and perhaps best practice to use HAS-A between these classes. I think Hibernate and many ORM systems do that. These classes exist on the same “layer” so compile-time dependency is perhaps tolerable. To reduce compile-time dependency, use interfaces rather than classes.

auto_ptr implementation notes – eSpeed IV

Someone asked me to implement a basic auto_ptr class template. It should be usable like

void foo(int * ip){…}

int* intP = new int(3);
AutoPtr aptr = ….. // create an AutoPtr object to encapsulate intP;
foo(someExpressionOfAptr);

Implement dtor, copier, op=… for the AutoPtr class,

Overload dereference, arrow to mimic pointer behavior.

Q: And what else?
A: cvctor to convert int ptr to an AutoPtr

Q: how about an operator-overload-converter (OOC) to convert from an AutoPtr to an int ptr? Why do we need it?
A: an auto ptr should be usable as an int ptr, ie foo(aptr). This requires the OOC.

Now you see the need to implicit convert both ways between AutoPtr and raw ptr!

what make EUR/USD FX bid/ask spread so tight

– Factor: large lot size. In interbank market, each deal is around 10-100 mio USD (minimum 1 mio), so a 1 pip bid/ask spread means $1k – 10k. I believe (personal opinion) the larger the volume, the tighter the spread.

– Factor: volatility. The more volatile, the wider the spread from a given liquidity provider i.e. market-maker.

– Factor: market depth. A deeper market makes it “cheaper” to unwind a losing position, thereby minimizing the market maker risk. MM can therefore take more risk and provide tighter spread.

– Factor: credit risk seems to be the most important determinant of bid/ask spread. The best spread is given to the highest credit banks. http://www.investopedia.com/articles/forex/06/interbank.asp says — “The interbank market is a credit-approved system in which banks trade based solely on the credit relationships they have established with one another. All of the banks can see the best market rates currently available; however, each bank must have a specific credit relationship with another bank in order to trade at the rates being offered. The bigger the banks, the more credit relationships they can have and the better pricing they will be able access. The same is true for clients such as retail forex brokers. The larger the retail forex broker in terms of capital available, the more favorable pricing it can get from the interbank market. If a client or even a bank is small, it is restricted to dealing with only a select number of larger banks and tends to get less favorable pricing.