Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Thursday, August 14, 2014

SKP's Design Patterns - Series II

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-pattaya

 

My Second Blog on Design Patterns, with Real-World Examples & Code Samples. Part 1 of the Blog is Here.


Adapter Pattern [Sample Code]
What can one do if he needs to use an Asian Hairdryer in a European Country, each with different socket types? I would seek an Adapter! As in real life, when we want to plug and play with similar but incompatible interfaces we use the Adapter. The Adapter adapts the Adaptee to the desired interface, by composing the Adaptee object and inheriting the desired interface or by multiple inheritance.
 
Fig. 1 : Adapter (Structural) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


The attached example is a real world Computer scenario, where I want to plug in an external hard drive (pre-usb era!), SeagateDrive of interface type SeagateGeneric to an incompatible computer, SamsungComputer of type Computer. SeagateGeneric provides read() and write() methods for the specified purposes, which needs to be adapted to the actual bufferData(), flushData() and purgeData() methods of the Computer. Note that there is no equivalent of purgeData(). The ideal way to handle this scenario is to throw an exception, whenever this method is invoked on the hard drive as it would do in the real world. The adapter to perform the translation in this scenario is the SeagateAdapter, which implements the Computer interface. It encapsulates a SeagateGeneric instance reference, and adapts it to the Computer interface. Whenever a bufferData() method is invoked on the Computer interface, it actual requires three invocations of read() on the SeagateGeneric implementation to match up to the Computer’s standards. These kinds of translations are done by the adapte.

PCAssembler is the main class here. Try adding your own device and its adapter to the computer.


 
Facade Pattern [Sample Code]
Consider a scenario where we require multiple method invocations on various classes, to achieve the desired functionality. Also, consider that this set of functionality is repeatedly being used in your code. If you are thinking of an option where you will perform direct invocations, you are bound to end up with code maintenance issues and tightly coupled code. If these invocations are remote, it is going to be worse with respect to the performance.
 
Fig. 2 : Facade (Structural) Design Pattern - Class Diagram 
[Source : Wikipedia]
 
 
Under the above mentioned conditions is where the facade comes into play.  Herein multiple method invocations are encapsulated into a single method of the facade class, to achieve the desired functionality. It provides us with a single point of change and looser coupling, with respect to the individual implementations. Remote method invocation patterns like SessionFacade (EJB) adapt from here to improve the overall performance and lower complexity.  
 

Fig. 3 : Facade (Structural) Design Pattern - Sequence Diagram 
[Source : Wikipedia]


The example attached is a very simple scenario of a InvoiceManagerFacade which has addInvoice() and deleteInvoice() methods. To achieve the desired result, each of these methods encapsulates the method invocations from OrderManager, LedgerManager and BillingManager classes.

AccountsCentral is the main class. Try adding your own method to the facade class, or try plugging in a new type of facade.


 
Template Pattern [Sample Code]
Imagine a real-world scenario where a factory is creating both aluminium nails and screws. Though the machine has to create both of them through similar processes, the way some steps are implemented may vary in each of these. When we think of such scenarios in software, we utilize the template pattern. Template pattern defines a way to re-use algorithms for various implementations with different or slightly different outcomes.
 
Fig. 4 : Template (Structural) Design Pattern - Sequence Diagram 
[Source : Wikipedia]


In the attached example, the abstract class SoftwareProcessor defines a general set of algorithmic steps (functions) to deliverSoftware(). This class is my template class. Since the implementation and testing phases differ in projects based on the technology stack being used, CProcessor and JavaProcessor classes adapt this algorithm for these phases. The common methods are all implemented in SoftwareProcessor and the specific ones are left as abstract.

SoftwareConsultants can be used to run this example. Try adding your own processor.


 
Iterator Pattern [Sample Code]
The need to have a handle to a collection of elements, without exposing its internal implementation is met by the Iterator Pattern. I would term this as a pure programming pattern, in its own right. By utilising this handle (Iterator), the client using the collection can easily process the same without any dependency on the internal logic.
 
Fig. 5 : Iterator (Behavioral) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


