Monday, July 3, 2023

C++ : Pointers and Reference

 Demo to illustrate use of pointers and reference when passed as parameter to a function

Example : https://github.com/puthukkudi/PointersAndReference.git

C++ : Adapter Pattern

The adapter pattern convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.


Examplehttps://github.com/puthukkudi/AdapterPattern.git

Sunday, July 2, 2023

C++: Abstract Factory Pattern

Abstract Factory design pattern is one of the Creational pattern. Abstract Factory pattern is almost similar to Factory Pattern and is considered as another layer of abstraction over factory pattern. Abstract Factory patterns work around a super-factory which creates other factories.

Abstract factory pattern implementation provides us with a framework that allows us to create objects that follow a general pattern. So at runtime, the abstract factory is coupled with any desired concrete factory which can create objects of the desired type.


Example :


In Factory pattern example we had vehicle factory to create car and bike object.Now in Abstract factory pattern we introduce one more level where client ask vehicle factory to create either TATA car or Toyota Car. Similarly it cas ask to create TATA bike or Toyota bike.


https://github.com/puthukkudi/AbstractFactoryPattern.git




Saturday, July 1, 2023

C++ : Factory Pattern

  •  Factory Pattern comes under creational pattern.
  • It provides a way of creating the object without exposing the creation logic to the client.

Example : Vehicle library for the client

Friday, June 30, 2023

C++ : Singleton pattern

 Singleton Pattern


Singleton is creational design pattern.
Only one instance of the class is created in Singleton Pattern.

Example :

- Only one instance of confriguation manager
- Only one instance of Logger
- Only one instance of db connection





Thursday, June 29, 2023

C++ : Constructors And Destructors

Constructors are used to construct an instance of a class and initiallize the data members of a class.

In C++ initiallization of data members are mandatory.

Destructors are used to deallocate the memory occupied by the instance of a Class.

Please check the example below :

https://github.com/puthukkudi/ConstructorsAndDestructors.git

C++ : Virtual Functions

Virtual functions helps to override methods from base class.
If the Base class and the Child class  both defines the function method() then the pointer reference of Base class pointing to the object of Child class when used to call function method(); it will call the Base class function method()

i.e;

Base * base = new Child();
base->method(); // this will call the Base class method() ; unless untill you declare method() as virtual in base class.



Internal Working :

If compiler finds any virtual function it creates a static array for each class called VTable or Virtual Table. Elements of this VTable are the function pointer to each member function.Since Vtable is a static array it means its object independent.

During object creation compiler creates a secrete data member for the base class. This data memeber is called Virtual Pointer. This Virtual Pointer is inherited by the child class. Respective class instances's virtual pointer points to respective class's VTable. Hence provisioning for overriding. 

Virtual Functions can't be static as static functions are tied to a class and not to instance of a class.






Please check the example below : 

https://github.com/puthukkudi/VirtualFunction.git

Wednesday, June 28, 2023

C++ : POINTERS

A pointer is an integer that stores the memory address.



Consider  a single street, with houses on one side from start to end.
Memory in a computer is just like this street, its an one dimmensional array/line, with a sequence of byte arranged in that 1D array. So one byte is equivallent to one house.

Now each house will have an address. If someone want to post a gift to a particular house you need an address to that house. Similarly for writting / reading from memory you need the address to that particular byte. This address is held by the pointer.

Please check documentation folder in project below : 







Wednesday, January 21, 2015

MVC ( Model View Controller ) in iOS - Part I

Hello Amigos!

   In this blog I have explained the MVC design pattern. Hope you'll like it.


   MVC (Model View Controller) is an architectural pattern for implementing user interface. The Model-View-Controller design pattern (MVC) and its variants have been around at least since the early days of Smalltalk. The design pattern is fundamental to many mechanisms and technologies in Cocoa Touch.


  It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.The objects in MVC pattern can be segregated into one of the three roles in an application named "model, view or controller". MVC pattern also describes the way objects communicate with each other across the boundaries of their roles.  


