Tuesday, July 1, 2014

Uses of Union in C

A union is a special data type available in C/C++ that enable user to store different data types in the same memory location. User can define a union with many members, but only one member can contain a value at any given time. Union thus provide an efficient way of using the same memory location for multiple types. Unions are quite similar to the structures in C but there is difference in memory allocation, memory required to store a union variable is the memory required for largest element of an union. Whereas, to store a structure variables, memory required is the sum of memory size of all members.

Union data type is quite useful in C. Unions in C are used for type-safe polymorphism. In C++'s use of classes & inheritance make the need of Union redundant.

Because of above mentioned properties Unions are mostly used for


1. Creating own Variant type

A variant can be thought of as a container that can hold a variable of almost any data type be it a numeric, float, string, or even an entire array. To create your own variant type, a union can be encapsulated within a structure along with a discriminator that indicates which of the fields of the union are valid. 
 typedef enum {EMPTY, CHAR, INT, UINT, FLOAT, DOUBLE, PTR} ValueType; 
 struct variant_t {
    int mType;
    union {
        char charVal;
        int intVal;
        unsigned int uintVal;
        float floatVal;
        double doubleVal;
        void* ptrVal;
    };
};

it can be then used as,
/* Read a value to the variant from some record */
void getData(struct variant_t* v, int variantType)
{
v->mType = (ValueType)variantType;
switch(v->mType)
{
case CHAR:
v->charVal = ReadData(fptr);
break;
case DOUBLE:
v->doubleVal = ReadData(fptr);
break;
}

2. In embedded systems.
In the embedded realm, each bit of a register may mean different things. In such scenarios a union of a 1 byte char and a structure with 8 separate 1 bit bit-fields , allows you to either change one bit or the entire byte.
Similar examples can be found in many networking APIs for IPv4 address like
union ipv4Addr {
  unsigned  ipAddress;
  char      octets[4];
};

3. To cast pointer to an int and vice-versa
In the embedded realm, mostly the size of a pointer and an int are same. This is because both of them can fit into a CPU register. So if you want to store a value at a particular memory location, you can do something like this
typedef union {
   int i;
   int* iptr;
 }intptr;

 intptr p;

 p.i = 256;
 *(p.iptr)=5; /* put 5 a location 256 */ 

 when we set p.i = 256; both the members of union has value 256, since each member share same location.


 An example C code build using VS2010 IDE can be downloaded from here. In this code a student record in "data.txt" file is read and stored in linked list. Each node of list has a union to store student information. The requirement is that, at a time user want to display only one of either name, roll number, grades or result. So depending on what user want to display, data is stored in Node that store a only a particular type ( Variant ) and display only that particular type of data.

Sunday, June 8, 2014

Head First C++ code for PizzaStore : Abstract Factory Pattern

After Factory method, Chapter 4 in the Head First Design Patterns book explains Abstract Factory design pattern.

" The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. "

Both Factory Method and Abstract Factory create objects but the key differences are :

  1. Factory Method create objects through inheritance, that is you need to extend a class and override a factory method. Whereas Abstract Factory create through object composition, it provide an abstract type for creating a family of products. Subclasses of this type create products. To use the Abstract Factory , you instantiate one and pass it into some code that is written against the abstract type.
  2. Factory Method is to just create one Product and each subclass is to decides which concrete class of Product to instantiate. Whereas Abstract Factory provides an abstract interface for creating a family of Products.
  3. Methods to create products in an Abstract Factory are often implemented with a Factory Method!
In the example code PizzaIngredientFactory is implemented as an Abstract Factory because we need to create family of Products ( the ingredients). PizzaIngredientFactory provides an abstract interface for creating a family of products. The subclasses as 'NYPizzaIngredientFactory' uses factory method like 'createDough()' in an Abstract Factory pattern.

Here is the class diagram of PizzaStoreV2






























The c++ code is build using VS2010 IDE. You can download code from here.


Wednesday, June 4, 2014

Head First C++ code for PizzaStore : A Factory Method Pattern

Chapter 4 in the Head First Design Patterns book explains Factory Method design pattern. As we learned in previous posts to "encapsulate what varies", we can apply same technique to "encapsulate the code that create objects". When you have code that create objects or instantiates concrete classes, then it can be an area of frequent change.

We create objects by using new operator but there is more to making objects than just using new operator. As per design principle 2 we should "Program to an interface, not an implementation". Why ? Because if code is written to an interface, then it will work with any new classes implementing that interface through polymorphism. When I say interface here then in C++ there is no clear distinction between interface and abstract class, unlike in C# and Java. To get a fair idea of interfaces and abstract classes in C++, you can refer stackoverflow discussions here and here. Generally speaking interface can also refer to a function's signature.
Whenever you see "new", think "concrete". When you use "new" you are certainly instantiating a concrete class, so that's an implementation and not an interface. When you have a code that makes use of lots of concrete classes then it will be prone to bugs because code may have to be changed as new concrete classes are added. So code will not be "closed for modifications" and hence violate our design principle 4 discussed in last post.
Anywhere in a code if you use "new", you'll be holding a reference to a concrete class, you should be using a Factory method to get around that! Factory method can be defined as

" The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."

The 'interface' above is factory 'method'. A factory method handles object creation and encapsulates it in a subclass. This decouples the client code in the superclass from the object creation code in the subclass. A factory method looks like

        abstract Product factoryMethod(String type)

A factory method returns a Product that is typically used within methods defined in the superclass. Client is actually code in superclass, factoryMethod isolates the client code from knowing what kind of concrete Product is actually created.

In the example code the PizzaStore class is the Creator class that contains the implementations for all of the methods to manipulate products, except for the factory method. The abstract factoryMethod ( createPizza(string) ) is what all Creater subclasses must implement ( ChicagoPizzaStore, NYPizzaStore ). The Concrete Creater( ChicagoPizzaStore, NYPizzaStore ) implements the factoryMethod(), which is the method that actually produce Products.
Pizza is the Product and all concrete products ( NYStyleCheesePizza, ChicagoStyleCheesePizza ... ) must implement the same interface so that the classes which use the products can refer to the interface not the Concrete Product ( NYStyleCheesePizza, ChicagoStyleCheesePizza etc. ).

Here is the class diagram of PizzaStore


















The c++ code is build using VS2010 IDE. You can download code from here.

Monday, June 2, 2014

Head First C++ code for StarbuzzCoffee : A Decorator Pattern

The third chapter in the Head First Design Patterns book explains another fundamental design principle that forms the basis of Decorator design pattern. The fourth design principle can be summed as

"Classes should be open for extension, but closed for modification."

The example code in Chapter 3 the Decorator Pattern provide Java Implementation of StarBuzzCoffee billing application. I tried to write similar code in C++ that explains the Decorator Pattern used in the program.
Inheriting from Base class that implements a lot of methods is not a good idea, as some of sub-classes might not need all the functionality (methods) of Base class. Also it violates design principle 2 explained in previous post.
Inheriting behavior by sub classing, set the behavior statically at compile time. And all sub-classes must inherit the same behavior. If object's behavior is extended through composition (has-a), then it can be extended dynamically at a runtime.
It is possible to add multiple new responsibilities to objects through this technique (composition), including responsibilities that were not even thought of by the designer of the superclass. And we don't have to touch their code! By dynamically composing objects, new functionality can be added by writing new code than altering existing code. This reduces chances of introducing Bugs.

Decorator pattern provides an alternative to sub-classing for extending behavior, it attaches additional responsibilities to an object dynamically. Decorators need the same "interface" as the component they wrap because they need to stand up in place of the component.
In the example code we subclass the abstract class Beverage in order to have correct type, not to inherit its behavior. The behavior is acquired by composing objects together. Decorators change the behavior of their components by adding new functionality that they achieve by wrapping the component of same type ( Since Decorator extends the same Base class as components they wrap).
Here CondimentDecorator class provides decorator interface that will wrap the objects of type Beverage ( Sub-classed from), that is why Condiment inherit from same abstract class Beverage, but it inherits from Beverage to get type so that it can wrap beverages. The behavior will be extended by composition dynamically as CondimentDecorator store reference to Beverage.

Here is the class diagram of StarBuzzCoffee




















The c++ code is build using VS2010 IDE. You can download code from here.

Saturday, May 31, 2014

Head First C++ code for Duck Simulator : A Strategy Pattern

The very first chapter in the awesome Head First Design Patterns book explains 3 fundamental design principle that forms the basis of Strategy design pattern. These principles are

  1. Identify the aspect of your application that vary and separate them from what stays the same.
  2. Program to an interface, not an implementation.
  3. Favor composition over inheritance.
The example code in Chapter 1 Intro to Design Patterns provide Java Implementation of Duck Simulator. I tried to write similar code in C++ that explains the Strategy Pattern used in the program. The behaviors of a duck that can vary (  Fly Behavior, Quack Behavior ) are encapsulated as family of classes and the non varying part ie Duck Class is base class for different types of ducks ( principle 1). Duck acts as client and make use of encapsulated family of behaviors/algorithms. This particular design is Strategy pattern and it defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that uses it.

Here is the class diagram of SimUDuck simulator

The c++ code is build using VS2010 IDE. You can download code from here.


Thursday, May 15, 2014

Tax Saving Mutual Fund Risk Measures

ELSS (Equity Linked Saving Scheme) Risk assessment

It’s quite a daunting task to select best performing mutual fund that can provide handsome returns and tax benefits too. One thing I want to make clear that I am only providing a way to understand the risk measurements and it does not guarantee that a given scheme will definitely provide best results or gains. Since these saving schemes are equity or market related so nothing is guaranteed but it is also a fact that equity linked scheme has always outperformed the sure shot saving schemes. There is inherent risk involved but if you can understand and measure those, you will be able to make informed decision.
So let us understand how to read factsheets of different mutual fund houses and make informed decisions.
Rsquare:  Measures the percentage of an investment's movement that are attributable to movements in its benchmark index. A mutual fund should have a balance in R-square and ideally it should not be more than 90 and less than 80
Beta Ratio:  where the alpha looks at excess returns over the index, the beta looks at excess risk over the index. If you have a beta of 1, it is said that you have the same risk as the market. If you have a beta of 0.61, it is said that you have experienced about 61% of the risk of the market.
Alpha Ratio: If you are trying to see if a mutual fund has beat the performance of it’s relative index, you should take a look at the alpha ratio. Measures risk relative to the market or benchmark index. For investors, the more positive an alpha is, the better it is. The greater is the number, the greater the out performance.
Sharpe Ratio:  An indicator of whether an investment's return is due to smart investing decisions or a result of excess risk. Higher Sharpe Ratio is better. The range of Sharpe Ratios for global equity funds went from as low a -1.11 to a high of 0.94. A positive Sharpe ratio means the fund did better on a risk adjusted basis. In other words, the higher the Sharpe ratio, the better. The Sharpe ratio tells you about history but it does not tell you anything about the future. Just because a fund has a positive Sharpe ratio for the last 5 years does not mean it will outperform the index for the next 5 years.
Treynor Ratio: Unlike Sharpe Ratio, Treynor Ratio utilizes "market" risk (beta) instead of total risk (standard deviation). It is measure of returns earned in excess of that which could have been earned on a riskless investment.
Expense Ratio:  Denotes the annual expenses of the funds, including the management fee, and administrative cost. Lower expense ratio is better.
Standard deviation: SD is applied to the annual rate of return of an investment to measure its volatility or risk. A volatile stock would have a high standard deviation. With mutual funds, the standard deviation tells us how much the return on a fund is deviating from the expected returns based on its historical performance.

Scheme/Time period
R Square
Beta
Alpha
Treynor Ratio
Sharpe ratio
Standard deviation
Canara Robeco Equity Taxsaver






3-Year
83.61
0.83
1.85
2.36
0.19
17.01
5-year
92.56
0.92
5.60
2.29
0.21
29.10
10 –year
85.53
0.90
4.72
20.97
0.74
27.51
Religare Tax Plan (Growth)






3-Year
92.95
0.78
4.42
6.42
0.38
15.14
5-year
93.83
0.81
3.54
0.91
0.15
25.33
Reliance Tax Saver Gr






3-Year
88.68
0.99
4.78
5.07
0.33
19.60
5-Year
93.45
0.85
4.67
1.96
0.19
26.73







Overall Category: ELSS Risk






3-Year
92.97
0.88
1.33
2.08
0.18
17.13
5-year
95.29
0.89
0.18
-3.56
0.02
27.62
10 –year
89.17
0.91
4.03
20.30
0.73
27.12

From above figures Religare Tax plan looks less risky but other two funds have outperformed it with extra risk. Another important factor is fund size. By fund size we mean total asset value that is managed by fund manager of respective fund.  Canara Robeco Equity Taxsaver have AUM ( asset under management ) of Rs 506.77 crore, Religare tax plan has 129.26 cr and Reliance tax saver 2104.51 cr. Sometimes as size of fund become too large, fund manager find it difficult to invest. Again what is too large is based on perspective.
Source: Jago Invester, Moneycontrol, Investopedia, MorningStar  and internet.

Friday, April 11, 2014

Welcome to TMC

Welcome. Initial blog posts contains C++ code for examples in Head First Design Patterns book.