single responsibility principle
Agenda
Context - 5 minutes
Definition - 5 minutes
Examples - 5 minutes
Coding - 30 minutes
Retrospective - 10 minutes
TLA SOUP
Single Responsibility
Open Closed
Liskov Substitution
Interface Segregation
Dependency Inversion
Principles not mandates
Lowers cost of change
Need to balance GTR vs. GTD
Define single responsibility
"A class should only have one reason to change"
KEY WORDS
Cohesion
Rate of change
Reason for change
Law of Demeter - Principle of Least Knowledge
Code-smells / anti-patterns
Fat Controller
God Class
Object Mother
Unit test set up is larger than unit tests
Very high rate of change
Over use of class-inheritance
(Lack of object composition)
Fat controller
public interface IFatController
{
bool IsAuthorised(string userName);
void ExecuteCommand(string command);
string QueryData(string query);
}
fat controller solution
public interface IAuthorisationExpert
{
bool IsAuthorised(string userName);
}
public interface ICommand
{
void Execute();
}
public interface IQuery
{
string QueryData(string query);
}Out of control controller
public class OutOfControlController
{
public string DoStuff(int id, string command, string data)
{
if (Thread.CurrentPrincipal.Identity == null)
throw new UnauthorizedAccessException();
if (!Thread.CurrentPrincipal.IsInRole("Administrator"))
throw new UnauthorizedAccessException();
if (command == "Update")
{
var response = Update(id, data);
Cache(response);
return response;
}
return null;
}
// Connects to database, finds record and updates it's data
protected string Update(int id, string data)
// Stores data in a cache
protected void Cache(string data)
}
OUT OF CONTROL CONTROLLER - solution
public class FocussedController
{
private readonly ISomeRepository _someRepository;
[Authorize("Administator")]
[CachableResponse]
public string Update(int id, string data)
{
var response = _someRepository.Update(id, data);
return response;
}
}
Pairing session - pre-req's
Pairing session - Overview
GameOfLife.Web is a RESTful API.
- POST creates a new civilisation.
- GET gets it's current state.
- PUT applies N evolutions to civilisation.
- Code has examples of requests.
- GET to api/civilisation/0 returns sample.
WEB API crash course
- Fiddler - recording, filters, composer
- Chrome's Advanced REST Client
- Web API
PAIRING SESSION - GOAL
- Apply the SRP to the GenerationController.
- Ensure tests all pass.
- Ensure Post, Get and Put still work.
Extension tasks
- Implement caching on the Get.
- Implement authorisation on all methods.
- Implement Civilisation.Evolve().
References
For more information:
Read Object Mentor's chapter
Visit wikipedia's entry
Read the Black Book (two copies in our library)
Small group katas
Optional training, in the next couple of weeks:
- Work in pairs with a guide.
- Apply SRP to either
Lunar Rover Kata
or any code of your choice
Email Lyndsay by end of 5th Oct. if you're interested