Components of MVC and Roles Played By Them In Architecture






  • Model

Model represents the business logic of your application.It is the object that encapsulate the application data and defines how to manipulate it. These object are reusable as it represents the knowledge applicable to specific problem domain. Once any persistent data is loaded in application it must be put into a model object. In ideal case model object should not have any explicit association with the UI used for presenting and editing it.

A model notifies the controller when there is a change in state so that Controller can change its commands and send update command to the respective view. Model also takes command from the Controller to update it's state when there is a change in view on user action. 

As said Model are UI independent, and cant talk directly to controller.It always notifies Controller using broadcast mechanism.


  • View

These are the UI objects that represents what users see on device. A view object can respond to the user actions  and knows how to present itself on the screen. A view generally presents the data obtained from application. On any user user actions Controller commands the Model to update its state. 

Despite of the close relationship between the view object and model object, they both are not coupled with each other in an MVC application. View object never stores the data it is presenting. But it can cache it for some performance reasons. It has protocol to acquire data if needed

A view object can work with a portion of / complete / multiple model object. Thus they tend to be reusable and consistent across different applications.



  • Controller

Controller is the intermediary between one or more application view object  and one or more of its model object. It co-ordinates all work. controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document). 

Apart from mediating role , controller object can other operations like managing life cycles of other object, performing setup and co-ordinating tasks for the application. Depending on the required design, controller objects can be either reusable or non- reusable.

View need to synchronise with controller. Controllers sets itself a s a view's delegate. Also it  drop a target on itself so that Model can communicate to it.

Figure below explains the Interaction between components:







MVC is not a bottom-line design pattern by itself. It contains several more relatively primitive design patterns.The elemental design patterns in MVC work together to define functional collaborations that are characteristic of an MVC application.The Cocoa (Touch) version of MVC comprises the Composite, Command, Mediator, Strategy, and Observer patterns. 


  • Composite : The view objects forms a view hierarchy in a coordinated manner. The view components in the hierarchy can range from compound views (such as table views) to individual views (such as text boxes or buttons). Each of the view nodes at any level can respond to user actions and draw itself onscreen.

  • Command : This is a target-action mechanism in which view objects can defer an execution on other objects, such as controllers, until certain events have occurred. The mechanism incorporates the Command pattern.

  • Mediator : A controller object plays a middleman role that adopts the Mediator pattern; it forms a bi-directional conduit for the flow of data between model and view objects. Changes in model are communicated to view objects through the controller objects of an application.

  • Strategy : A controller can be a “strategy” for any view object. A view object isolates itself in order to maintain its sole duty as a data presenter and delegates all application-specific decisions of the interface behaviour to its “strategy” object (the controller).

  • Observer : A model object keeps interested objects such as controllers updated with any changes to its internal state. 



In next post will give an example that implements MVC pattern. 

Reference : 
Objective-C Design Patterns for iOS - Carlo Chung
Wikipedia


Saturday, April 12, 2014

Formula to solve any (Non-Preemptive) Gantt Chart

