{"id":100,"date":"2016-10-08T18:16:16","date_gmt":"2016-10-08T18:16:16","guid":{"rendered":"http:\/\/www.dimlucas.com\/?p=100"},"modified":"2017-02-14T08:49:00","modified_gmt":"2017-02-14T08:49:00","slug":"loose-coupling-explained","status":"publish","type":"post","link":"https:\/\/www.dimlucas.com\/index.php\/2016\/10\/08\/loose-coupling-explained\/","title":{"rendered":"Loose Coupling in C# Explained"},"content":{"rendered":"<p>Hello everyone, in this tutorial I want to provide you with a simple as possible, yet comprehensive enough example of what loose coupling really is and why it&#8217;s useful. Understand loose coupling and you&#8217;re going to have another advanced software engineering concept under your belt.<\/p>\n<p>Before we start, I&#8217;m going to borrow the Loose Coupling definition from <a href=\"https:\/\/en.wikipedia.org\/wiki\/Loose_coupling\">Wikipedia<\/a>:<br \/>\nIn\u00a0computing\u00a0and\u00a0systems design\u00a0a\u00a0loosely coupled\u00a0system is one in which each of its\u00a0components\u00a0has, or makes use of, little or no knowledge of the definitions of other separate components. Sub-areas include the\u00a0coupling\u00a0of classes, interfaces, data, and services.<\/p>\n<p>The key takeaway from this is the phrase &#8220;little to no knowledge&#8221;. Object oriented programming and design offers multiple layers of abstraction for your application. That&#8217;s another key-word, &#8220;Abstraction&#8221;. Everyone who has ever taken a course on OOP or read an OOP book has stumbled upon this word and probably knows how OOP helps you achieve Polymorphism. The benefits of loose coupling include:<\/p>\n<p>\t\u2022 Cleaner Code: After applying loose coupling your code is going to be much easier to read<br \/>\n\t\u2022 More Maintainable Code: Your code will also be easier to change<br \/>\n\t\u2022 Testable Code: This is the reason why beginners see no need for loose coupling. Because most beginners do not unit test and don&#8217;t know how hard it is to unit test tightly coupled code<br \/>\n\t\u2022 Scalable Code: I understand that in a small application loose coupling might not make any noticeable difference but in large scale projects it just makes your life a lot easier<\/p>\n<p>The easiest way to explain loose coupling is actually to explain the exact opposite, tight coupling. Tight coupling is when one or more classes in your application is highly dependent on one or more other classes. Take this class hierarchy for example:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nclass ClassA\r\n{\r\n    public ClassA() { }\r\n}\r\n\r\nclass ClassB\r\n{\r\n    public ClassB()\r\n    {\r\n        _foo = new ClassA();\r\n    }\r\n\r\n    private ClassA _foo;\r\n}\r\n<\/pre>\n<p>In this simple example, ClassB contains an instance of ClassA and ClassB is <strong>responsible<\/strong> for creating that instance. So in this implementation ClassB needs to have <strong>knowledge<\/strong> about the inner workings of ClassA. Remember that we want ClassB to have little or no knowledge about how ClassA operates or how its objects get instantiated. The above code using loose coupling will look like this:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nclass ClassA : IMyInterface\r\n{\r\n    public ClassA() {  }\r\n}\r\n\r\nclass ClassB\r\n{\r\n    public ClassB(IMyInterface foo)\r\n    {\r\n        _foo = foo;\r\n    }\r\n\r\n    private IMyInterface _foo;\r\n}\r\n<\/pre>\n<p>An interface, in this very simplistic example called MyInterface, is introduced to solve the conflict. That way, any class that implements IMyInterface can be passed to class B who no longer needs to know how to instantiate it.<\/p>\n<p>To provide a more real-world example, I will create a Console Application project with some rather simple functionality. It\u2019s going to display some to-dos in the console and whether those To-Dos have been completed or not. (The full code of this project can be found <a href=\"https:\/\/github.com\/dimlucas\/CSharpBlog\">here<\/a>).<\/p>\n<p>I&#8217;m going to create a &#8220;Models&#8221; folder to place my ToDo class first:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/dimlucas\/b7a212848a15c9b2d2fbcf5626e51cdb.js\"><\/script><\/p>\n<p>I tried to keep it as simple as possible, after all this is just a console application.<\/p>\n<p>Next let&#8217;s create the class with the basic to-do functionality. For the sake of demonstration I&#8217;m going to actually create two classes. One will be tight coupled, the other will be loosely coupled. Let&#8217;s name them TightlyCoupledToDos and LooselyCoupledToDos respectively.<\/p>\n<p>For now the two classes are essentially identical:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class TightlyCoupledToDos\r\n{\r\n    public class TightlyCoupledToDos\r\n    {\r\n        \r\n    }\r\n\r\n    public async Task&lt;IEnumerable&lt;ToDo&gt;&gt; All()\r\n    {\r\n\r\n    }\r\n}\r\n<\/pre>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class LooselyCoupledToDos\r\n{\r\n    public LooselyCoupledToDos()\r\n    {\r\n\r\n    {\r\n\r\n    public IEnumerable&lt;ToDo&gt; All()\r\n    {\r\n\r\n    }\r\n}\r\n<\/pre>\n<p>Both have an All() method that returns a list of to-dos. The interesting part in how these two classes are going to populate the to-do list. In a real world application data like that probably come from a service. So let&#8217;s go ahead and create our ToDoService in a &#8216;Services&#8217; folder:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class ToDoService\r\n{\r\n    public IEnumerable&lt;ToDo&gt; GetAll()\r\n    {\r\n    \t\r\n    }\r\n}\r\n<\/pre>\n<p>This is an initial form of the service. Because we don&#8217;t have an API or a database we are going to fetch data from JSONPlaceholder&#8217;s ToDo list which can be found here https:\/\/jsonplaceholder.typicode.com\/todos<\/p>\n<p>To parse the JSON data we will use Newtonsoft&#8217;s NuGet package. To add it:<br \/>\n\t\u2022 Right click on your project<br \/>\n\t\u2022 Go to &#8216;Manage NuGet Packages&#8217;<br \/>\n\t\u2022 Go to the &#8216;Browse&#8217; tab<br \/>\n\t\u2022 Search for &#8216;Newtonsoft.Json&#8217;<br \/>\n\t\u2022 Click Install<\/p>\n<p>Next we will use an HttpClient and the Newtonsoft.JsonConvert class to get the data from the API and parse them to a list of ToDo objects:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/dimlucas\/668593e285fc972d8cb5e32067e2f3bc.js\"><\/script><\/p>\n<p>A simple enough, service implementation. It uses an instance of the HttpClient class to asynchronously read JSON data the feed them to the Json Converter for deserialization.<\/p>\n<p>After having created the service, let&#8217;s use it in our TightlyCoupledToDos class to get some data.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/dimlucas\/655d7c3a9b39d747d6e88e53a79f23ad.js\"><\/script><\/p>\n<p>You see the service in initialized in the constructor and the All() method uses the service to get the parsed data and return it<\/p>\n<p>Let&#8217;s go in our Program.cs file to make use of the TightlyCoupledToDos class and display the list of to-dos on screen<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nclass Program\r\n{\r\n    static void Main(string[] args)\r\n    {\r\n        ToDos();\r\n        Console.ReadLine();\r\n    }\r\n\r\n    static async void ToDos()\r\n    {\r\n        TightlyCoupledToDOs vm = new TightlyCoupledToDos();\r\n        IEnumerable&lt;ToDo&gt; todos = await vm.all();\r\n        foreach(ToDo todo in todos)\r\n        {\r\n            Console.WriteLine(todo);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>The Console.ReadLine() statement is there to keep the console window open for us, so that we can see the results. The ToDos() method instantiates the TightlyCoupledToDos class, gets the todos asynchronously and writes them to the output:<\/p>\n<p><img loading=\"lazy\" src=\"https:\/\/www.dimlucas.com\/wp-content\/uploads\/2016\/11\/loosecoupling.png\" alt=\"loosecoupling\" width=\"697\" height=\"494\" class=\"alignnone size-full wp-image-107\" \/><\/p>\n<p>So far so good, our classes all work and the absence of loose coupling has yet to come back and bite us. But what if we need to use another service. There are several reasons why we would want to replace the ToDoService with something else:<br \/>\n\t\u2022 We might want to test our code with fake data provided by fake service<br \/>\n\t\u2022 We might want to support different sources of data like files, APIs or databases<br \/>\n\t\u2022 We might want to conditionally supply a service to the ToDos class according to some event<\/p>\n<p>It&#8217;s hard to do so when the ToDos class heavily depends on a specific service implementation. As you might have guessed it&#8217;s time to get ourselves some loose coupling. Here&#8217;s what we need to do:<\/p>\n<p>\t\u2022 Create a IToDoService interface that will be implemented by any supporting service<br \/>\n\t\u2022 Modify our ToDoService to implement the IToDoService interface<br \/>\n\t\u2022 Create a TestToDoService that also implements IToDoService<br \/>\n\t\u2022 Modify LooselyCoupledToDos to work with either service<\/p>\n<p>The implementation of the IToDoService is pretty simple:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/dimlucas\/42d90d1cecad2bef94d5ea727c1cea42.js\"><\/script><\/p>\n<p>And in ToDoService:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/dimlucas\/44f954620970c3982fd906354d0a09b3.js\"><\/script><\/p>\n<p>Now let&#8217;s create another service that will return local data to the caller instead of calling an API or querying a database. This is a rather common practice during unit tests.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/dimlucas\/090426575c0e09e250c3d751883ec20d.js\"><\/script><\/p>\n<p>The TestToDoService implements the IToDoService differently. Instead of using an HttpClient to get JSON data from the web, this class creates a list and fills it up with some dummy data to be sent to the caller for testing<\/p>\n<p>Now this is the most important step of them all! We need to go to our LooselyCoupledToDos class and make it support what its name says it supports. In order to do that, the class needs to hold a reference to an IToDoService object and not a ToDoService or TestToDoService object. It also needs to take that reference as a constructor argument rather than instantiating on its own. That way our LooselyCoupledToDo class knows nothing about the actual service and thus we will have achieved the precious separation of concerns we want.<\/p>\n<p><script src=\"https:\/\/gist.github.com\/dimlucas\/66add27ae1d200a566c8e5b919549e79.js\"><\/script><\/p>\n<p>Now that we&#8217;ve implemented our classes in a loosely coupled way let&#8217;s see how easy it is to switch services. Let&#8217;s introduce a static field in our Program class that will be true if the app is in test mode and therefore needs to use test data or false if the application is not in test mode and must fetch real data:<\/p>\n<p><script src=\"https:\/\/gist.github.com\/dimlucas\/b86cfcb5a054adae503ea2e93de096bc.js\"><\/script><\/p>\n<p>If _testMode is true the LooselyCoupledToDos is initialized with the test service, if it is not it gets initialized with the real service.<\/p>\n<p>You can see the whole project in my GitHub repository dedicated to C# <a href=\"https:\/\/github.com\/dimlucas\/CSharpBlog\">here<\/a><\/p>\n<p>Now that you&#8217;ve learned what loose coupling is, it&#8217;s time to take it one step further and learn about Inversion Of Control and Dependency Injection. I will be writing on those soon. Until then, keep coding!!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello everyone, in this tutorial I want to provide you with a simple as possible, yet comprehensive enough example of what loose coupling really is and why it&#8217;s useful. Understand loose coupling and you&#8217;re going to have another advanced software engineering concept under your belt. Before we start, I&#8217;m going to borrow the Loose Coupling [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[6],"tags":[59,57,58,62,60,61,63,64,65,66],"_links":{"self":[{"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/posts\/100"}],"collection":[{"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/comments?post=100"}],"version-history":[{"count":18,"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/posts\/100\/revisions"}],"predecessor-version":[{"id":139,"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/posts\/100\/revisions\/139"}],"wp:attachment":[{"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/media?parent=100"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/categories?post=100"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.dimlucas.com\/index.php\/wp-json\/wp\/v2\/tags?post=100"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}