Sunday, June 3, 2012

20 Design pattern and Software design interview questions for Programmers

Design patterns and software design questions are essential part of any programming interview, no matter whether you are going for Java interview or C#  interview. In face programming and design skill complement each other quite well, people who are good programmer are often a good designer as well as they know how to break a problem in to piece of code or software design but these skill just doesn’t come. You need to keep designing, programming both small scale and large scale systems and keep learning from mistakes.Learning about Object oriented design principles is a good starting point. Anyway this article is about some design questions which has been repeatedly asked in various interviews. I have divided them on two category for beginners and intermediate for sake of clarity and difficulty level.

Design pattern interview questions for Senior and experienced level

design pattern and software design question asked in interviewThese are questions which not only relates to design patterns but also related to software design. These questions requires some amount of thinking and experience to answer. In most of the cases interviewer is not looking for absolute answers but looking for your approach, how do you think about a problem, do you able to think through, do you able to bring out things which are not told to you. This is where experience come in picture, What are things you consider while solving a problem etc. overall these design questions kicks off your thought process. Some time interviewer ask you to write code as well so be prepare for that. you can excel in these questions if you know the concept, example and application of your programming and design skill.

1. Give an example where you prefer abstract class over interface ?
This is common but yet tricky design interview question. both interface and abstract class follow "writing code for interface than implementation" design principle which adds flexibility in code, quite important to tackle with changing requirement. here are some pointers which help you to answer this question:

1. In Java you can only extend one class but implement multiple interface. So if you extend a class you lost your chance of extending another class.

2. Interface are used to represent adjective or behavior e.g. Runnable, Clonable, Serializable etc, so if you use an abstract class to represent behavior your class can not be Runnable and Clonable at same time because you can not extend two class in Java but if you use interface your class can have multiple behavior at same time.

3. On time critical application prefer abstract class is slightly faster than interface.

4. If there is a genuine common behavior across the inheritance hierarchy which can be coded better at one place than abstract class is preferred choice. Some time interface and abstract class can work together also where defining function in interface and default functionality on abstract class.

To learn more about interface in Java check my post 10 things to know about Java interfaces

2. Design a Vending Machine which can accept different coins, deliver different products?
This is an open design question which you can use as exercise, try producing design document, code and Junit test rather just solving the problem and check how much time it take you to come to solution and produce require artifacts, Ideally this question should be solve in 3 hours, at least a working version.

3. You have a Smartphone class and will have derived classes like IPhone, AndroidPhone,WindowsMobilePhone
can be even phone names with brand, how would you design this system of Classes.
This is another design pattern exercise where you need to apply your object oriented design skill to come with a design which is flexible enough to support future products and stable enough to support changes in existing model.

4. When do you overload a method in Java and when do you override it ?
Rather a simple question for experienced designer in Java. if you see different implementation of a class has different way of doing certain thing than overriding is the way to go while overloading is doing same thing but with different input. method signature varies in case of overloading but not in case of overriding in java.

5. Design ATM Machine ?
We all use ATM (Automated Teller Machine) , Just think how will you design an ATM ? for designing financial system one must requirement is that they should work as expected in all situation. so no matter whether its power outage ATM should maintain correct state (transactions), think about locking, transaction, error condition, boundary condition etc. even if you not able to come up exact design but if you be able to point out non functional requirement, raise some question , think about boundary condition will be good progress.


6. You are writing classes to provide Market Data and you know that you can switch to different vendors overtime like Reuters, wombat and may be even to direct exchange feed , how do you design your Market Data system.
This is very interesting design interview question and actually asked in one of big investment bank and rather common scenario if you have been writing code in Java. Key point is you will have a MarketData interface which will have methods required by client e.g. getBid(), getPrice(), getLevel() etc and MarketData should be composed with a MarketDataProvider by using dependency injection. So when you change your MarketData provider Client won't get affected because they access method form MarketData interface or class.

7. Why is access to non-static variables not allowed from static methods in Java
You can not access non-static data from static context in Java simply because non-static variables are associated with a particular instance of object while Static is not associated with any instance. You can also see my post why non static variable are not accessible in static context for more detailed discussion.