Each scheduling algorithm favors particular criteria:
(http://academic.udayton.edu/SaverioPerugini/courses/cps346/lecture_notes/scheduling.html)

  • CPU utilization (maximize)
  • throughput: number of processes which complete execution per time unit (maximize)
  • turnaround time (TA): total amount of time to execute a particular process (minimize)
  • waiting time: amount of time a process has been waiting in the ready queue (minimize)
  • response time: amount of time it takes from when a request is submitted to when the response is produced (minimize); does not include the time for a response to be output

Formula to solve any (Non-Preemptive) Gantt Chart:

Waiting Time = Service Time - Arrival Time
Turnaround Time = Finish Time - Arrival Time
Finish Time = Service time + Burst Time
Service Time = Service Time of previous process + Burst Time of previous process

Thursday, December 26, 2013

Creating Adobe - AIR Native Extension for iOS

Holla Amigos !,

In todays blog session I'm going to discuss the  procedure to generate Adobe AIR ANE (Adobe AIR native extension) for iOS devices. Before going further let me first tell you something about AIR and ANE.


What is Adobe AIR?
    The Adobe® AIR® runtime enables developers to package the same code into native apps for iPhone, iPad, Kindle Fire, Nook Tablet, and other Android™ devices, reaching the mobile app stores for over 500 million devices.

What is a native extension?

      Native Extensions for Adobe AIR are code libraries that contain native code wrapped with an ActionScript API. Native extensions provide easy access to device-specific libraries and features that are not available in the built-in ActionScript classes. Examples of native extensions include making a mobile device vibrate, integrating ad-networks and in-app purchasing systems into your games, and using the iOS GameCenter in your iOS games.



This blog also explains one of the most important feature called Method Swizzling and its usage. This was posted by me long back in a Facebook forum.  (https://www.facebook.com/groups/330366610363679/481424851924520)


Now let us start with a demo ANE creation example. We will be creating an ANE to open my blog in iPhone and to show a welcome alert when the application will resign active . We will her do method swizzling for  Application delegate method applicationWillResignActive: .

Here are the steps:

1) Open Xcode and create a new  project to make a cocoa static library. Name it  BlogViewerLib.

2) Add FlashRuntimeExtensions.h from /Applications/Adobe Flash Builder 4.6/sdks/4.6.0/include

3) Modify your BlogViewerLib-Prefix.pch as follows:












Here we imported necessary headers. objc package classes are required for method swizzling.


3) Modify your BlogViewerLib.h as follows:



4) Modify your BlogViewerLib.m as follows:











Lots of coding!!!!! lets see what we have done in BlogViewerLib class. The class inherits the NSObject class and implements UIApplicationDelegate and UIAlertViewDelegate protocol. UIApplicationDelegate is to implement the application delegate method applicationWillResignActive: .

I didn't used UIAlertViewDelegate methods but if you want you can implement its method. So its optional for this project.

I used a macro definition of a method named DEFINE_ANE_FUNCTION which returns an FREObject (please visit this link.1) and takes following parameters:


FREContext ctx   : please visit this link.2
void* funcData  :
uint32_t argc 
 FREObject argv[] 

please visit this link.3

Then we have defined a blank implementation of applicationWillResignActive: . Inside the implementation block you can define other delegate method also.  customApplicationWillResignActive is the custom method which will replace the delegate method applicationWillResignActive: . It has FREDispatchStatusEventAsync( ) , which send a callback to AS3.0

Please check the implementation of customApplicationWillResignActive() and BlogViewerContextInitializer() to see how method swizzling is performed.


Next you need to implement the contextInitiallizer , contextFinallizer, extesionInitiallizer and extensionFinallizer methods.

please visit this link.4
please visit this link.5


5) Go to edit scheme and use release. Now Clean the build and build. You will get libBlogViewerLib.a .

6) Now create a flex library project. Include AIR SDK  in the project settings. Check Flash builder project in Blogger_AS3 and a project in default folder. Both are the projects with same name . But the one in default has blank implementation.

I this project we have created an extension with id "com.dreams.dreamsbloggerane" . we will use this extension to call method implemented in our objective-C library. Be careful, with the method name. It should be same as the name declared for each FREFunction() in contextInitializer().

The class BlogViewerExtension extends the EventDispatcher, and implements the onStatus() method, which handles the events dispatched from library  by FREDispatchStatusEventAsync().




























7) Check your extension.xml file in ANE_GENERATOR. 



















It defines properties for default and iPhone-ARM platform.

8 ) Building both projects you will get Blogger_AS3.swc files . If you unzip this you will get library file. Get these two library files and keep in iOS and default folders in ANE_GENERATOR. Copy pate the  libBlogViewerLib.a file in iOS folder. SWC file builded for iPhone-ARM must be kept in ANE_GENERATOR. Now cd to ANE_GENERATOR and run following cmd.

