# 88 - Creating SOLID Code: Single Responsibility Principle (SRP)


2/25/2009
Level: Intermediate
Tags: SOLID Principle
Comments: (25)
Author:
Stephen Bohlen
 
Presented By:
Codebetter.com


This is the first in a 5 part series where we will explore the tenets of the S.O.L.I.D principles.

In this first episode we will take a look at the S (Single Responsibility Principle) and see how following this principle can help us to create cleaner, more manageable code

S - Single Responsibility Principle
O - Open/Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle
Click here to Watch this Episode

Download (17.28 MB) (11:42) (1440x900)
Download (12.77 MB) (11:42) (960x600)

Links/Resources:


Comments: (25)

Aleh Matus said....

Strictly speaking, each class in this example still has more than one responsibility in the end. For example, Report Printer has one do-responsibility. It is responsible for the print workflow: getting the data for the report, formatting the data, and sending it to the output stream. Report Printer also has three know-responsibilities. It is responsible for knowing where to get the data, knowing who to ask to format the data, and knowing that the output stream is the console. One way to achieve single responsibiliy (SRP) for the Report Printer class is to remove all its know-responsibilities by appling dependency injection (DIP).


2/26/2009 9:02:44 PM

Steve Bohlen said....

@Aleh:

Patience, my friend, this is part 1 of a 5-part series and if you look carefully at the SOLID acronym you will see that DIP isn't until the 5th installment :)

If I were to perfectly redesign the classes all in the first episode, what would be left for the subsequent installments when I *do* need to focus on DIP?

Trust me, DIP (and for that matter OCP, LSP, and ISP) are coming and by the end we should (hopefully!) see a better overall design leveraging all of the SOLID principles.

Thanks for the comment though because it zeros us in on the very important fact that most of these principles are actually most valuable when all taken together as a self-reinforcing group) rather than in isolation as is being presented here.

With luck, by the end of all 5 of the installements this will be more apparent once all of the other principles are brought into play.  In a sense this is the downside of releasing these in separate 10-minute units rather than all at once in a single hour-long screencast but as creators we all have to live within the confines of our medium of choice :)


2/27/2009 12:49:43 PM

flipdoubt said....

I was going to make a similar comment about where the different responsibilities are being instantiated and working together, but I will be patient. One thing I am (patiently) waiting to see is how the output from one responsibility will be passed to the next. The data access and report formatter responsibilities can't return void in a production app. I understand why you want them separate, but how you keep them separate but pass the work product from one to another seems to load up my code with a bunch of assumptions. Still, eagerly waiting to see what happens.


3/2/2009 5:45:27 AM

Steve Bohlen said....

@flipdoubt:

That's a great point, but you're not going to see the passing back of data out of the operations in this series as its moving too far away from the core of the intent (to show refactoring by applying SOLID principles).

You do bring up a very important point however but its soluble by defining the operations of the components (e.g., the DataAccess class) in terms of returned interfaces as well (e.g., IReportData or similar) so that this too is a coupling in terms of abstractions rather than implementations.

Nice catch that the sample fails to address this aspect of the SRP (and other loose-coupling) but that's how I usually recommend addressing it.


3/2/2009 2:45:37 PM

flipdoubt said....

Thanks for the prompt reply, Steve. Can you recommend any tutorial's that go all the way with a concrete example that shows the separated responsibilities passing work products around?

The IReportData you suggest is where I get in trouble. If it has methods that read a byte[], then the data consumer has to make assumptions. If it is more like a list of entities or a more memory friendly IEnumerable of entities, is that too specific of an implementation? What would Uncle Bob do?


3/3/2009 5:18:22 AM

Steve Bohlen said....

@flipdoubt:

Yeah, I think I 'spoke' too quickly there with IReportData; in my real world, it would in fact probably by IEnmerable<ReportElement> returned from DataAccess.GetData() and that's about the best level of abstraction I can hope for in such a case.

