From Chunky Bird, 9 Months ago, written in Java.
This paste will go to its last resting place in 1 Month.
This paste is a reply to SRP from Unreliable Kangaroo
- view diff
Embed
  1. class User
  2. {
  3.     void CreatePost(Database db, string postMessage)
  4.     {
  5.         try
  6.         {
  7.             db.Add(postMessage);
  8.         }
  9.         catch (Exception ex)
  10.         {
  11.             db.LogError("An error occured: ", ex.ToString());
  12.             File.WriteAllText("\LocalErrors.txt", ex.ToString());
  13.         }
  14.     }
  15. }
  16.  
  17. This violates the single responsibility principle as the Createpost() method has too much responsibility. It can create a new post, log errors in the database and log an error in a local file.
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28. We can solve this by abstracting the functionality that handles the error logging and breaks them up into two classes, Post and ErrorLogger so that they each only handles one specific task. The post class only create post and the the ErrorLogger class only handles error logging.  
  29. class Post
  30. {
  31.     private ErrorLogger errorLogger = new ErrorLogger();
  32.  
  33.     void CreatePost(Database db, string postMessage)
  34.     {
  35.         try
  36.         {
  37.             db.Add(postMessage);
  38.         }
  39.         catch (Exception ex)
  40.         {
  41.             errorLogger.log(ex.ToString())
  42.         }
  43.     }
  44. }
  45.  
  46. class ErrorLogger
  47. {
  48.     void log(string error)
  49.     {
  50.       db.LogError("An error occured: ", error);
  51.       File.WriteAllText("\LocalErrors.txt", error);
  52.     }
  53. }
  54.