admins-MacBook-Pro:ANE_GENERATOR prashantp$ /Applications/Adobe\ Flash\ Builder\ 4.6/sdks/4.6.0_3.9/bin/adt -package -target ane BlogViewerLib.ane extension.xml -swc Blogger_AS3.swc -platform iPhone-ARM -C ios . -platform default -C default .

please visit this link.6



9) You will get .ane file in ANE_GENERATOR . You can now use this as a native lib in your AS3.0 AIR-iOS project. Please check testBlogger project.




source download : download








Monday, December 9, 2013

Mind Re-Fresher Queston

Hola Amigos,

Here is a mind refreshing question for you all. You remember increment (++) operator. Of-course you do .....

Then tell me the difference between y++ and ((y+=1)-1) ?


Ans: Both are same statements

if y = 1

and a = y++ => a = 1; y = 2

and if a= ((y+=1)-1) =>   y+=1 = 2  
=>   ((2) -1) => a = 1; y = 2

Saturday, July 13, 2013

Memory management in Objective - C


Bonjour les amis,

 
This post explains the memory management in Objective-C .
Amigos with C++ background can also refer to this post as it will help them to get a basic idea of how the memory is allocated  and should be handled by you. If you have worked or working on any in house frameworks, this post will help you to get some overview of how memory handler module works in your  your framework.

Before going any further I would first like to explain the "
Brique de fooundation" of memory management in C++, Reference counting. Consider two programmers working on two different classes but using same reference of any object xyz. Now who will delete the memory allocated to this object? If programmer1 delete the object and programmer 2 is still using it he will get a crash. Now how the programmers will know when to delete the object and who will delete it ? Now consider the same situation in a large project where many programmers are working on different classes and they all uses many such object's reference in different classes!!!! problemas? Of-course it's a big problem!!! To solve this issue reference counting was engineered.


What is reference counting ?


Definition from wiki : 
In computer science, reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource.

In layman language a reference count is an internal count managed by an object, indicating the count that someone has its ownership.

What is ownership:  An owner of an object is the code snippet which states that "it needs that particular object and no one can delete it".

Methods/Messages related to memory management in Objective- C

alloc (also called "new") : This will create a new object and claims an  ownership of it.

      alloc will explicitly creates an instance of an object. The piece of code creating object using alloc is the only whole soul owner of that object and should delete that object when it has done with it. This will increase the retain count of that object by one. 


retain : This will claim an ownership of an existing object      retain will increase the retain count (reference count) by 1 and makes the calling piece of code a new owner of that object. So some one using retain can say I am also the owner so no one should delete the object till I am done with it . Here also the object should be deleted once its usage is over.


copy : Creates a copy of an object and claims an ownership of it 

    copy will create a copy of the existing object and makes the calling piece of code the owner of that copy of object. So this copy will manage the separate track of retain count. And this copy of object should be deleted when its usage is done.

release : This will delete the object and take away the ownership.

    release will will delete the object decreasing its reference count by 1. But remember "only owner should use it".
 
autorelease :
This will delete the object automatically and don't give the ownership.
    with autorelease  you don't lock the object but you be the temporary owner of the object such that it is deleted automatically when after sometime its usage is over. All the objects are kept in a memory pool called autorelease pool ( an instance of NSAutorelease class) and are deleted at once like  a garbage collector when the pool cleaned. The reference count is made 0 when the objects are deleted.
 
   ARC ("automatic reference counting") is the  the garbage collector mechanism in Objective - C  . All new projects generally uses ARC to prevent the overhead of manual memory management.



Thursday, July 4, 2013

Shallow and Deep Copy in C++

!Hola,

Hope!  my last post was useful for you guys. Guess now you are  aware of dynamic memory allocation for an Array !!!  This post explains the Shallow and Deep copy. Another confusing topic of object oriented programming.