In the attached example, ProductMenu holds a menu or list of ProductItem. This list and its usage should be implementation agnostic to the clients. Hence, the need for a ProductIterator which implements the generic Iterator interface. The createIterator() method of ProductMenu, passes the array implementation of ProductItem to the constructor of ProductIterator.

The example can be run using ProductMenuTester.


 
State Pattern [Sample Code]
State Pattern defines a way to maintain various steps or states of the same machine or class. The word machine comes to the mind easily, because it is the simplest example of a real-world scenario where there is a need for operating the same object in steps or set states, with the transition from one step to the next defined by a single action (or multiple actions).
 
Fig. 6 : State (Behavioral) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]
 


The example attached is a very crude but helpful one, that of an OnlineShopping site. The limitation of the site being that at any given point only a single item can be purchased and processed. The various states during the purchase and processing are SelectionState, PurchaseState, AuthoriseState, AssembleState (optional) and DispatchState. Each of these states is processed and followed in a sequential manner. OnlineShopping maintains an instance variable of each of these states and also a currentState variable. The various state methods that exist within OnlineShopping are selection(), purchase(), authorise(), assemble() and dispatch(). When client calls these methods, the actual invocations are performed on the state implementation held in the currentState variable. All state implementations implement the State interface, which specifies the lifecycle methods.

ShoppingClient is the main class. Try adding your own states along with the required lifecycle method.


[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-pattaya
 

Thursday, August 7, 2014

SKP's Design Patterns - Series I

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket


Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.


Observer Pattern [Sample Code]
Observer Pattern, as the name suggests, is used in scenarios when updates need to be done at multiple points (Observers) depending on changes in state at another place (Subject). Each of the Observers has to register themselves with the Subject, individually. The Subject should also provide method which allows the Observers to remove themselves. Registered Observers are informed of changes in state through a notify method, usually.
 
Fig. 1 : Observer (Behavioral) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


The provided example is that of a StockBroker application, which involves maintenance of various types of financial information. Subject is the interface in the application which provides a template for the Observed class. StockData is the concrete implementation of Subject and provided implementation of addObserver(), removeObserver() and notifyObservers(). Additionally, it maintains a list of registered observers. IncomeHandler, InvestmentHandler and PortfolioHandler are the various observers used to maintain income, investment and portfolio of a specific StockBroker. All these depend on the constantly fluctuating values of stocks. They are specifically interested in the stockSymbol, stockValue and stockUnits of each individual stock. Each of the observers implements the interface Observer. The Observer interface provide the update() method, which is implemented by each of these concrete classes.

Use StockBroker.java to run the application, Try adding your own observer to this application. Also, you can try picking up these values from a live web service and then writing a custom observer which depends on this.



Decorator Pattern [Sample Code]
Decorator Pattern provides an elegant way to use composition for enhancing functionality, where the result expected has direct dependency on the composed and composing class. A chain relation (via composition) or decoration can be finally used to achieve the desired output at runtime. In real-time, when the functionality of one particular product is expected to be built form a base product and various other related sub-products or fixtures, we can rely on the Decorator.
 
Fig. 2 : Decorator (Structural) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


The attached example is that of a Pizza application. Here, the pizzas in the shop are made with various combinations of bases and topping combinations. This is a classical example for usage of the decorator pattern. Pizza is the abstract base class for each of the pizza bases to implement and ToppingDecorator is another abstract class that inherits from Pizza for each of the toppings to implement. Hawaiian, Italian and Mexican are the concrete implementation of Pizza whereas Mushroom, Onion and Chicken are the concrete implementations of ToppingDecorator. Each of these toppings encapsulates a Pizza instance. This instance, at runtime, will hold another topping or the pizza base instance. Finally, it is when the cost has to be calculated on the entire pizza that the real value of decorator pattern is seen and just one call suffices to calculate the entire bill value.

PizzaWorld is the main class. Try adding more decorators and pizza base classes to see if you can get a real taste of the Decorator!



Singleton Pattern
Singleton Pattern defines a way to maintain only single instance of a class in the entire execution of a program/application and to provide a uniform way to access it. There are numerous methods which exist in which this pattern can be implemented. I have explained three most common scenarios here:
 
Fig. 3 : Singleton (Creational) Design Pattern - Class Diagram 
[Source : Wikipedia]

 

1. Eager Singleton [Sample Code]
The simplest singleton is the one in which the instance is created at class-load time, and stored in a static instance variable. A static getter method is then used to get this instance, when required. The instantiation of an object earlier than its first use might not be a recommended approach.

In the given example, MediaContract (Main Thread) works on an instance of the ProductionHouse (Singleton). The Singleton is instantiated at class-load time and maintained in the private static instance variable. getInstance() in ProductionHouse helps in retrieving the instance.

 
2. Thread-Safe Singleton (Most Common) [Sample Code]
To overcome the above drawback, the recommended approach is to instantiate the object at the first access time and also to make it thread-safe to prevent concurrent thread instantiation. The disadvantage of this method is poorer performance, as the method is synchronized.

As in the earlier example, the classes are MediaContract (Main Thread) and ProductionHouse (Singleton). getInstance() method is synchronized and the instance is created only if it is null.

 
3. Double-checked Locking [Sample Code]
The disadvantage mentioned above can be critical for a highly accessed object in an application. To better this, the scope of the synchronized block is reduced to affect only the first access. This again has some disadvantages. I recommend reading on Initialization on Demand Holder Idiom.

The example remains the same, the difference being in the reduced scope of synchronisation within the getInstance() method and also that it affects only the first access and not subsequent accesses.



Command Pattern [Sample Code]
In scenarios, where we need to create a sequence of actions (or operations) and perform them at a specified (later) point in time, we have a candidate for usage of Command Pattern. Though it very closely resembles the Observer pattern in implementation, the usage is different and the command (actions) is invoked only on a single chosen receiver by an invoker, than on all observers.
 
 
Fig. 4 : Command (Behavioral) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]


