This word create from five word. each word has own meaning. It is a term describing a collection of design principles for “code stranded” that was coined by "Robert C. Martin". The First 5 Principles of Object Oriented Design.
As per name indicate, A class or module should have one and only one responsibility to perform any functionality. There should never be more than one reason for a class to change. single responsibility will help to achieve High cohesion.
For example: We have created class for Employee which will use only for employee related functionality. If we need Customer Data we should create new Class which will responsible for Customer Details.
class Employee {
private String name;
public String getEmpDetails (){
// details like name etc.
return this.name
}
//getter setter
}
class Customer {
private String name;
public String getCustDetails (){
// details like name etc.
return this.name
}
//getter setter
}
When you are creating a software module (it can be a class or method) should be open for extension but closed for modification means you cannot update the your class code that you have already written for a project, but you can add new class to the project. you can apply this principle either through inheritance or through composition. Open-close principle use inheritance.
Example : framework like struts or spring, we will see that we can not change their core logic and request processing, but we modify the desired application flow just by extending some classes and plugin them in configuration files.
Extending Struts Action
public class OpenCloseAction extends Action
{
@Override
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
//add your logic
}
}
In this principle, Derived classes must be substitute for their base classes. Abstraction (interface or abstract class) should be enough for a client.
Public Interface Car{
void start();
void stop();
}
In this principle, Clients should not be forced to depend upon the interfaces that they do not use.
Example : MouseMotionListenerImpl : We only need to write handlers for events, we wish to handle. Nothing is mandatory.
public class MouseMotionListenerImpl implements MouseMotionListener
{
@Override
public void mouseDragged(MouseEvent e) {
//handler code
}
@Override
public void mouseMoved(MouseEvent e) {
//handler code
}
}
In this principle, Program to an interface, not to an implementation.
Example : Spring framework provide DI principle in bean configuration
.