This goes to a point (I agree with) that I read someone on a blog make one day (and I paraphrase): "there is no such thing as tight or loose coupling -- there is only coupled or non-coupled code.  The trick is to always couple to abstractions rather than implmentations."

And I love the "What would Uncle Bob do?" question -- its a great way to consider arriving at the proper solution :)


3/3/2009 7:05:35 AM

Wayne Godfrey said....

First - I love what you're doing here and really appreciate the length of the videos (kinda SRPish).

My first reaction when watching this video was similar to Aleh's in that it seemed you still ending up with one of your classes having multiple responsibilities. ReportPrinter was still "responsible" for getting the data and formatting the report - it just handed the work to another class. It just had that "smell" to it as I've heard many say.

I'll try to stay patient and see if DIP will remove the "code smell".

Thanks again!


3/5/2009 9:03:41 AM

Derek said....

@flipdoubt:

"What would Uncle Bob do?" - that's brilliant! :)

@Steve:

Once again nice series of screen casts; I've read the book but the film was better.


3/7/2009 9:22:10 AM

nightshade427 said....

I'm not sure I understand the way the responsibilities were broken out. Why does the printer class know where to get data? Isn’t that knowledge for a report to have not a printer? Doesn't a report need to know where to gets its data and not the printer? Doesn’t a printer just print data given to it? Would it be better to have the Report class depend on ReportData and ReportPrinter and have ReportPrinter depend on ReportFormater . Then in print method of the Report have the Report get the data it needs from ReportData and pass that to ReportPrinter, which then the ReportPrinter hands off to ReportFormater. Leaving the other principles out of the picture I was thinking something like this, it is a slightly different breakdown of responsibilities, what are your thoughts?

public class Report{

  public void Print(){
    var data = new ReportData();
    var printer = new ReportPrinter();
    printer.print(data.GetData());
  }

}

public class ReportData{

  public string GetData(){
    Console.WriteLine("Getting Data...");
    return "test data";
  }

}

public class ReportPrinter{

  public void Print(string dataToPrint){
    var formater = new ReportFormater();
    string formated data = formater.Format(dataToPrint);
    Console.WriteLine("Printing Report...");
  }

}

public class ReportFormater{

  public string Format(string dataToFormat){
    Console.WriteLine("Formating Report...");
    return "formated data";
  }

}


3/8/2009 2:43:22 PM

Ryan said....

How were you transforming:

new ReportPrinter()

into:

ReportPrinter reportPrinter = new ReportPrinter();

This seems like a really handy shortcut and I just spent way too much time trying to figure out how to do it!

Thank You


3/23/2009 2:24:38 PM

Claudio Lassala said....

Great series of webcasts on SOLID, guys.

Quick CodeRush tip: if you want to create a class without the default constructor, use the "c," template. That way you don't have to remove the ctor every time.  ;)


3/28/2009 11:22:27 AM

Bog Saggett said....

Great screencast. Just one suggestion. Could you speak a little slower please? Some parts were a little hard to comprehend because of the speed of talking, particularly as to me you have an accent :)


4/12/2009 3:41:41 AM

Darren said....

What Visual Studio Add-In are you using? Looks sweet!


5/1/2009 9:35:03 PM

cheap ugg boots on sale said....

8/25/2010 8:57:32 AM


ugg boots sale said....

