Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does the idea that an object should only do one thing come from?

Tags:

oop

I'm not sure I agree with it, so I'd like to find the book or journal article behind this idea so that I can check that I understand exactly what they're saying and what context they mean it.

I think I understand the idea - I just want to know the source so I can check where the idea comes from.

why I'm asking:

The term "do one thing" is vague and could mean lots of things including "only have one method per class" (ridiculous)... I think it could mean a single responsibility (i.e. lots of methods.) It's also not particularly useful because you have to judge when a single responsibility becomes complicated enough to need refactoring out into several responsibilities with some kind of delegation...

like image 262
Dafydd Rees Avatar asked Nov 09 '09 20:11

Dafydd Rees


People also ask

What is meant by the single responsibility principle?

The Single Responsibility Principle (SRP) is the concept that any single object in object-oriented programing (OOP) should be made for one specific function. SRP is part of SOLID programming principles put forth by Robert Martin. Traditionally, code that is in keeping with SRP has a single function per class.

Why use single responsibility principle?

The argument for the single responsibility principle is relatively simple: it makes your software easier to implement and prevents unexpected side-effects of future changes.

Could you provide an example of the single responsibility principle?

A class should have only one reason to change. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and if in the future we need to make one change we are going to make it in the class which handles it.


1 Answers

SOLID Principles from Bob Martin.

Single Responsibility Principle to be exact.

Although, in the first page of the chapter on the Single Responsibility Principle, he states:

This principle was described in the work of Tom DeMarco and Meilir Page-Jones. They called it cohesion.

The references for the work he mentioned are:

  • Structured Analysis and System Specification, Tom DeMarco, Yourdon Press Computing Series, 1979
  • The Practical Guide to Structured Systems Design, 2d. ed., Meilir Page- Jones, Yourdon Press Computing Series, 1988

Other sources (from S.Lott in comments) include:

  • Wikipedia article on GRASP
  • c2 article on Allocation of Responsibility
like image 191
Grundlefleck Avatar answered Sep 23 '22 19:09

Grundlefleck