Monthly Archives: April 2014

Template method pattern vs Strategy Pattern

Template method pattern and Strategy pattern can appear quite similar in nature as both help us execute an algorithm/ code steps and define executions differently under different circumstances.

The major difference is that Strategy pattern let you decide complete different strategy i.e. set of algorithm(s) based on requirement at the run time, for example which tax strategy to be applied Indian or Chinese. On the other hand, Template pattern puts in some predefined steps (of a algorithm), out of which some are fixed and others can be implemented differently for different usages, say read data from file, parse data, write data to file- parsing might be done differently based on kind of data we are dealing with, but reading from and writing to file will be fixed.

More here –

http://kamalmeet.com/2013/03/understanding-strategy-pattern/
http://kamalmeet.com/2014/04/template-method-design-pattern/
http://stackoverflow.com/questions/669271/what-is-the-difference-between-the-template-method-and-the-strategy-patterns

Template method design pattern

Template method design pattern allows one to create a template of code or algorithm which will provide guidelines for other developers on how to write the solution for different implementations.

To keep it simple, let’s go back to HTML template. HTML template lets you define overall look and feel of page without getting into details. For example, I want all my pages to have a header, a footer, left panel, right panel, middle content panel. I might want to add some parts are fixed, say header and footer will always looks same, but center, right and left can be customized by users.

Same principle is used in template design pattern. Say I have to implement a template reading data from database.

Step 1: get database connection
Step 2: create query
Step 3: Execute Query
Step 4: Parse Data
Step 5: Close connections

Here Step 1, 3 and 5 are common for all type of queries but Step 2 and 4 will be data dependent. This can be achieved by Template Method pattern.

A good explanation can be seen here

templatemethodpatternexample

Image from http://javapostsforlearning.blogspot.in/2013/03/template-method-design-pattern-in-java.html

Spring Framework- Basics

The question which I asked 4 years back when I was to use Spring framework for project was- Why Spring? I was using Struts for few years and was in love that, so why to try something new.

Over the time I have found a very convincing answer which I will share.

    1.Empowering POJO’s
    2.Dependency Injection
    3.It is more than web application development framework
    4.Support for Aspect oriented programming

1. For me most important feature which Spring provides is use of POJOs (Plain Old Java Objects). Working with frameworks like Struts, you need to follow a very strict format, for example for each controller servlet you need to extend action class and override execute method with fixed number of parameters. Even if you are creating simple servlet you need to have get and post methods to handle client requests in a particular format. Spring finally gives you freedom to use plain java classes and convert to controllers or request handlers using simple annotations.

2. Dependency injection is implementation of inversion of control principle which helps maintain loose coupling and move away dependencies from the current class and let it focus on its real goal. Read more on dependency injection-http://kamalmeet.com/2012/03/dependency-injection-simplified/, http://kamalmeet.com/2013/03/more-on-dependency-injection/, http://kamalmeet.com/2013/03/spring-implementation-of-dependency-injection/

3. As I said, Spring is not just for handling request response or implementing MVC like struts, it goes much beyond that. It is kind of a bouquet providing end to end solution for an application like it provides Spring Security for controlling access to application, provides Spring MVC for handling request/ response in MVC mode, provide Workflow to handle control flow, support for webservices through Spring Restful templates etc.

4. Finally support for aspect oriented programming (AOP). Spring supports AOP, that means you can separate some aspects of code so that your classes can focus on the responsibility given to them. For example creating logs is one aspect of a code, which we need to write in every class to make sure proper logs are maintained. Spring helps you pull this aspect out of the code and handle through some configuration making sure logging occurs whenever required.

Maximum Subarray Problem- N log N solution

For algorithm and explanation, read here.

Code implementation