1.Ugg footwear is a great regard for your base like many reasons.cheap uggs for sale. Probably the most rocky landscape. Another equally important disputeugg uk is the ever-mounting medley of styles ugg boots saleand ensign that you are removable to buy ugg boots, actually form to the shape of the arch.UGG Bailey Button|UGG Argyle Knit|UGG Cardy|UGG Crochet|UGG Flower|UGG Leopard|UGG Mini|UGG Paisley|UGG Short|UGG Tall|UGG Elsey Wedge|UGG Infants Erin|UGG Langley|UGG Lo Pro|UGG Lo Pro Button|UGG Locarno|UGG Mayfaire|UGG Nightfall|UGG Rainier Eskimo|UGG Sundance II|UGG Ultimate Bind|UGG Ultra Short|UGG Ultra Tall|UGG Suede|UGG Upside|UGG Roxy|UGG Seline|UGG Corinth Wedge|UGG Liberty|UGG Highkoo|UGG Knightsbridge|UGG Bomber Jacket|UGG Adirondack|UGG Suburb Crochet|UGG Bailey Button Boots|UGG Classic Argyle Knit|UGG Classic Cardy Boots|UGG Classic Crochet Boots|UGG Classic Flower boots|UGG Classic Tall Boots 5684 Leopard|UGG Classic Mini Boots|UGG Classic Paisley Boots|UGG Classic Short Boots|UGG Classic Tall Boots|UGG Elsey wedge Boots|UGG Infant's Erin Baby|UGG Women's Langley Boots Black|UGG Lo Pro Button Boots|UGG Women's Locarno Boots|UGG Mayfaire boots|UGG Nightfall Boots|UGG Rainier Eskimo Boots|UGG Sundance II Boots|UGG Ultimate Bind Boots|UGG Ultra Short Boots|UGG Ultra Tall Boots|UGG Suede Boots|UGG upside Boots|UGG Roxy Tall Boots|UGG seline Boots|UGG Women's Corinth Boots in Cocoa|UGG Liberty Boots|UGG Highkoo Boots|UGG Knightsbridge Boots|UGG Bomber Jacket Boots|UGG Adirondack Tall Boot|UGG Suburb Crochet Boots|UGG Swell|UGG Desoto Espresso|UGG Cove|UGG Ashur|UGG Gaviota|UGG Shoreline|UGG Smithfield|UGG Tess|UGG Classic Tall|UGG Women's Stella|UGG Brookfield|UGG Roseberry|UGG Kensington|UGG Chrystie|UGG Sandra|UGG Tasmina Ultramarine|UGG Payton|UGG Felicity|UGG Gissella|Ugg Stripe Cable Knit|UGG Broome|UGG Adirondack|UGG Swell Tall Boots|UGG Desoto Espresso Boots|UGG Cove Boots|UGG Ashur Boots|UGG Gaviota Boots|UGG Shoreline Boots|UGG Smithfield Boots|UGG Tess Boots|UGG Classic Tall Boots II Boots|UGG Women's Stella Boots|UGG Brookfield Boots|UGG Roseberry Boots|UGG Kensington Boots|UGG Chrystie Boots|UGG Handbags|UGG Sandra Boots|UGG Tasmina Ultramarine Boots|UGG Payton Boots|UGG Felicity Boots|UGG Gissella Boots|Ugg Stripe Cable Knit Tall Boots|UGG Broome Boots|UGG Adirondack Boots II|UGG Bailey Button Fancy|Kid's UGG Boots 5281|UGG Bailey Button Triplet|UGG Classic Tall 5885|2.timberland boots3.mbt shoes4.tiffany5.ugg uk


8/27/2010 8:08:18 PM

jack said....

Dear friends, welcome to our nike air max shoes online shop- www.kicksinfo.com, and all our nike air max shoes - are original from the Nike factory, we are the Nike shoes professional wholesaler and we are serious want to establish a long term business with worldwide customers, we can supply our best wholesaler price with the lowest discount for all our - customers, also we can take free shipping service and make drop ship to worldwide address. First, you can use the lowest price to buy a pair of - authentic nike air max 2009, nike air max 90, nike air max tailwind, nike air max tn and now hot sale nike air max 2010 shoes; Second, we are professional and we can supply our best service to you. So have a nice time to shopping in our online shop and choose the Nike shoes you like.