Before proceeding please make sure that you know what is constructor. ( Great!!!!,  that is the minimum qualification required to understand this post)

Now what is a copy constructor ?
A copy constructor is used to copy an object. Suppose we have a class named Dreams. Then the syntax for declaring the copy constructor will be:

syntax:

public Dreams (Dreams & otherDreams);



Make sense!!! 
So what are we doing above ? We are passing the address of the Dream's object to the constructor.
Note : In C++ even if you don't create any constructor, the compiler by default adds a default constructor (interview question)
The default copy constructor provided by the C++ compiler always does the shallow copy. But what actually is a shallow copy? For this let us look into a code snippet below:

class Dreams

{
    public:
    int dreamSize;
     String * dreamCategory;

    
     // empty constructor
     Dreams( )

     {
             dreamSize = 10;
             dreamCategory = new String[dreamSize];
      }

     // copy constructor
     Dreams(Dreams & otherDreams)

     {
         dreamSize = otherDreams.dreamSize;
         dreamCategory = others. dreamCategory;     // note this usage of " = "
      }
  
      ~ Dreams()
      {
             delete[] (this->dreamCategory);
       }
};

class Test

{
      int main( )
     {
          Dreams dream1; // calls  empty constructor
          dreams1.dreamCategory[ 0 ] = 20 ;

         {
               Dreams dream2(dream1);  // calls copy constructor
               cout <<" value of dream1.dreamCategory[0] : %d", dreams1.dreamCategory[ 0 ];

         }    
       
         //segmentation fault error below

         cout <<" value of dream1.dreamCategory[0] : %d", dreams1.dreamCategory[ 0 ];
         return 0;

   }
};


so what is happening here ?
in main() we first created a object  dream1 then we created object dream2 of class Dreams to which we passed dream1.This will call the copy constructor which in turn assigns the member's value of dream1 to dream2.

Did you noticed something awkward happening above? Will the code run properly ?
Answer is no , it will give segmentation fault error!!!!!

Consider the scope of dream2 ( dream2 is inside curly-braces ) . Once the scope of dream2 ends the destructor will be called and the memory allocated for the dream2.dreamCategory will be deleted so will be deleted for dream1.dreamCategory

Why?

Because in copy constructor 
dreamCategory = others. dreamCategory;  will allocate same memory allocation for  dream1.dreamCategory and dream2.dreamCategory.  THIS TYPE OF COPYING IS CALLED SHALLOW COPY





To prevent this we need to create our own version of copy constructor and allocate memory for dream2.category separately like this.

class Dreams

{
    public:
    int dreamSize;
     String * dreamCategory;

    
     // empty constructor
     Dreams( )

     {
             dreamSize = 10;
             dreamCategory = new String[dreamSize];
      }

     // copy constructor
     Dreams(Dreams & otherDreams)

     {
         dreamSize = otherDreams.dreamSize;
         dreamCategory = new String[dreamSize]; // explicit memory allocation
         for(int i = 0, i < otherDreams.dreamSize; i++)

         {
                 dreamCategory[i] =  otherDreams.dreamSize[i];
         }

        // you can also use std::copy instead of for loop      
      }
  
      ~ Dreams()
      {
             delete[] (this->dreamCategory);
       }
};

class Test

{
      int main( )
     {
          Dreams dream1; // calls  empty constructor
          dreams1.dreamCategory[ 0 ] = 20 ;

         {
               Dreams dream2(dream1);  // calls copy constructor
               cout <<" value of dream1.dreamCategory[0] : %d", dreams1.dreamCategory[ 0 ];

         }    
       
         //no segmentation fault error below

         cout <<" value of dream1.dreamCategory[0] : %d", dreams1.dreamCategory[ 0 ];
         return 0;

   }
};

Here as you see we have explicitly allocated memory for dream2.THIS TYPE OF COPYING IS CALLED DEEP COPY.  So the memory map will look like this:




Hope this post was useful. Please give  your valuable comments or if you have any queries feel free to post.