Coding styles – efficient code writing

The Single Responsibility Principle 
THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE

Click to access srp.pdf

one class should only have one responsibility. for example, in a server and client example. Client might have functions of make connection and sending messages. it sounds perfect reasonable but it actually has two responsibilities. The drawback of this is 1. eg when two different application use this class. one might only use the connecting function whereas the other one using chatting function. they have to include both codes in when compile. 2 when they change some code for connection method. it might result chatting function in class not working.

The Open-Closed Principle
http://www.objectmentor.com/resources/articles/ocp.pdf

A method should be deigned open to the extension but closed for the modification. The key is using abstraction. For example, you might have a method of drawShapes(ShapeType shapeType). in the method, you have case “SQUARE”, case “RECTANGLE” and so on. To add a CIRCLE in, you will have to edit the method body. Instead, you can have a interface of Shape, using add(Shape shape) to add in additional shapes. then iterate the list and draw the shapes. in this way, the principle is maintained.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s