Single Responsibility Principle: SOLID design Principles

Share the Article

What is Single Responsibility Principle

Single Responsibility principle is one of the basic principle for object oriented class designing. It is also contributing first “S” in SOLID acronym where S stands for Single Responsibility Principle. This principle tries to give future modifiability and maintainability to an application.

As it clear from the name, ” Single Responsibility” insists us to design a class to handle only single task. In other words, we should not create classes, such that they are doing multiple tasks or jobs. If our classes are handling multiple tasks then in future maintenance of such application will be very difficult. This is because updates done in one place of class will impact several places and leads to code pollution.

Basically, we should have only one reason or need for updating our class not multiple.

Why

Lets us try to understand the need of Single Responsiblity Principle by taking an example of an application performing below jobs:

  1. Selecting Computer components
  2. Assembly of components manually
  3. Dispatching assembled computer through Trains

Example not using Single Responsibility Principle

Lets us try to design above application without “Single Responsibility Principle” first.

Design a class Computer performing all 3 jobs:

class Computer { string m_cpu; string m_screen; string m_keyborad; public: void selectComponent(string cpu, string screen, string keyboard) { } void assembleComputer() { cout<< " Assemble component manually"<<endl; } void dispatchComputer() { cout<<"Computer Dispatch by Train"<<endl; } };

As seen above, we have designed a class Computer which is handling multiple tasks, such as, selecting components, assembling them and finally dispatching computer.

Below is the full application:

#include<iostream> //main header for io using namespace std; //for namespace class Computer { string m_cpu; string m_screen; string m_keyboard; public: void selectComponent(string cpu, string screen, string keyboard) { } void assembleComputer() { cout<< " Assemble component manually"<<endl; } void dispatchComputer() { cout<< " Computer Dispatch by Train"<<endl; } }; int main() //Client-code { Computer c1; c1.selectComponent("single core","Normal Screen","Keyboard"); c1.assembleComputer(); c1.dispatchComputer(); return 0; }

Suppose, now we have future requirement to update above application with below needs:

  • Add more components such as Speaker, Touch screen, Bluetooth headset
  • Assembly should happen in electrical mode also (not only manual)
  • Dispatch should support – Truck , Aeroplan, also

As seen above, only one class Computer is doing all jobs. Therefore, we need to update Computer class for all above cases. Whoever, maintaining Computer class needs to keep modifying it. Due to this our application is not easily adapting for future needs.

In order to write application which we can very easily adapt for future needs, the “Single Responsibility Principle” is the best suit.

How

Lets us try to design same application using “Single Responsibility Principle”.

Thumb rule – Give only one responsibility to one class and should have only one reason for getting updated.

Lets us try to update above application with above rule. Since above application is doing 3 jobs, such as, selecting components, assembling components and dispatching computer. Therefore, now we shall break down this and create one class for each responsibility as below:

First Job – Selecting Components

Firstly, design class Computer which handles only one job, i.e., selecting components:

class Computer { string m_cpu; string m_screen; string m_keyboard; public: void getComponent( ) { } };

Second Job – Assemble Computer

Secondly, design class AssemblyComputer which is also handling single job of assembly of components.

class AssemblyComputer { public: void assemblyComponent() { cout<< " Assemble component manually"<<endl; } };

Third Job – Dispatch computer

Finally, design class DispatchComputer to handle job of dispatching of computer.

class DispatchComputer { public: void dispatch() { cout<< " Computer Dispatch by Train"<<endl; }; };

Complete Example using Single Responsibility Principle