8. Design a Concurrent Rule pipeline in Java?
Concurrent programming or concurrent design is very hot now days to leverage power of ever increasing cores in
advanced processor and Java being a multi-threaded language has benefit over others. Do design a concurrent system key point to note is thread-safety, immutability, local variables and avoid using static or instance variables. you just to think that one class can be executed by multiple thread a same time, So best approach is that every thread work on its own data, doesn't interfere on other data and have minimal synchronization preferred at start of pipeline. This question can lead from initial discussion to full coding of classes and interface but if you remember key points and issues around concurrency e.g. race condition, deadlock, memory interference, atomicity, ThreadLocal variables  etc you can get around it.

Design pattern interview questions for Beginners

These software design and design pattern questions are mostly asked at beginners level and just informative purpose that how much candidate is familiar with design patterns like does he know what is a design pattern or what does a particular design pattern do ? These questions can easily be answered by memorizing the concept but still has value in terms of information and knowledge.

1. What is design patterns ? Have you used any design pattern in your code ?
Design patterns are tried and tested way to solve particular design issues by various programmers in the world. Design patterns are extension of code reuse.

2. Can you name few design patterns used in standard JDK library?
Decorator design pattern which is used in various Java IO classes, Singleton pattern which is used in Runtime , Calendar and various other classes, Factory pattern which is used along with various Immutable classes likes Boolean e.g. Boolean.valueOf and Observer pattern which is used in Swing and many event listener frameworks.

3. What is Singleton design pattern in Java ? write code for thread-safe singleton in Java
Singleton pattern focus on sharing of expensive object in whole system. Only one instance of a particular class is maintained in whole application which is shared by all modules. Java.lang.Runtime is a classical example of Singleton design pattern. You can also see my post 10 questions on Singleton pattern in Java for more questions and discussion. From Java 5 onwards you can use enum to thread-safe singleton.

4. What is main benefit of using factory pattern ? Where do you use it?
Factory pattern’s main benefit is increased level of encapsulation while creating objects. If you use Factory to create object you can later replace original implementation of Products or classes with more advanced and high performance implementation without any change on client layer. See my post on Factory pattern for more detailed explanation and benefits.

5. What is observer design pattern in Java
Observer design pattern is based on communicating changes in state of object to observers so that they can take there action. Simple example is a weather system where change in weather must be reflected in Views to show to public. Here weather object is Subject while different views are Observers. Look on this article for complete example of Observer pattern in Java.


6. Give example of decorator design pattern in Java ? Does it operate on object level or class level ?
Decorator pattern enhances capability of individual object. Java IO uses decorator pattern extensively and classical example is Buffered classes like BufferedReader and BufferedWriter which enhances Reader and Writer objects to perform Buffer level reading and writing for improved performance. Read more on Decorator design pattern and Java

7. What is MVC design pattern ? Give one example of MVC design pattern ?
8. What is FrontController design pattern in Java ? Give an example of front controller pattern ?
9. What is Chain of Responsibility design pattern ?
10.What is Adapter design pattern ? Give examples of adapter design pattern in Java?
 These are left for your exercise, try finding out answers of these design pattern questions as part of your preparation.

These were some of the design pattern questions I have seen in most of interviews, there are many more specially in software design which is important in google interviews and various other companies like Amazon, Microsoft etc. Please share if you have faced any interesting design questions which is worth sharing.

23 comments :

trgoofi said...

Hi
Can you explain how "abstract class is slightly faster than interface" ?
thx.

Javin @ Sort List in java said...

Hi trgoofi, I have also read this somewhere, but I logic is that abstract class can still participate in static binding by declaring static method but since interface can not have any method implementation all binding will be dynamic.I am still looking for more convincing and detailed reason and let you know if I found it, if you have more convincing logic, please let us know.

Mike said...

design pattern questions are more popular on J2EE interviews rather than in core Java interviews. Though decorator, Singleton, Factory are both applicable to Java and J2EE. J2EE specific patterns like MVC, ViewResolver patter, Front Controller patter, Service Locator are missing from your list of design pattern question. Question like How will you ensure Scalability, high avaibility should be asked on software design part as well.

Anand VijayaKumar said...

Javin & trgoofi

Actually speaking these days, the difference in performance between an Abstract class and an Interface could be negligible or non-existent. In the olden days this could've been true for the following reason:

A Class can extend from only one parent class while it can implement multiple interface. Since at runtime the JVM may have to scan through multiple interfaces to find a method while it needs to scan only one class, an abstract class could have given a marginally better performance when compared to an interface.

