Monday, August 24, 2015

UML Training...

I know , the almighty has been testing me all through my professional life... Now there is a new dilemma that is haunting me everyday. This is should i make all my training materials online for others to access free of cost or not... i believe in free flow of knowledge... hence i have made all my Google play apps open source.... For me, it does not look good to earn money by sharing knowledge... knowledge should be free... that is why i like Google because they have democratized knowledge.... however, i have not picked up any skill other than software to support my family... and not only that i like sharing knowledge with others... hence the dilemma... but i can't stop listening to my heart... hence here goes another training material and its source code... i believe whoever is able to follow it, does not have to come to me... however, who does not follow and can pay a little bit, will surely come to me and make it a win-win situation... the supportive source code can be cloned from

Monday, July 20, 2015

Memory layout in C++ vis-a-vis Polymorphism and Padding bits

I know there is no need for the knowledge of memory layout for a normal day-to-day development of C++. However, when someone goes in the bit/byte level of C++, he needs looks for such discussion.

To state the problem, lets have a class hierarchy like the following.

class A {
    virtual void funA()
    virtual ~A(){}
    int a;

class B {
    virtual void funB(){};
    virtual ~B(){}
    int b;

class C : public A, public B {
    int c;

Now if we run this app using a GCC compiler on a 64 bit machine and see the sizeof() these classes, we will see A will be 16 byte, B will be 16 byte and C will be of 32 bytes . So lets discuss how these numbers have come.

To start with the discussion, i need to throw some lights about how polymorphic behavior in C++ using virtual functions is tackeled by a compiler. Whenever there is a class having virtual function, the compiler will generate a VTABLE of that class and all the objects of that class will use that VTABLE. VTABLE is nothing but a TABLE having pointers to the virtual functions in a class hierarchy. And whenever there is a VTABLE, the compiler will silently add a pointer in the beginning of an object of the class. This pointer is called vptr and it actually points to the beginning of the VTABLE.

So in the following case two VTABLES will be created (each for class A & B).

Hence the size of an object of class A will be size-of-a-pointer(vptr) + size-of-int. So for a 64 bit architecture (where a pointer is 8 byte long) it will be 8 + 4 = 12. If this is the case, then how come sizeof(A) shows 16. Here comes the concept of Alignment and Padding bits.

Here is an excerpt from Wiki about alignment.

"A memory address a, is said to be n-byte aligned when a is a multiple of n bytes (where n is a power of 2). In this context a byte is the smallest unit of memory access, i.e. each memory address specifies a different byte. An n-byte aligned address would have log2(n) least-significant zeros when expressed in binary.

The alternate wording b-bit aligned designates a b/8 byte aligned address (ex. 64-bit aligned is 8 bytes aligned).

A memory access is said to be aligned when the datum being accessed is n bytes long and the datum address is n-byte aligned. When a memory access is not aligned, it is said to be misaligned. Note that by definition byte memory accesses are always aligned.

A memory pointer that refers to primitive data that is n bytes long is said to be aligned if it is only allowed to contain addresses that are n-byte aligned, otherwise it is said to be unaligned. A memory pointer that refers to a data aggregate (a data structure or array) is aligned if (and only if) each primitive datum in the aggregate is aligned.

Note that the definitions above assume that each primitive datum is a power of two bytes long. When this is not the case (as with 80-bit floating-point on x86) the context influences the conditions where the datum is considered aligned or not.

Data structures can be stored in memory on the stack with a static size known as bounded or on the heap with a dynamic size known as unbounded."

To maintain the alignment, compiler inserts padding bits in the compiled code of a structure/class object.

"Although the compiler (or interpreter) normally allocates individual data items on aligned boundaries, data structures often have members with different alignment requirements. To maintain proper alignment the translator normally inserts additional unnamed data members so that each member is properly aligned. In addition the data structure as a whole may be padded with a final unnamed member. This allows each member of an array of structures to be properly aligned. .... ....

Padding is only inserted when a structure member is followed by a member with a larger alignment requirement or at the end of the structure" - Wiki

To get more info about how GCC does it, please look at

and search for the text "basic-align".

Now lets come to this problem:

Using the example class, i have created this program for a GCC compiler running on a 64 bit Ubuntu.

int main() {
    A objA;
    C objC;
    return 0;
And the result for this program is as the following:


As i was sayingthat object of class A will have a VPTR (pointing to the VTABLE of A) and an int. The pointer will be 8 byte long and the int will be 4 byte long. Hence before compile the size is 12 bytes. But the compiler will add extra 4 bytes at the end of int a as padding bits to maintain the alignment of class A equal to the highest length of the data member of the class which is divisible by 2, that is vPtr (8 byte long). Hence after compilation, the A's objects size will be 12 + 4 = 16 bytes.

Similarly for class B's objects.

Now object of C will have two VPTRs (one for each class A & class B) and 3 ints (a,b,c). So the size should have been 8 (VPTR A) + 4 (int a) + 4 (padding bytes) + 8 (VPTR B) + 4 (int b) + 4 (int c) = 32 bytes. So the total size of C will be 32 bytes.

Monday, July 13, 2015

Android Graphics & Animation - a Bouncing Ball Game with source code

Last week while conducting the summer training on Android & Java, one guy requested me to help develop an Android game. I thought the bouncing ball would be the perfect example through which we can show about Android graphics and animation. However, i would strongly suggest to use professionals Game engines like cocos-2d to develop real life Game apps.

Please have a look at this app and get it from Google Play Store:

This app is  simple yet will be able to clarify many things related to android graphics to the students. I have made this game opensource and one can clone the source code from the following link.

Here is a screen recording of this app.


If this helps the Android learners, i would probably be the happiest guy.

Sunday, June 21, 2015

Memory Layout of Java Objects vis-a-vis Inheritance...

These two diagrams describe the memory layout of Java objects. This is with respect to inheritance and not from padding bits or alignment's point of view. To make it simple, i have omitted the methods from the Object class (the root class) in the VTBLE (also called method table). They will obviously occupy the first few indexes in each VTBLE in Java as all the classes are naturally derived from the Object class.

Sunday, May 31, 2015

Concurrent Programming Model in Android...

When an Android application is launched, the Android system creates a thread of execution for the application. This is known as the main thread. This is also known as the UI thread because all the android widgets used for this application run in the context of this main thread. Every UI thread will have its own looper by default which in association with a Message Queue is responsible for dispatching the user interface events to the appropriate widgets. This has been depicted in the following diagram:

We need to arrange our application components so that the UI thread always remains responsive.

Hence we cannot do a long running task like connecting to a network server and downloading a big file or doing a CRUD operation on a remote database in the main UI thread. if we do it then the long running task will block the UI thread and it will freeze the UI. Moreover, if the duration of this freezing of the UI thread is more than 5 seconds, we will get an "Application Not Responding" message which is not desirable. Hence we should do the long running task in a background UI thread.

Another important fact about Android is that the UI toolkit is not thread safe. Hence we cannot manipulate the UI thread from a background worker thread.

Thus there are simply two rules in Android application model vis-a-vis concurrency framework:

1. We should not block the UI thread
2. We should not manipulate the UI thread from a background thread.

Keeping in mind all these factors, there are mainly two ways of doing concurrent programming in Android:

1. Asynctask
2. Handler, Message & Runnable

This has been depicted in the following diagram.

Here are three different applications which show how we can write a concurrent program in Android and communicate to the main thread from a background thread.

You can browse/download the source code of these apps from here:




The first has used an Asynctask, the second has used the function Activity.runOnUIThread and the third has used Handler & Message to achieve the same purpose.

Hopefully this will help you to understand the concurrent framework of Android.

Tuesday, February 3, 2015

How to create your own background for Google Docs

As i was making documents to share with my students using Google Docs, i wanted to create a background for all these documents. Hence i had to do the necessary research to achieve this. I would like to share it with you which may help the Google docs user.

Step I:

Load the background image to the google drive.

Step II:

Create a URL for this image. To do that first go to the sharing option of that image in google docs and make it publicly available. Then open the website and copy the sharable link to this site to create a permalink.

Step III:

Open the website in chrome browser and search for Stylish extension.

And install this extension. It will add an icon on the right side of the address bar.

Step IV:

  • Open any google docs and click on the stylish icon.
  • Click the first link Find more styles for this site
  • You may search for Linen Background for Google Docs and click the link
  • Now open your Google docs and you will see a nice background
  • Click on the Stylish icon on the right hand side of the address bar and this time click “Manage installed styles”
  • Then in the right pane click the button edit.
  • Replace the background url with the permlink that you have got in step II. It will look something like the following
#docs-editor {
background: url( !important;
.docs-title-inner {font-family: Georgia !important;}
.docs-menubar {height:28px !important;}

Step V:

Refresh the open google docs and enjoy the background you have just created.

Monday, January 26, 2015

The Designing of a Software System from scratch with the help of OOAD & UML - A Restaurant System

Note : See the source code from this link./ Or you can download it from here

From the last few days i have been thinking to share my idea about how to design software system from scratch with the help of object oriented principles. The way the OOPS is taught to the students may enable them to write small programming assignments, but when it comes to design a whole system, many of them may falter. I would like to address that part with the  basic principle of OOAD and tell you how to traverse from the problem domain to the solution domain with the help of OOAD.

So, lets start. I have thought of an example to design a Restaurant system from scratch. I have used Java as the language, but one can use any OO language to achieve it.

To start designing of a software system using OOAD, one has to first identify the main entities participating in that system. So, in a Restaurant system who are the main participants? You guessed it right. A restaurant itself. Then the next entity is of course a customer. I think these are the main two entities. Now what does a restaurant consist of. It consists of some tables, a menu card, and food items. Another thing i have forgotten to mention. A restaurant should have a FIFO queue for its customers… right?

Now what kind of operation a Restaurant has to do? It should have some functionality to know if all tables are occupied, and if not which one is vacant; it should be able to book a vacant table when a new customer arrives. And when the customer leaves, it should be able to release that table and if anybody is waiting in its FIFO queue, it should be able to allocate that vacant table to that customer. It should also keep a track about who is the current customer it is serving and which customer has been allocated which table. Then it should also be able to generate a bill.

Now what does a Menu consist of? It has a list of some food items… right? So from Menu’s angle, it needs an entity called Item. Now what are the attributes of a food item vis-a-vis a restaurant? Each item should have an ID, a Name and its Price… right?

Now think that a restaurant will have a list of tables scattered systematically. So what kind of attributes a Table in a Restaurant may have? It should have an ID and it should know whether it is occupied or not. What kind of operation does a Table need? When a customer leaves the table, it should be able to tell the outside that it is occupied… right? On the other hand when a customer leaves the table it should let the outside world know that it is vacant and ready to accept new customer.

With these things in mind lets design the Restaurant, Table, Menu and Item classes.



Now lets talk about the other main entity called the Customer. What are the attributes of a customer should have when he enters a restaurant. he must have an ID. i am not talking about his passport or SSN or Aadhar card ID. This ID is with respect to the restaurant by which the customer can be identified within the Restaurant premise. We will also add Name as another attribute to a customer. Although there is no absolute need for this from the OOAD designer’s perspective, this is needed only for decoration as you will see later. And what kind of operation a customer usually does. He looks at the menu, decides what he wants to have and how many plates… right? So the customer entity should have an operation called giveOrder. Now think about this. In order to give order customer needs an entity which will hold the customer’s choice, i.e., which item and how many plates for that item. Lets call this entity as ItemOrder, each ItemOrder object representing a specific Item and its number of plates ordered by the customer. So in the actual order by a customer, there will be a collection for all these ItemOrders objects created by the customer. Lets create a class as Order which will hold a list of such ItemOrder objects. This Order class can be used by the Resaturant entity for calculating the total amount to be billed to the customer… right? So in essence, we have got three major classes to design the customer and his flow of orders, namely Customer, ItemOrder, Order. Lets see how these classes will look like.


Remember, all setters and getters functions have been removed from these diagrams (except ItemOrder) to make it simple.

Okay, another helper class we need. That is the bill class. It should have the functionality to calculate the total amount to be billed for a particular customer.
With all these classes ready, lets design the complete class diagram of the Restaurant System.

As you have probably guessed that a Restaurant HAS Tables and Restaurant HAS Menu. Menu HAS Item (rather items, a list of item). Restaurant has an ASSOCIATION with the Customer. The Bill stores a reference to a Customer for future use. Hence Bill has an AGGREGATION relationship with Customer. Each Customer creates an Order. Hence Customer HAS Order. And an Order holds a list of ItemOrders each representing and amount ordered for a particular Item. Hence Order HAS ItemOrder. Each ItemOrder keeps a reference of Item. Hence ItemOrder has an AGGREGATION relationship with Item. The Restaurant USEs Bill to calculate the total bill.

And with this explanation, the complete class diagram will look as the following.
Class Diagram.png

Please note that the complete signatures of the operations are not given in the UML diagrams to make it simple. You can refer the respective class from the source code attached to have an idea of each operation.

Let me  explain the UML in more detail. As you can see that Restaurant has a one-to-one HAS relationship with Menu and an one-to-many HAS relationship with the TABLE. This is quite obvious… right? Because a single Restaurant will have only one Menu list and it may have one to many number of TABLEs. The relationship of the Restaurant with the Customer is Association. Because a customer is an Independent entity. The Restaurant simply adds the new customer to its FIFO queue. As i have already mentioned, that a Customer HAS a Order (one-to-one relationship). Because whenever a customer plans to order, he needs to create an Order which he will populate with different ItemOrders(remember ItemOrder keeps a reference to an Item and how many plates the customer needs). As the ItemOrder keeps a reference to the Items, it obviously has an Aggregation relationship with the Item. A bill also has to keep a reference of the customer because it needs to identify for which customer the Bill has been generated. Hence the Bill also has an Aggregation relationship with Customer. The Restaurant has a USE relationship with the Bill because it creates the Bill object as a local variable in the generateBill function. Now probably you have acquired some sorts of idea about how this whole system has been designed using UML and OOAD.
The code for this whole Restaurant System is here. It is, of course in accordance to this class diagram given earlier.

Hope this helps the OOAD learners....