#include<iostream> //main header for io using namespace std;//for namespace class Computer { string m_cpu; string m_screen; string m_keyboard; public: Computer(string cpu,string screen,string keyboard){}; void getComponent() { } }; class AssemblyComputer { Computer *m_computer; public: AssemblyComputer(Computer *c1) { m_computer=c1; } void assemblyComponent( ) { m_computer->getComponent(); cout<< " Assemble component manually"<<endl; } }; class DispatchComputer { AssemblyComputer *m_assembledComputer; public: DispatchComputer(AssemblyComputer *a1) { m_assembledComputer = a1; } void dispatch() { m_assembledComputer->assemblyComponent(); cout<< " Computer Dispatch by Train"<<endl; } }; int main() { Computer c1("Single Core","Screen", "Keyboard" ); AssemblyComputer a1(&c1); DispatchComputer d1(&a1); d1.dispatch(); return 0; }

As seen above, now in our application each class is doing only single job. Therefore, future extensions are very easy to design. For instance, If there is an update in assembly part, then, other parts, like, dispatchComputer shall not get impacted.

Adding new requirements in same example

Lets us try to update above application by supporting different dispatch mode, i.e., through truck and aero plane (in addition to train)

#include<iostream> //main header for io using namespace std; //for namespace class Computer { string m_cpu; string m_screen; string m_keyboard; public: Computer(string cpu, string screen, string keyboard) { }; void getComponent() { } }; class AssemblyComputer { Computer *m_computer; public: AssemblyComputer(Computer *c1) { m_computer=c1; } void assemblyComponent( ) { m_computer->getComponent(); cout<< " Assemble component manually"<<endl; } }; class DispatchComputer { AssembleyComputer *m_assembledComputer; public: DispatchComputer(AssembleyComputer *a1) { m_assembledComputer =a1; } void dispatch(string dispatchmode) { m_assembledComputer->assembleyComponent(); cout<< " Computer Dispatch by "<<dispatchmode<<endl; } }; int main() //Client-Code { Computer c1("Single Core","Screen", "Keyboard" ); AssembleyComputer a1(&c1); DispatchComputer d1(&a1); d1.dispatch("Aeroplane"); return 0; }

As seen above, now we have updated dispatchComputer class. Here, the function dispatch(string dispatchmode) shall accept a string argument. Hence, with this minimal change in one class, new requirement is easily supported in above application.

Pros & Cons of Single Responsibility Principle

Pros

  • Firstly, it introduces loose coupling between classes, therefore, future adaptation is very easy.
  • Secondly, the code becomes very easy to understand and maintain. Clean code.
  • Finally, it becomes very easy to write unit test cases.

Cons

  • This needs very careful design approach, otherwise it may lead to too many classes. In worst case, every function may become one class.

Main Funda: Single Responsibility Principle promotes modularization of design.

Advanced C++ Topics

Singleton Design Pattern
Factory Method Design Pattern
Builder Design Pattern
How std::forward( ) works?
How std::move() function works?
What is reference collapsing?


Share the Article

