The Single Responsibility Principle

Preview:

DESCRIPTION

The Single Responsibility Principle (SRP) is one of the 5 SOLID principles. These slides gives you an overview of the principle as well as a refactoring from a non-SRP code to a SRP-code.

Citation preview

The Single Responsibility Principle

Lars-Erik KindbladSenior Consultant

Blog: kindblad.com

Agenda

What is the Single Responsibility Principle?Code SampleSummary

Single Responsibility Principle

Single Responsibility Principle = SRP1 of the 5 SOLID principles for creating better object-oriented code

The Single Responsibility Principle The Open Closed Principle The Liskov Substitution Principle The Interface Segregation Principle The Dependency Inversion Principle

SRP states that ”a class or module should have one, and only one, reason to change” A class should do one thing A class should have only one responsibility

The benefit: smaller classes that are easier to read, maintain and unit-test

The God Object

A God object is an object that knows too much or does too muchThe opposite of the SRP

CODE SAMPLE

Database code

Send mail code

1. Extract mail sending code

2. Extract database code

Repositories are potential God-objects

3. Replace Repository.GetUser with a DbCommand

4. Replace Repository.AddUser with a DbCommand

5. Replace Repository.DeleteUser with a DbCommand

UserManager looks like a facade class

... Extract

6. Extract RegisterUser

7. Rename UserManager

... to UserFacade

Not every dependency are needed at all times

8. Change to a Service Locator

9. Validation

Could be extracted but not needed now since the class

is small...

Overview

AddUserDbCommand

DeleteUserDbCommand

GetUserDbCommand

SendEmailConfirmationRegisterUser

UserFacade

Remove?

Summary

A class following the single responsibility principle is a class that does only one thing and has only one reason to change

The opposite of SRP is a God-objectBenefits

Easy to give the class a good name Less code per class means reduced complexity, less errors, easier to maintain, extend

and test

Arguments against Too many classes Difficult to understand the big picture

The pros outweights the cons – SRP is a requirement forwriting maintainable unit-tests

QUESTIONS?

The information contained in this presentation is proprietary.© 2012 Capgemini. All rights reserved.

www.capgemini.com

About Capgemini

With more than 120,000 people in 40 countries, Capgemini is one of the world's foremost providers of consulting, technology and outsourcing services. The Group reported 2011 global revenues of EUR 9.7 billion.Together with its clients, Capgemini creates and delivers business and technology solutions that fit their needs and drive the results they want. A deeply multicultural organization, Capgemini has developed its own way of working, the Collaborative Business ExperienceTM, and draws on Rightshore ®, its worldwide delivery model.

Rightshore® is a trademark belonging to Capgemini

Recommended