Nike Air Max is a line of shoes first released by Nike, Inc. in 1987. Since its introduction, Nike has frequently introduced newest and updated models in the same product line.Today, buy cheap nike free shoes is the right choice is not only good for your health, but also is convenient for walking and running or training, so most people want to come home or give as a gift to their friends or family! Marking happier! They are really a nice addition this summer for wardrobe.We have a variety of nike free 3.0, nike free 7.0 shoes for you to choose.Certainly all our products are for sale, new and free shipping.Wish has a good experience Purchase here.


8/28/2010 12:39:19 AM

replica watches said....

The company Guido Panerai & Figlio was replica watches founded in 1860 in Florence, Italy. The brand became the official watchmaker of replica handbags the Italian Navy, providing them with highly specialized and military timepieces. Panerai watches are unique and their design is unmistakable. The large size of ugg boots the watch is not in conflict with the minimalist dial markings. The need replica watches for instant legibility of the time in poor light or even in darkness resulted in the design of a unusually large dial, clearly marked ugg boots with luminous numerals and hour markers. So the watches have an aesthetic replica watches personality as strong as their technical and mechanicals characteristics, making them great watches from every point of replica watches view, destined for great performances and personalities.


8/30/2010 5:48:53 PM

links of london said....

The easiness of gold necklaces and authentic life people links of London to complete the quest for really enjoy, In 2010, sweetie bracelets unveiled boutique bracelet, in contrast to the clumsy thick bracelet, the revolutionary bracelet build a elegant and wonderful sensitive elegance, and girls will consider it. An elegant links of London bracelet female with extended hair, improving her palm and also the links of london charms stunned tumble, much like writing a wonderful message. Receive my very own knowledge to illustrate. Mother's day is nearly here, so I wish to drive my mummy a silver charms bracelets which was my mother's most popular for years but can't buy. On entering the links of London shop, I really feel really happy for I can give my mother a big surprise. After selecting carefully, I finally acquire charm bracelets with extended hair.
More useful resources about links of London sites you need
links of London links of London, sweetie bracelets sweetie bracelets, links of london charms links of london charms, silver charms silver charms, charm bracelets charm bracelets, links of london friendship bracelets links of london friendship bracelets, links of london uk links of london uk, links of london sweetie bracelets links of london sweetie bracelets, links jewelry co uk links jewelry co uk, linksoflondon linksoflondon, links of London necklaces links of London necklaces, links of London earrings links of London earrings, links of London jewelry links of London jewelry
thomas sabo thomas sabo sale thomas sabo uk sabo jewellery thomas sabo jewellery thomas sabo charms thomas sabo bracelets sabo charms thomas sabo bracelet thomas sabo charms sale


8/30/2010 8:08:00 PM

Ugg Bailey Button said....

any reason to say no to cheap UGG boots? UGG boots that prevailed for years will still warm your frozen toes with the featured sheepskin leather.get moreCheap Ugg Boots ||Ugg Boots SaleUgg Boots UK ||Ugg Cardy Boots || Ugg Bailey Button||Ugg Classic Cardy  ||Ugg Classic Short || g Classic Tall || Ugg Classic Mini    ||


8/30/2010 10:52:40 PM

asdfas said....

We are a professional online retailer and wholesaler who are mainly exporting good quality replica handbags and replica watches.www.bagswatches.com is dedicated in superior quality Replica products and Customer service.We are proud to offer you a wide range of Swiss Watches.All of them are good in quality and reasonable in price.Is it possible to buy best quality replica rolex ?The answer it obvious.Look around our website,we offer best quality replica Tag Heuer,best quality Replica Omega and best quality Replica Patek Philippe.Best quality products,best price,and best customer service.We have a sufficient sources of goods.Breitling replica is one of the most fashionable and popular brand watches.No matter what kind of brand watch you are looking for,we can meet your requirements.Replica U-BOAT are in a unexpected discount price.replica handbags hot-sellers on our site. We supply all name-brand replica handbags Most of us like to carry brand handbags that will fully reflect our elegance and charming appearance.Louis Vuitton handbags play a very important role in our life. Even some of celebrities bring replica Louis Vuitton.knock off Louis Vuitton with first-class quality are also value for your money.That is the main reason why celebrites will choose replica handbags.Superior quality Gucci handbags are worthy to cherish, too.Regardless of choosing replica Gucci or you just a fan of replica chanel,as long as you buy from us,you will gain greatly from this shopping.We have 4 years experience in this line.We are experienced in deal with perfect replica Hermes with reasonable and competitive prices.We have already built up long-term business relationships with customers around the world.If you have a really keen interest in Hermes handbags or you take a fancy to prada handbags .Please feel free to shop on our store.We also provide all kinds of chanel handbags.The goods is marvelous and the price is magnificent.Every order is free shipping.Shop Breitling replica on our store is your best choice.Replica U-BOAT should not be ignored.Large orders will be offered wholesale price and free gifts.