21,353 thoughts on “Single Responsibility Principle: SOLID design Principles

  1. © COPYRIGHT 2022 Pierwsze wrażenie, które sprawia podręcznik, jest niezwykle pozytywne. Pełno w nim ilustracji utrzymanych w takim samym stylu – co niezwykle rzadkie w RPG-ach. Layout także prezentuje się ciekawie – jego największą zaletą są spore marginesy, na których spisano statystyki BN-ów, podlinkowano odpowiednie strony (np. z daną zasadą czy potworem z wbudowanego bestiariusza), bądź po prostu rozwinięto myśli zasygnalizowane w głównej części tekstu. Syberyjska ruletka można obejrzeć w programie stacji: Uwaga! Informacje na temat poprzednich emisji znajdują się niżej na stronie. Jednakże w niektórych gminach, pozdrawiam z Krakowa, dominują własne systemy sprzedaży biletów, które rodzą wiele kuriozalnych sytuacji. Dla przykładu, w tym samym środku transportu, ale innej linii, możemy spotkać się albo z biletomatem obsługującym wyłącznie płatność monetami, albo w drugim natomiast – tylko kartą. Ok, jest tam też blik, ale w tradycyjnym wydaniu z koniecznością wpisywania kodu. https://printforum.com.au/community/profile/felipaburney171/ Stupromilowy las – to rozbudowana wersja Alkochińczyka. Do niej również potrzebna jest specjalna plansza. W przeciwieństwie do poprzedniej gry, jest ona przeznaczona dla maksymalnie 5 osób. Możesz wcielić się w jedną z 12 postaci i przesuwać się nimi po planszy (lesie) oczywiście, jak to w każdej grze alkoholowej wykonując zadania (nie tylko polegające na piciu) Ruletka amerykańska ma takie same zasady jak ruletka europejska, ale z tą różnicą, że zobaczymy tutaj dodatkową liczbę, a mianowicie podwójne zero (00). Czy system rzeczywiście działa? Czy system rzeczywiście działa? 10 22 Zapewne na niejednej imprezie spotkałeś się z hasłem „Piją Ci co mają dzisiaj spodnie”. Tego typu zabawy dały początek grom alkoholowym, które coraz częściej stają się podstawą każdej, dobrej imprezy. Dzisiaj przedstawimy Wam trzy, najbardziej popularne gry, wypróbowane na naszej własnej skórze.

  2. Die Online Casino Werbung soll natürlich neue Spieler auf das Spieleangebot aufmerksam machen und in die Casinos locken. Für viele potentielle Kunden bietet sie aber auch die Möglichkeit, mittels eines Bonuscodes ein kostenloses Extraguthaben für den Spieleinstieg zu erhalten. Viva Slots Vegas: Casino-Slots Lädt zum Bewerten ein Zu dieser Website Dein Online Casino! JETZT KOSTENLOS DONWLOADEN – Huge Jackpots & Slots Werde Teil der High Society an einem der bunten Casinotische. Mit dem Unterschied, dass du diese Erfahrung bei RTLspiele gratis und ohne Risiko sammeln kannst. Erlebe die verschiedensten Jackpot Games in coolen, verschiedenen Designs. Begebe dich in den Dschungel, wandere durch die Wüste der Pharaonen und lass dich von einer Welt aus 1001 Nacht verzaubern. Auch mit dem beliebten Moorhuhn kannst du dich bei den Jackpot Games auseinandersetzen. In den typischen Spielen am „Einarmigen Banditen“ kannst du um virtuelle Chips spielen und deine Geschicklichkeit testen. http://roulettekinderspiel280.theburnward.com/probieren-sie-diese-aus Sobald das Guthaben auf dem Account gutgeschrieben wurde, kann man sich auch an die Slots rund um Triple Chance, Magic Mirror oder an den Merkur Hit Eye of Horus setzen und die Walzen zum Glühen bringen. Vor allem die Spiele der Merkur Reihe gehören zu den beliebtesten Games in Online Casinos. Und genau diese findet man nicht nur bei Sunmaker, sondern auch bei Sunnyplayer vor. Wie zu Sunmaker gibt es auch einen ausführlichen Sunnyplayer Test, der sehr lesenswert ist! Immerhin kannst du dir bis zu 150€ extra Wettguthaben sichern, was Ihr zu tun habt. Schutz der Information Es gibt sichere Netzwerke und Industriestandard-Verschlüsselungs-Technologien, online roulette spiele im casino um den No Deposit Casino Bonus nutzen zu können. Weißt Du, ist. Mit dem Google-Übersetzer konnten wir alles übersetzen, ein Spielerkonto im Spin247 anzulegen. Und wenn nicht, die offiziell mit Glücksspielunternehmen als Werbepartner bzw. Während der Freispiele werden Sie zwei kleinere Sätze von Rollen sehen, sodass das Fehlen einer telefonischen Hotline zumindest teilweise ausgeglichen werden konnte.

  3. Erkeklere erkekliğini dibine kadar hissettiren orgazm olmak ne demek adeta ders veren ateşli sohbet kızları ile alo telekız boşalma hattında her saniyesini zevkle yaşayacağınız anlara merhaba deyin 😉İlgini çekebilir: Telefonda ucuz sex hattı Dul Sohbet HattıTelekızlar sizinle telefonda standart bir kızın yapabileceklerinden çok daha fazla şeyi yapıp sizi telefonu kapatana kadar tatmin eden hatunlardır Telefonda Güzel Arkadaşlıklar Arıyorum https://notepin.co/shared/fhzhdto chat yapın.

  4. Fly agaric mushrooms contain the psychoactive chemicals ibotenic acid and muscimol, which are known to cause twitching, drooling, sweating, dizziness, vomiting, and delirium. Fly agaric mushrooms are not the same thing as psilocybin-containing mushrooms. “It would seem more bizarre for the police to start cracking down on a guy selling mushrooms and LSD, while at the same time, decriminalizing possession of all drugs,” he said. Just like cannabis, the psychedelics movement faces deep divisions over decriminalization, regulation and social justice. With fears over big marijuana firms dominating the debate, lawmakers and advocates are trying to address similar issues in the psychedelics space. Psilocybin, a potent psychedelic, is illegal. But the government appeared satisfied by a wealth of scientific study and anecdotal experience backing the efficacy of the compound derived from so-called “magic mushrooms” to ease mental suffering and dramatically diminish the ruthless anguish that can hound someone facing death. https://keeganfbpf219864.pointblog.net/magic-mushrooms-shelf-life-51505335 “Mushrooms have been used in traditional medicine for literally thousands of years, and, hence, they are just that much closer to these ancient traditions,” said ethnopharmacologist Dennis McKenna. Why Do Magic Mushrooms Stain or Bruise Blue?In Psilocybin Mushrooms of the World, Stamets notes that blue-staining, or “bluing”, in magic mushrooms is not well understood. However, the process is thought to parallel the degradation of psilocyn – the primary active chemical in most magic mushrooms. Therefore, bluing should be avoided (through careful handling) because it probably reduces a mushroom’s potency. My mistake; I did a bit more research and it turns out liberty caps aren’t limited to cow fields, and don’t grow in dung necessarily. I was repeating info I learned as a teenager, and to be fair I DID find liberty caps in a cow field (and yes, I ate them and got high af). Check out this guide to psychoactive mushrooms of Vancouver island.

  5. Casinos offer free spins so that you can try their games without spending a dime. One complimentary spin equals one spin on a slot. Some promotions are run on specific titles, while others are for any of the provider’s games. The free spins are often connected to a bonus or a specific game. Free spin bonuses let you play real money slots online for free. Every free spin refers to a single turn at a specific slot. If you win, you get to keep the money — subject to any additional conditions, which we’ll come to later. If you lose, your free spin is gone. You don’t have to wager cash to play pokies online and possibly win. The best way to begin your gambling journey is using a no deposit free spins bonus. When you decide to become a part of a virtual casino, you’ll get access to this reward and promotional game. You get a chance to play certain excellent games or one specific title, such as pokies using free spins bonus codes. https://lukaskbrw976421.idblogz.com/15814906/bitcoin-dice-house-edge The number of no deposit free spins of course varies by casino, and some casinos are more generous then others. Remember, sometimes it is not the number of free spins you receive that’s important – it’s their value. Ten free spins worth $0.10 each are more valuable than 50 free spins worth $0.01 each. Always check any offer in full before you sign up for the site offering you the deal. New free spins offers may come with no wagering requirements imposed. This is the best deal you can find as you won’t be required to risk your money to keep your winnings from free spins and cash them out. Even if you need to make a deposit to lay your hands on wager-free free spins, they are worth it. Your winnings from them will be added to your real-money balance automatically. Week-end dГ©couvertes

  6. Now that you know what to look for in slot machines, here is how to find the best online pokies real money. The first thing to do when choosing a game is to try the free version. With the free version, you can find out if the game is worth playing. Also, it would help if you tried online real money pokies with no deposit bonuses, as they allow you to play and win real money without having to deposit in your first few spins. Online slots for real money are popular in the United States gaming market. Spinning the reels makes up about 70% of all wagers. Below you will find the best real money slot online casinos for US players. Our experts have revealed their ultimate list of the best online casinos in the world for real money gaming after conducting a rigorous review process. The team assessed more than 100 licensed online casinos before finally whittling it down to this small group of elite casino sites. http://netentnodepositspins466.huicopper.com/online-slots-free-bonus-no-deposit-required Bitcoin is becoming increasingly popular, both in the poker world and in the rest of the market. We can increasingly find machines that allow us to extract bitcoins and businesses that accept this currency as a method of payment. Since China joined the list of countries that support bitcoin transactions, its value has increased exponentially. The speculation that exists around this cryptocurrency is one of the main advantages that we can find in bitcoin, and is that this currency has a great potential that makes its value increase over time, which means a significant return on investment (ROI) for poker players. The term Bitcoin Poker refers to online poker sites, where Bitcoin is used as currency or where you are playing online poker for real money using Bitcoin. We’re not going to get down to the nitty-gritty of all the technicalities involved with Bitcoin, because it may be a bit overwhelming. And honestly, you don’t need to worry yourself with learning all the terminology in order to use Bitcoin for playing online poker. So, we’ll show you straight away how to deposit and withdraw Bitcoin on poker sites.

  7. If some one desires to be updated with latest technologies after that he must be
    pay a quick visit this website andd be up to ddate everyday.

    Feel free to surf tto my web site … repair your own car – Sterling,

  8. With havin so much content do you ever run into any issues of plagorism or
    copyright violation? My site has a llot of completely unique content I’ve either written myself or outsourced but it seems
    a lot oof it is popping it up all over the internet without myy authorization. Do you knnow
    any methods to help reduce content from being ripped off?
    I’d truly appreciare it.

    Also visit my web page electrical troubles
    att home – Lacey,

  9. Incredible! This blog looks juset like my old one!
    It’s on a entirelyy different subject but
    it has pretty much the same page layout and design. Superb choice
    of colors!

    Feel free to visit my blog post; car rspair – Russel,

  10. My brother recommended I might like this web site. He waas totally right.
    This post truly made my day. You cann’t imagine just
    how much time I had spent for this info! Thanks!

    My web-site :: truck repair manuals (Edgar)

  11. First of all I want to say terrific blog! I had a quick question that I’d like
    to ask if you do not mind. I was interested to know how you center
    yurself annd clear your thoughts before writing. I’ve had
    a difficult time clearing my mind in getting my idezs out there.
    I do ttake pleasure in writing but it just seems like the first 10 to 15 minutes tend to be wasted just
    trying to figure out how to begin. Any ideas or hints?
    Appreciate it!

    Here is my web-site – 2006 nissan altima engine wiring harness, coppertalk.org,

  12. Slotomania mit Freunden spielen? Wenn Sie bei einem Anbieter kostenlose Glücksspiele spielen möchten ohne Anmeldung und ohne Download, halten Sie einfach nach dem Bereich mit dem Testmodus, Demospielen oder ähnlichen Bereichen Ausschau. Noch einfacher ist es aber einen Casino Slot gratis von unserer Liste auszuprobieren und die Automatenspiele kostenlos ganz bequem in Ihrem Wunschbrowser zu spielen. Kostenlose Casino Spiele sind sowohl für neue Spieler als auch für erfahrene Spieler gleichermaßen geeignet. Egal, ob Sie neue Spiele und Anbieter kennenlernen oder alte Spiele einmal gratis zum Spaß erleben möchten, das kostenlose Spiel ist die perfekte Möglichkeit. Probieren Sie hier auf unserer Website und bei den von uns empfohlenen Casinos eine Vielzahl toller Gratis Spiele aus. Lassen Sie den Geldbeutel heute zu und spielen Sie kostenlos! https://electrodaze.com/profile/aidensamuel7055/ Die Gäste des Casino Velden erwartet am 31. Dezember ein Feuerwerk aus Spiel, bester Unterhaltung und kulinarischem Verwöhnprogramm sowie die Chance auf zahlreiche Casino Gutscheine in der Glücksdusche. Überrasche deinen Herzenspartner mit Dinner & Casino Night Gutscheinen und schenke ein luxuriöses Erlebnis mit Candle Light Atmosphäre, das garantiert in Erinnerung bleibt. 23:00 TRANSFER vom Schloss Loretto per Schiff oder stylischem Auto Eisner Shuttle (nur auf Anfrage) zur “Glamour in White Party” im CASINO VELDEN (Eintritt inkludiert) Beim Dinner Deal von 1. September bis 30. November 2018 können Gäste zu besonders attraktiven Konditionen Spiel und Genuss kombinieren. Beim Dinner Deal erhält der Gast ein zweigängiges Menü im Cuisino Restaurant DIE YACHT und bekommt zusätzlich Begrüßungsjetons im Wert von 10 Euro für das Spielvergnügen.

  13. With havin so much written content do you ever run into
    any problems of plagoorism or copyright violation? My website has a
    lot of unique content I’ve either written myself or outsourced but it seems a lot oof it is popping
    it up all over the internet without my permission. Do you know any solutions to helpp prevent content from being stolen? I’d really appreciate it.

    Take a look at my homepage home electrical repair (Kristopher)

  14. This is the right website for everyone whoo would
    like to understand this topic. Youu realize a whole lot its almost hzrd
    too argue with yoou (not that I pesonally will need to?HaHa).
    Yoou definitely put a brand new spin on a subject that has been written about for a
    long time. Excellent stuff, just excellent!

    Here is my site home improvement (Isabell)

  15. My brother recommended I might like this wweb site.
    He was totally right. This post actually made my day. You cann’t imazgine just how much time I had spent for this information! Thanks!

    Also visit my webpage :: car alarm install [Amber]

  16. Thank you for the good writeup. It actually was a amusement
    account it. Look advanced to more added agreeable ftom you!
    By the way, how could we communicate?

    Here is my website elctrical troubles at home (Miquel)

  17. Howdy! This post could not be written any better!

    Reading through this post reminds me of my previous room mate!
    He alwqys kept talking about this. I will forward this post tto him.
    Pretty sure he will have a good read. Thank you for sharing!

    my site :: car fix; Francine,

  18. You completed various good points there.
    I did a search on thhe issue and found a good number of
    people will go along with with your blog.

    Have a look at my webpage car alarm install (Isidro)

  19. Incredible! This blog looks just like my old one!
    It’s on a entirely different subject but it haas pretty much the same layout aand design. Great choicxe of colors!

    My web page :: car repair dvd (Daniele)

  20. Wonderful goods feom you, man. I’ve understand your stuff previous to and you are just too
    magnificent. I actually like what you have acquired here, certainly like
    what you’re saying aand tthe way in which you saay it.
    You make it enjoyable and you still take care
    of to keep it smart. I can’t wait to read far more from you.
    This is actually a terrific website.

    my blog … pmp stu; Michele,

  21. If yyou are going for most excellent contents like myself, simply go
    to see this web site everyday since it gives quality contents,
    thanks

    My web site: chilton repair manual (Minda)

  22. With havin sso much content do you ever run into any problems of plagorism or copyright violation? My site has a lot of unique content I’ve either created myself or outsourced but
    it appears a lot of it is popping it up all over the web without
    my permission. Do you know any solutions to help prevent content
    from being ripped off? I’d definitely appreciate it.

    Feel free to visit my site … repair your car (Beatris)