public class MaxSumTest
{
/**
* Main method
* @param s
*/
public static void main(String s[])
{
int[] arr=new int[10];
arr=new int[]{10, -19 , 8 , 4, -5, 2, -1, 3, 8,-9};

int arrlength=arr.length/2;
int[] arr1=createarr(0,arrlength,arr);
int[] arr2=createarr(arrlength, arr.length,arr);
int sum=maxsum(arr1,arr2);
System.out.println(sum);
}

/**
* To find out maximum sum subarray, following divide and conquer technique is used
* 1. Divide the array in 2 equal parts, now there are 3 possibilities.
* a. Max sum subarray crosses the mid of original array, i.e. a part of solution is in left array and other in right. Finding this is simple as we just need to move backword on left subarray to find the maximum sum, and then move fwd on right array to find max, and finally add the two
* b. The other possibility is that max subarray is completely on left array. This means left subarray becomes main array and we discard right array. We will repeat the steps from 1.
* c. The last possibility is that max subarray is completely on right array. This means right subarray becomes main array and we discard left array. We will repeat the steps from 1.
*/
public static int maxsum(int[] arr1, int[] arr2)
{
int sum1=0;
int maxsum1=0;
int sum2=0;
int maxsum2=0;
int maxsum=0;

//1.a. Find maximum sum crossing the the mid of original array.
for(int i=arr1.length-1;i>=0;i–)
{
sum1=sum1+arr1[i];
if(maxsum1y)
if(x>z)
return x;
else
return z;
else
if(y>z)
return y;
else
return z;
}

/**
* Create a subarray from start to end
* @param start
* @param end
* @param arr
* @return
*/
public static int[] createarr(int start, int end, int[] arr)
{
int[] myarr=new int[end-start];
for(int i=start,j=0;i
Finish.

eCommerce: A view from the backend

Apart from features mentioned in my last post, which were directly related to commerce part of business, following are other important parts of an ecommerce system

Content: Your system will need to display items like News on products, Stock prices, policies etc.The content might be product related like images or videos for promotion.

Community: For customer to make an educated guess, it is desirable that he should know what others are talking about product and services. Product reviews, comparisons, chat messages, forums can be helpful for this.

Some other features which are actually invisible to end users, but business needs to take care while setting up ecommerce system

Load Handling: How much concurrent load can your website handle? The ecommerce site needs to be load tested to understand its behavior with increasing load.

Scalability: The website today might be designed to handle 10K users, but in future we might have 100K users. Can our website (technology we used) will scale up to handle increased user base.

Search Engine Optimization (SEO): This is another important aspect of an ecommerce system. Say we have a website selling mobile phones. We would like to make sure that search engines rank our site high whenever a mobile related query like “Android smartphone”, “Nokia phone” etc is searched for.

To support all the features mentioned for ecommerce site, we need to have some services working at backend to fill in manage the data

Content management: How the content is to be managed on user interface. What all items will be displayed and their organization at UI. This means creation and maintenance of pages and templates to be shown on website.

Product management: To add and manage product details.

Catalog management: As mentioned earlier, catalog will create list of products in a categorized manner. There can be different version of catalogs created and maintained by business.

Order management (workflow): An order management process needs to be defined and maintained.

User management: This is for both end user (making purchase) and business user (managing the system). We need to make sure no one gets unauthorized access to the system. For end user we need to make sure if user is active, and maintain user purchase history.

Offers Management: Various offers are provided by business in form of discounts and personalized deals. Business needs to monitor these offers and when an offer is active (season based/ holiday season etc).

In addition to above mentioned components, a true ecommerce system might also have

Suppliers and supply chain management: From where we will get the products? How much inventory is available and how much time will it take to be delivered (or how many tickets are left).

Shipping management: How shipping is handled (mostly outsourced). How products which are returned to company are handled?

Customer Relationship management: How do we make sure customer keeps coming back. You need to maintain the customer purchase history so you can recommend the most suited products. Also returns and complaints needs to handled gracefully to avoid any bad publicity and encourage customer loyalty.

Key components of an eCommerce system

Having an online presence is a must for any business in current world. For a company which is selling products, it will mean creating an ecommerce website, from where customers can purchase products. There can be businesses which are selling totally online (Amazon, ebay) and others which already have offline selling mediums (showrooms), having ecommerce site as an additional way to sell products (Bestbuy).

Depending on the business, and role of ecommerce in it, and complexity of the system will vary. For example, one can have listing of products online but actual selling is through phone, or user can order online which is being manually interpreted by backoffice employees, or a completely automated system. There can be different types of ecommerce systems as well, some selling tangible products like mobile phones, electronics, apparels, other might be selling airline tickets, music for download, a consultant service etc.

As noted, we can have multiple types of ecommerce systems, but some of the key components used by most sites are-

Product Information: Product is the sellable unit in ecommerce system (we can sell services as well, but then they will be considered as product for that particular system). We need to have as much information as possible about product so that it can be shown to customer, who can then make an informed decision on purchase. Information should be provided in industry accepted standards, so that it can be compared easily by customer.

Catalog: A catalog is online version of brochure or menu, which should contain all the products (services) business is providing. The products are further categorized/ sub-categorized into meaningful lists like electronics > kitchen appliances > microwave

Search: This is most used feature of any ecommerce website. Rather then looking for a product in catalogs, customer will prefer searching for it by keywords. A  good search functionality will make sure he gets what he is looking for (or better).

Shopping cart: All the selected products by customer will be shown in shopping cart. This is responsible for applying any offers, taxes, discount etc.

User Details/ Profile management: An ecommerce site might allow a user to shop without login to system. But at times it is desirable to let user create a profile, so that he does not need to enter his details (address, name, phone number etc) everytime he makes a purchase.

Order management: How can customer order for a product or a service? Can he order online, send emails, call up customer care or go to nearby store.

Payment: What are different modes of payment customer can use- Credit card, debit card, net banking, cash on delivery etc. Usually a third party payment gateway can be used to keep focus on business requirements.

Guarantee/ Warranty management: A product might have guarantee or warranty associated, which needs to be honored by the business to make sure customer is coming back to it.

Offers: Businesses need to come up with frequent offers/ discounts/ loyalty programs to boost up sales. Business also uses techniques like cross sell or up sell to increase profit and help customer make good choices.

Privacy Policy: A business might need to collect some information from customer like name, address, age (sometimes more private info) etc. What will happen to info collected from customer (kept private)? Also will cookies be used by the site?

Security: Customer might be sharing sensitive information online, so system needs to use https/ SSL for data collection. Additional requirement will be to secure data already collected by use of authorization and firewalls.