However, these days, the fire-power that computers have (in terms of processing) is many times higher than what it was just even a couple of years ago + JVMs have been optimized over generations.

So, I would say this abstract class, Interface thingi is non-existent or inconsequential now :)

If you feel otherwise please feel free to let me know..

Thanks
Anand

Anand VijayaKumar said...

You have a very good collection of questions on design patterns Javin. I too have an article on interview questions on design patterns.

Click Here to see it.

Pls, share your thoughts on the questions.

Anand

Java programmer said...

One of the best list of java design interview questions and answers I found around web, Thanks for sharing this great list of Java design pattern interview questions and answers. I have 6 years experience in Java and found that many design pattern questions actually appeared in Senior Java interview. Once again thanks a lot.

Prabhat said...

Can anyone please share Java design pattern questions asked on Capegemini and Infosys interviews ?

satya said...
This comment has been removed by the author.
satya said...

One thing i want to high light here do you think this questions are from design pattern or Design consideration ????? I think design pattern is bit different?

Praveen Kumar Basavaraj said...

Questions are good. But answers are very short. Detailed explanation would help a lot. Thanks

Anonymous said...

@Javin - Can you please share some detailed answers or design for ATM machine example or Market data example?

Anonymous said...

Hi Javin,

Great job as always.
keep doing and helping people to clear there doubts and crack java interviews..

God Bless You !!!!!!

Best Regards,
Rajesh

Ramakrishna Allam said...

How do we ensure an application is 100% available? can someone answer this please?

Anonymous said...

Does Design patterns help in memory management?
Can someone explain on this?

Anonymous said...

Regarding Answer 6, related to design of Market data provider, I think there are couple of more approaches.

1) Let different implementation comes with different JAR file e.g. Reuters implementation comes with Reuters JAR, Bloomberg comes with bloomberg.jar and Wombat comes with there own JAR.

2) Make them to implement MarketData interface as MarketDataImpl. Since all JAR will be using same class name, using different JAR with different provider make things simple, you don't need any runtime configuration, because the class which will be available in Classpath will be instantiated.

3) Make sure to include correct jar during build time.

RAJAT said...

Regarding, whether abstract class is faster than interface, that's true, because of different byte code generated, when calling a method using abstract class or interface. When you access a method using interface type, it involves scanning to multiple implementation.

Anonymous said...

One of the popular question I have seen on Object Oriented Analysis and Design is designing and implementing Elevator (Lift) system for multi-story buildings, with lot of variants e.g. ground floor + car park, multiple lifts, improving algorithm so that lift can reach quickly on request etc. It would be great, if anyone can elaborate how to deal with such Object oriented design questions in limited time during interviews.

Rats said...

which design pattern is application to implement elevator or hw can we implement elevator class.

Karthik PPS said...

Javin, interesting to read each and every page of yours. Nicely written!

Koi nahi said...

Calender is not implementing singleton, but factory.
Nice article (like all other article on this blog)!

Anonymous said...

Can you explain how "abstract class is slightly faster than interface" ?

Abstract classes are slightly faster than Interfaces because the class compilation and loading happens immediately with Abstract Classes whereas for the Interfaces (specially marker interface) the class loader has to go through the libraries to find the package and then the interface class associated with the call

Kabir said...

Some more questions for Java developers who are preparing design pattern hard :

1) What is difference between Factory and Abstract Factory design patttern?
2) What is difference between State and Strategy Pattern?
3) Differnece between Proxy and Decorator design Pattern?
4) Why Composition is better than Inheritance? Give two reasons
5) Difference between aggregation, assoication and composition in OOP?
6) Difference between Template and Strategy design pattern?
7) Why Singleton pattern is bad? Give atleast two reasons
8) When do you use Command Pattern?
9) When should you use Prototype Design Pattern?
10) Why use Visitor design Pattern? What is the advantage of using Visitor?
11) Difference between Creational and Behavioral Design patterns?
12) Can you write code for double checked locking in Java?

Sorry, but I don't know the answer and I have posted it here so that someone can answer these question :-)

Anonymous said...

Design pattern and software design are two completely different thing, how can interviewer mix design pattern and software design ? designing software require experience in terms of scalability, stability, performance and lot more rather than just using MVC design pattern in Spring or Struts.

Post a Comment