The example is of an Auction House where there are various items for auction, the base abstract class of which is represented by AuctionItem. The abstract method to be implemented by implementing classes is sell(). AuctionVase, AuctionFurniture and AuctionJewel are all concrete implementations of AuctionItem. Instances of each of these are created and set (mapped by an itemKey) into the AuctionControl, which can be thought of as a remote control for presenting items in the AuctionStore. Whenever the presentItem() is invoked on the AuctionControl class, passing in an itemKey, the appropriate AuctionItem instance is selected and sell() is invoked on this instance.



Factory Pattern
Factory Pattern, I am made to believe, is the most widely used and implemented pattern in software projects after the Singleton Pattern. Since Singleton is only a creational pattern at single class level, the scale of the effect of usage of Factory should be much higher. Factory Pattern deals with creation of similar type of objects and production in a centralized manner, depending on the condition or type of object requested. There are variations of the usage of factory pattern, three of which I have enlisted below:

 
1. Simple Factory [Sample Code]
The simplest factory is the one that is used to create (instantiate) a specific type of product (object) depending on a condition. The specific types of objects that can be created in a single factory are all expected to implement a single interface.

In the attached example, the factory is used to instantiate a specific type of object depending on the operating system. All the specific systems implement the System interface, which defines the common methods that the concrete class of this type should implement. SystemFactory is the factory class which provides the create() method which takes a type argument. The type argument decides which concrete factory should be instantiated.
 

2. Factory Method [Sample Code]
When there can be various families of products (objects) that which can be instantiated, but each family of these product needs to be created by a specific type of factory, we define a factory method in the base factory class. The concrete implementations of the base factory then override this method to produce concrete type of products, depending on the condition.
 
Fig. 5 : Factory Method (Creational) Design Pattern - Class Diagram 
[Source : Wikipedia]


In the example, you can notice the presence of two abstract classes, Mobile (Product) and MobileStore (Creator). One family of concrete product implementations are NokiaASeries, NokiaBSeries and NokiaCSeries to be created by the NokiaStore, which is the concrete implementation of the creator. In similar fashion another family of products such as SonyASeries, SonyBSeries and SonyCSeries are to be created by SonyStore, another concrete implementation of MobileStore. MobileStoreCentre is the main class to run this application. The createMobile() method is the abstract method (factory method) that is to be overridden by the creator implementations.
 