8/31/2010 6:20:33 AM

nike dunk said....

linda It's unfortunate that those who could best benefit from the Gucci Shoes Sale won't read it. They'll simply see it as an dunk low on a sacred icon. It's too bad, because probably at least 47 percent of the electorate believes a good bit of the shox shoes and nike shox shoes myth ??not a comforting thought. The author's Air Jordan Shoes and Air Jordans are reasonable look at the huge discrepancy between what Reagan supposedly did and his actual ugg classic boots. It is not Reagan bashing, though certainly some much-needed balance is achieved in assessing Michael Jordan Shoes's presidency. He is most assuredly correct to suggest that if we are to have a Coach Handbags at a bright future, we must, at the very least Cheap Jordans, move beyond myths. The book does tend to be a bit Cheap MBT Shoes and repetitious.


9/1/2010 5:38:51 PM

sky said....

http://www.albatouristik.com
 p90x DVD workout  only for your healthy
http://www.rosetta-stone-shop.net
 rosetta stone  enjoy your learning another language
http://www.itunes-gift-cards.org
itunes gift card  convinent  for your friends and relataves
http://www.highwaytowatches.com      swiss replica watches
http://www.watches-mens.com      mens watches
http://www.cnaweb.net/product/fitness_programs/insanity.shtml      insanity workout DVD price , insanity workout.com
http://www.cnaweb.net/product/fitness_programs/turbofire.shtml      Turbo Jam Workout DVD ,Turbo Jam.com
http://www.cnaweb.net/product/fitness_programs/turbofire.shtml      Turbo Fire Workout DVD ,Turbo Fire.com
http://www.cnaweb.net/product/fitness_programs/body-gospel.shtml      Body Gospel Workout DVD,Body Gospel.com
http://www.cnaweb.net/product/fitness_programs/power90.shtml      Power 90 Workout DVD ,Power 90.com
http://www.cnaweb.net/product/fitness_programs/brazil_butt_lift.shtml      Brazil Butt Lift ,Workouts DVD
http://www.cnaweb.net/product/fitness_programs/best_sellers/slim_in_6.shtml      Slim in 6 Workout DVD,Slim in 6.com
http://www.cnaweb.net/product/fitness_programs/hip_hop_abs.shtml      Hip Hop Abs Workout DVD, Hip Hop Abs.com


9/1/2010 6:51:58 PM

cheap ugg boots said....

Cheap UGG Boots On Sale!We are the best ugg boots saler in UK.Buy Cheap UGG Boots now,here you can pucahsing the most Discount UGG Boots without 100% Original,we assured that our of our ugg classic short boots are comes from factory direcly with competitive price,14-Day Money-Back Guarantee.Fast And Free Shipping! Save 20-60% OFF!

Do you want to buy Cheap Women's Ugg Bailey Button?Softugg.com are professional supply Women's Sundance Boots,Ugg Classic Cardy Sale,our ugg boots are comes from factory direclty,made with top quality,competitive price and best customer,welcome to your inquiring!


9/2/2010 2:30:33 AM



Name: *
Email (not displayed): *
Url:
Comments: *



So, you Human...?