3. Abstract Factory [Sample Code]
AbstractFactory defines a template or interface for creation of similar types of objects or implementations. Usually, AbstractFactory will encapsulate a factory method or more within for actual creation of the product.
 
Fig. 6 : Abstract Factory (Creational) Design Pattern - Class and Sequence Diagram 
[Source : Wikipedia]

 


Taking the same example as above, MobileStoreFactory instantiates the concrete instance of the abstract factory (MobileStore) based upon the variable specified, either "Nokia" (NokiaStore) or "Sony"(SonyStore). The factory is then responsible for creating the objects of similar types based upon the choice - such as "ASeries" or "BSeries" or "CSeries". The mobile is then assembled based upon this by the MobileStore. You may use MobileStoreCentre to run this example and understand the design pattern based on the output.


[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket
 

Friday, September 27, 2013

Journey to be a Goooo.... ooogler! (Interviewing at Google!)

The most discussed, most sought after, one of the largest and on the bleeding edge of technology, in our times. Which software product development company comes to most developer’s/architect’s mind? - Google! Finally, I am close to being part of this team. I have worked for other top software development companies (in their own domain), of our time, Siebel (Oracle), GXS (OpenText), Huawei, Symantec, Misys (Finastra) and Yahoo (Verizon). I also do have good amount of experience in top consulting companies (in various domains) of the world like Infosys and Headstrong. The one where I want to be, is finally the one calling on to me - Google!

Google Logos - Over the Years


I would like to tell you a specific record of mine before we go ahead. I had applied for the Genius Book of World Records (Also, Limca Book of Records, India) for not being able to pursue my MS/MTech/PhD in Computer Science – Seven Times. This is after securing admit, not offered, clearing initial tests or being shortlisted for interview. The administrator says they do not keep such records – else I would be the only student registered under such a record. If I would have been a Master’s or Doctorate in Computer Science, Google would have been much more of a valid terminal point for Research and Development as also Programming. I am only a Bachelor’s in Computer and Information Science. Though I do not rue this fact, I need to rely only on my Programming Skill and Experience now to ace the interviews.

So, Google! Yes. I had been interviewed by Google India in 2012, for a position in Bangalore. Though I reckon that I answered about 4/5 questions right in the first telephonic screening, I was not selected beyond that round. I had no way to question the decision and just accepted it!

They sourced my CV again from their data bank in 2013. This time from Google California. The recruiter or sourcer, initially sent me an email asking my interest for a position at Google. I sent a positive response to him. He then asked me for time slots in Pacific Time (Remember, I am in Indian Standard Time – GMT +0530 – PST +1230). I gave him a time slot, which is quite some time after my dinner – so if you are in India – get ready for a late night interview. The exact slot I gave him was 10:30PM IST. Whoa!

It's time for me to be a Goooo.... ooogler! Well, as a Computer Science Student, Programmer, Architect, Developer and Geek, the only other company that I want to have on my resume as badly is Microsoft. But Google slightly takes the edge in favoritism, in terms of my core competencies and skills. Also, my experience in programming languages and stacks such as Java, J2EE, C and C++; incline me towards Google!

Why would they have considered me?
I have worked for top product companies like Siebel, GXS, Huawei, Symantec, Misys and Yahoo. I ran a product startup named TechArmy – which was in the area of analytics and search engines. I have informal and formal grounding in programming and computer science since the age of 13 – and also an undergraduate degree in computer science. (I do have a sort of world record in my name as mentioned above – which should informally work in my favor for absolute product companies if they do consider those of any merit at all, of course!)

What would they have found different in my resume?
I am an absolute do-er. I believe mostly in execution. It is build, break and innovate. Either wise, it is innovate, build, break and keep building. I am a programmer to the core. My primary skill is Java and J2EE. The secondary programming languages I consider are C and C++. I am twice certified on Core Java, Sun Certified Java Programmer 1.4, Sun Certified Java Programmer 5.0. I am certified on each of C and C++ as Quest C Proficiency Certified and Quest C++ Proficiency Certified. I am also certified in Data Structures as Quest Data Structures Proficiency Certified. Additionally, I am certified on Enterprise Java as Sun Certified Business Component Developer 1.3 and Sun Certified Business Component Developer 5.0; The last one would have mattered the least to them as they are primarily a Computer Science, C, C++, Java, Python, Algorithms and Data Structures company – as per my knowledge. I think I hit all the sweet spots except for any experience on Python! So, Experience, Education, Certifications and Continued Education – all of it matters to them.

What was the initial mail all about?
The initial mail is that they have found your resume relevant to positions at Google. They would like to check your interest level for the same. It does not mention anything about the actual position or title that you are being considered for.

What is the initial telephonic screening about?
This screening round is about mostly a mix of computer science and programming. I did no preparation, nor did I follow any blog, nor did I do any brush up on my skills – I just went ahead with what was in my head! Computer Science and Programming. I am at nine years of experience level and was able to comfortably clear questions on Computer Architecture, Programming, Algorithms, Data Structures, Unix and Unix Internals. I was right on almost all of the questions, except that I faltered completely on a Unix Command. I have been using Windows most of the time, this was the real reason. I thought I have ruined my chances only with that question – but that was not the real case!

What seems to be the expectation of the sourcers during the initial screening?
They want people who can think through along with them. I was thinking out aloud on the approaches that were in my mind for each problem presented. I was also able to suggest multiple ways of doing the same things – and that I am taking time to find what is the best in the current situation. You have to keep him along with you and let him know that you can solve a problem – but are trying the most efficient way in terms of space, time or both. At times, he may also suggest or give some tips – as both of you enter into a conversation than a questionnaire session. If you are stuck somewhere or taking time – it is advisable to keep the interviewer apprised of the quick or brute force approach that you already have. The interviewer does give you ample time to answer.

What happens once you are shortlisted?
So, once the sourcer is done with the questions – by which the sourcer has ascertained your fitment for Google – he or she informs you that another interview with a Google Technical Panel will be scheduled. In my case, it took the interviewer about an hour before he made the decision. There were about total six questions in all, in the areas I had mentioned above. He also informed me that this position would be for Google Australia and whether I would be fine to work in Australia. California would have made me really happy, but I said I am absolutely fine with the location. He said either of the Technical Panel from Australia or the California office would call me. I bid a good night to him, whereas I actually I had to bid him a good day! That was the only other mistake I made.

What kind of help/information does the Technical Sourcer share with you?
I got a mail in the next two days from the same sourcer or recruiter asking me for another set of time slots in the next three weeks for the Technical Interview. I gave him a list of about six to eight slots. He also shared that now there will be a recruiting co-ordinator involved who would be actually setting up the interview. He shared everything that is involved in the selection process in a mail along with lots of links on what topics to prepare. The mail also provided tips on how to ace the interview, what is expected from a candidate and the background of Google's business.

What kind of documents did I receive before the second interview?
The recruiter shared two very important documents along with the links. One of them contains the type of preparation required for the interview. This includes types of questions and a few further reading links. The second of them contains a longer list of topics and the absolute types of questions that may be asked during these interviews. It contains coding questions, design questions, blog links, videos, recommended books and online course links. In a way the Google hiring team is preparing and providing the candidate with an exhaustive set of documentation and information to ace the interview! If you have been programming for a long time and like solving complex problems in computer science – you are ready for the interview.

What is my preparation for the second (or maybe pre-final) round of interview?
My preparation includes topics like Core Java, Recursion, Bit Manipulation, Reverse Linked List, Singly Linked List, String Manipulations, Arrays, Trees, Graphs and Pointers. I also will go through a bit of C, C++ and Unix. I will design solutions for twice (and similar) the number programming problems they have provided as examples. I will brush up on other main topics in Computer Science – Algorithms, Networking, Databases, Operating Systems, Programming and Architecture. I will also try to get up to some Theory and Discrete Mathematics before the interview. That’s all. I will rely on my close to 17 years of informal, formal programming and computer science knowledge to clear this. Well, I am gonna keep you all informed how well I did on this one. This was later scheduled and I was down with Typhoid and could not take up an interview for a long time. I later decided to search for a job in my hometown (where Google does not exist) and move out from the interview process.

What is my expectation beyond the second round of interview?
I guess I will be called onsite for the interview. Well, this maybe California or Australia. I am not sure as I read on somebody else’s blog that this is the convention that they follow. This is for the last set of rounds of interview they have before they take you in or bid goodbye!

Google or No Google, What am I upto?
I stick to my love for Java, as also J2EE. I am gonna complete my Oracle Certified Master, Java Enterprise Edition 6 Architect certification by the year end. I am also planning to take up my Spring and Hibernate certifications and take my knowledge to expert levels – but only through Brainbench Certifications. With that, I will have ten certifications in all; in Algorithms, Data Structures, C, C++, Java and J2EE! Early next year, I plan to start on my application for the Executive Post Graduate Certificate Program in Information Technology (Executive MBA). That’s it! The Google Experience would only multiply the value of all of these! Otherwise, it has to be one another consulting or another product company.

I will keep you updated on my second round of telephonic discussion. I am not in a position to post the real questions as I have no permission from the company resources. I later decided to search for a job in my hometown (where Google does not exist) and move out from the interview process. Neither Google or any other company endorses this post, but I am only providing an informal write-up of my experience - so that it can be helpful.

[Google - 2/2]


[Update : 2012-2016]

On a Serious and Correct note, I thought about my career goals, my unfulfilled academic/professional goals and everything that I am as an individual - The Journey of Myself - The Ex-Yahoo, Ex-Symantec, Ex-Siebel (Oracle), Ex-Huawei, Ex-GXS (OpenText), Ex-Misys - AND - The ONLY name that I want to re-emphasize as my Dream Company and that I want to see on my resume is - Google!

Saturday, May 29, 2010

Clash of the Titans, C++ vs Java!

As a software engineer, the mind is trained to seek optimizations in every aspect of development, and ooze out every bit of available cpu resource to deliver a performing application. This begins not only in designing the algorithm or coming out with efficient and robust architecture, but right onto the choice of programming language. Most of us, as we spend years in our jobs - tend to be proficient in at least one of these. 
 
Recently, I spent some time to check on the performance (not a very detailed study) of the various programming languages. One, by researching on the internet; Two, by developing small programs and benchmarking. The legacy languages - be it ASM or C still rule in terms of performance. But these are definitely ruled out for enterprise applications due to the complexity in development, maintainability, need for object orientation and interoperability. They still will win for mission critical or real-time systems, which need performance over these parameters. There were languages i briefly read about, including other performance comparisons on the internet. These include Python, PHP, Perl and Ruby. Considering all aspects and needs of current enterprise development, it is C++ and Java which outscore the other in terms of speed. According to other comparisons [Google for 'Performance of Programming Languages'] spread over the net, they clearly outshine others in all speed benchmarks. So much for my blog title :-) So when these titans are pit against each other in real time, considering all aspects of memory and execution time - Java is floored. Though I have spent last 7 years of my life coding and perfecting my Java and J2EE skill - I suddenly feel... Ahem, Slow! One of the problem statements to verify this is given below (alongwith the associated code) and the associated execution parameters. 
 
[Disclaimer: Problem Statement given below is the property of www.codechef.com]
In Byteland they have a very strange monetary system. Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit). You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. You have one gold coin. What is the maximum amount of American dollars you can get for it? Input The input will contain several test cases (not more than 10). Each testcase is a single line with a number n, 0 <= n <= 1 000 000 000. It is the number written on your coin.  
 
JAVA SOLUTION (Yet to Upload)
C++ . SOLUTION (Yet to Upload)
 
RESULTS

TIME

MEM

LANG

0.00

2.8M

C++ 4.3.2

0.26

218.3M

JAVA

 
 
I am sure these results will continue to be remain in the same ratio (with slight variations for other or benchmark problems) - even with the most optimized java code.