Software Design Blog - Software Design Simple solutions to solve complex problems / BlogEngine.NET en-US /opml.axd Jay Strydom Software Design Blog 0.000000 0.000000 Late binding principle: defer resource binding to improve flow <img class="img-responsive" src="/pics/banners/IncreaseFlowBlog.jpg"> <br> <p>Donald G. Reinertsen, author of “The Principles of Product Development Flow”, asked the question should we assign a resource to a task at the start of a project?</p> <p>Let’s explore this questions in our software examples below. Will delaying assignment produce light classes, with less memory consumption, and reduced computing waste?</p> <p><b>The problem</b> is how can you delay resource demands during object construction? For example, using dependency injection (DI), how do you inject dependencies into a class and delay the construction of these dependencies at the same time?</p> <p><b>The solution</b> is to use automatic factories to delay resource demands until it is used.</p> <a class="btn btn-primary btn-sm" role="button" href="/Downloads/">Download Source Code</a> <h3>Setting the scene</h3> <p>This post will use an illustration of a cloud storage service that relies on an expensive online connection resource. Let’s assume that we cannot modify the constructor behaviour of the resource class. The interfaces and resource implementation are shown below.</p> <pre class="brush: c-sharp;"> public interface IStorageService { void Save(string path, Stream stream); bool HasSufficientSpace(int requiredSizeMb); } public interface IStorageResource { void UploadStream(string path, Stream stream); } public class CloudStorage : IStorageResource { public CloudStorage() { Console.WriteLine("Establishing cloud connection..."); // Simulate expensive initialisation System.Threading.Thread.Sleep(5000); } public void UploadStream(string path, Stream stream) { // your code here } } public class CloudStorageService : IStorageService { private readonly IStorageResource _resource; public CloudStorageService(IStorageResource resource) { if (resource == null) throw new ArgumentNullException("resource"); _resource = resource; } public void Save(string path, Stream stream) { Console.WriteLine("Called Save"); _resource.UploadStream(path, stream); } public bool HasSufficientSpace(int requiredSizeMb) { Console.WriteLine("Called HasSufficientSpace"); return true; // No need to check, the cloud service has unlimited space } } </pre> <h3>Evaluating the results</h3> <p>Let’s run the code and observe the output.</p> <pre class="brush: c-sharp;"> var container = new UnityContainer(); container.RegisterType&lt;IStorageService, CloudStorageService&gt;(); container.RegisterType&lt;IStorageResource, CloudStorage&gt;(); var storageService = container.Resolve&lt;IStorageService&gt;(); if (storageService.HasSufficientSpace(100)) { using (var fileStream = System.IO.File.OpenRead(@"C:\Temp\File.txt")) { storageService.Save(@"Files\File01.txt", fileStream); } } </pre> <pre>Establishing cloud connection... Called HasSufficientSpace Called Save </pre> <div class="alert alert-warning" role="alert"> <b>Oops!</b> The resource was initialised before it was used. </div> <p>The CloudStorageService class is poorly implemented because:</p> <ul> <li>The resource dependency is demanded in the constructor causing a significant start-up delay. By default, Windows will refuse to start the service if it takes longer than 30 sec to initialise.</li> <li>System memory and computing cycles are wasted since the resource may never be used.</li> </ul> <h3>Late binding with an Auto Factory</h3> <p>We are only going to change the CloudStorageService class. Everything else will remain the same, which minimises the risk of potential regression.</p> <p>The auto factory version is shown below.</p> <pre class="brush: c-sharp;"> public class CloudStorageServiceAutoFactory : IStorageService { private readonly Lazy&lt;IStorageResource&gt; _resource; public CloudStorageServiceAutoFactory(Func&lt;IStorageResource&gt; resource) { if (resource == null) throw new ArgumentNullException("resource"); _resource = new Lazy&lt;IStorageResource&gt;(resource); } private IStorageResource Resource { get { return _resource.Value; } } public void Save(string path, Stream stream) { Console.WriteLine("Called Save"); Resource.UploadStream(path, stream); } public bool HasSufficientSpace(int requiredSizeMb) { Console.WriteLine("Called HasSufficientSpace"); return true; // Cloud service has unlimited space } } </pre> <div class="alert alert-info" role="alert"> <b>Note:</b> Unity will automatically pass in a func&lt;IStorageResource&gt; lamba factory function so your bootstrap code doesn’t have to change. </div> <p>Let’s call the improved CloudStorageServiceAutoFactory class instead.</p> <pre>Called HasSufficientSpace Called Save Establishing cloud connection... </pre> <div class="alert alert-success" role="alert"> <b>Success!</b> The resource demands were deferred until the resource was needed. </div> <h3>Why is this a great solution?</h3> <p>Here is an alternative version as covered in a <a href="" target="_blank">DevTrends</a> post:</p> <pre class="brush: c-sharp;"> public class CloudStorageServiceBad : IStorageService { private readonly Func&lt;IStorageResource&gt; _factory; private IStorageResource _resource; public CloudStorageServiceBad(Func&lt;IStorageResource&gt; factory) { if (factory == null) throw new ArgumentNullException("factory"); _factory = factory; } private IStorageResource Resource { get { return _resource ?? (_resource = _factory()); } } // The methods goes here } </pre> <div class="alert alert-warning" role="alert"> <b>Warning!</b> Bad code, do not copy. </div> <p>The code above is bad because:</p> <ul> <li>A reference is required to the factory and resource, yet the factory is only used once</li> <li>Performing lazy loading in the Resource property is not thread safe</li> </ul> <p>The solution as shown in the CloudStorageServiceAutoFactory class will pass the factory to Lazy&lt;IStorageResource&gt;, which requires less code and is thread safe. See <a href="/post/evolution-of-the-singleton-design-pattern">this post</a> about thread safety.</p> <p>Let’s compare the output of the two solutions by executing the method in multiple threads:</p> <pre class="brush: c-sharp;"> Parallel.Invoke(() =&gt; storageService.Save(@"Files\File01.txt", null), () =&gt; storageService.Save(@"Files\File01.txt", null)); </pre> <p>CloudStorageServiceBad output:</p> <pre>Called Save Called Save Establishing cloud connection... Establishing cloud connection... </pre> <p>CloudStorageServiceAutoFactory output:</p> <pre>Called Save Called Save Establishing cloud connection... </pre> <div class="alert alert-success" role="alert"> <b>Success!</b> The CloudStorageServiceAutoFactory class is thread safe. </div> <h3>Manual Construction</h3> <p>For those out there who haven’t transitioned to DI yet, but I <a href="/post/step-by-step-guide-to-use-dependency-injection">highly recommend</a> that you do, here is how you would wire it up manually:</p> <pre class="brush: c-sharp;"> var service = new CloudStorageServiceAutoFactory(() =&gt; new CloudStorage()); </pre> <h3>Summary</h3> <p>This post illustrated how to improve memory utilisation and to reduce computing waste using automatic factories to delay expensive resource demands.</p> <p>Delaying the demand of resources until the code paths are actually executed can significantly improve application performance.</p> /post/Late-binding-principle-defer-resource-binding-to-improve-flow /post/Late-binding-principle-defer-resource-binding-to-improve-flow#comment /post.aspx?id=50ecf780-9515-46d9-aa67-4b5b75394305 Fri, 29 Jan 2016 10:39:00 +1300 Dependency Injection Software Design C# .NET Jay Strydom /pingback.axd /post.aspx?id=50ecf780-9515-46d9-aa67-4b5b75394305 0 /trackback.axd?id=50ecf780-9515-46d9-aa67-4b5b75394305 /post/Late-binding-principle-defer-resource-binding-to-improve-flow#comment /syndication.axd?post=50ecf780-9515-46d9-aa67-4b5b75394305 How to structure DI registration code cleanly <img class="img-responsive" src="/pics/banners/DIRegistrationCleanupBlog.jpg"> <br> <p>The <a href="/post/step-by-step-guide-to-use-dependency-injection">previous post</a> introduced dependency injection (DI). This post will provide a practical approach to wire up DI cleanly.</p> <p><b>The problem</b> is where do we keep our dependency injection registration bootstrap/wiring code?</p> <ul> <li>We don’t want a giant central registration assembly or a monolithic global.asax class</li> <li>We don’t want to bleed DI into our implementation assemblies that requires DI references</li> <li>We don’t want to be locked into a specific DI framework</li> </ul> <p><b>The solution</b> is to componentise registrations and keep DI frameworks out of our implementation and interface libraries.</p> <a class="btn btn-primary btn-sm" role="button" href="/Downloads/">Download Source Code</a> <h3>What is Unity?</h3> <p>Unity is a DI container which facilitates building loosely coupled apps. It provides features such as object lifecycle management, registration by convention and instance/type interception.</p> <h3>What is MEF?</h3> <p>The Managed Extensibility Framework (MEF) provides DI container capabilities to build loosely coupled apps. It allows an app to discover dependencies implicitly with no configuration required by declaratively specifying the dependencies (known as <i>imports</i>) and what capabilities (known as <i>exports</i>) that are available.</p> <h3>MEF vs Unity</h3> <p>MEF and Unity provide similar capabilities but they both have strengths and weaknesses.</p> <ul> <li>Unity has greater DI capabilities – such as interception</li> <li>Unity is less invasive since MEF requires developers to sprinkle [Import] and [Export] attributes all throughout the code</li> <li>MEF has great discoverability features that are not available in Unity</li> </ul> <div class="alert alert-success" role="alert"> <b>The Winner:</b> MEF for discovery + Unity for DI </div> <h3>Setup</h3> <p>The solution layout of the <a href="/post/step-by-step-guide-to-use-dependency-injection">previous DI introduction post</a> is shown below.</p> <img class="img-responsive" src="/pics/blogs/DIProjectLayoutBefore.png"> <br> <p>All of the bootstrapping code currently lives in the OrderApplication console assembly. The registration can quickly get out of hand with a large app with many components. The registration is also not discoverable which means we can’t just drop in new dlls to automatically replace existing functionality or add new functionality.</p> <h3>Clean Wiring</h3> <p>Let’s get started with clean wiring in 3 steps.</p> <h5>1. Move each components’ DI registration to its own assembly</h5> <pre class="brush: c-sharp;"> // Orders.Bootstrap.dll public class Component { private readonly IUnityContainer _container; public Component(IUnityContainer container) { if (container == null) throw new ArgumentNullException("container"); _container = container;; } public void Register() { _container.RegisterType&lt;IOrderRepository, OrderRepository&gt;(); _container.RegisterType&lt;IEmailService, EmailService&gt;(); _container.RegisterType&lt;IRenderingService, RazaorRenderingService&gt;(); _container.RegisterType&lt;IMailClient, SmtpMailClient&gt;(); _container.RegisterType&lt;IOrderService, OrderService&gt;(); var baseTemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EmailTemplates"); _container.RegisterType&lt;ITemplateLocator, TemplateLocator&gt;( new InjectionConstructor(baseTemplatePath)); } } </pre> <div class="alert alert-success" role="alert"> <b>Solved!</b> The Orders.Implementation and Orders.Interfaces assemblies are no longer coupled to a specific DI framework since it doesn’t know about DI. </div> <h5>2. Discover and bootstrap your registration</h5> <p>MEF is great at discovering assemblies so let’s create an interface that can be discovered by exporting the bootstrap interface.</p> <pre class="brush: c-sharp;"> // Bootstrap.Interfaces.dll public interface IBootstrap { void Register(); } </pre> <p>Add the MEF export attribute to the bootstrap component created in step 1. </p><pre class="brush: c-sharp;"> [Export(typeof(IBootstrap))] public class Component : IBootstrap { private readonly IUnityContainer _container; [ImportingConstructor] public Component(IUnityContainer container) { if (container == null) throw new ArgumentNullException("container"); _container = container;; } public void Register() { // Registration code from step 1 } } </pre> <p>The ResolvingFactory below will perform the discovery and Unity registration.</p> <pre class="brush: c-sharp;"> // Bootstrap.Implementation.dll public class ResolvingFactory { [ImportMany(typeof(IBootstrap))] private IEnumerable&lt;IBootstrap&gt; Bootstraps { get; set; } private readonly IUnityContainer _container; public ResolvingFactory() { _container = new UnityContainer(); Initialise(); } private void Initialise() { var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new DirectoryCatalog(GetBinPath())); using (var mefContainer = new CompositionContainer(catalog)) { mefContainer.ComposeExportedValue(_container); mefContainer.SatisfyImportsOnce(this); } foreach (var bootstrap in Bootstraps) { bootstrap.Register(); } } public string GetBinPath() { var domainSetup = AppDomain.CurrentDomain.SetupInformation; return !string.IsNullOrEmpty(domainSetup.PrivateBinPath) ? domainSetup.PrivateBinPath : domainSetup.ApplicationBase; } public T Resolve&lt;T&gt;() { return _container.Resolve&lt;T&gt;(); } } </pre> <p>The new project assembly layout is shown below.</p> <img class="img-responsive" src="/pics/blogs/DIProjectLayoutAfter.png"> <h5>3. Run the solution</h5> <p>Let’s run the new Unity + MEF solution.</p> <pre class="brush: c-sharp;"> // OrderApplication.dll static void Main(string[] args) { var orderModel = new OrderModel() { Description = "Design Book", Customer = new CustomerModel() { Email = "", Name = "Jay" } }; var factory = new ResolvingFactory(); var orderService = factory.Resolve&lt;IOrderService&gt;(); orderService.Create(orderModel); } </pre> <div class="alert alert-success" role="alert"> <b>Solved!</b> Simply drop a new bootstrap dll in the app directory and it will be registered automatically. </div> <h3>Summary</h3> <p>DI code often becomes messy with large amounts of registrations.</p> <p>This post shows how DI registration can be componentised to keep code clean, simple and discoverable.</p> /post/how-to-structure-di-registration-code-cleanly /post/how-to-structure-di-registration-code-cleanly#comment /post.aspx?id=c68f54a4-9d92-4534-8422-c5c64c2b6da8 Thu, 21 Jan 2016 06:43:00 +1300 Dependency Injection Software Design .NET C# Jay Strydom /pingback.axd /post.aspx?id=c68f54a4-9d92-4534-8422-c5c64c2b6da8 0 /trackback.axd?id=c68f54a4-9d92-4534-8422-c5c64c2b6da8 /post/how-to-structure-di-registration-code-cleanly#comment /syndication.axd?post=c68f54a4-9d92-4534-8422-c5c64c2b6da8 Problem solving beyond the basics <img class="img-responsive" alt="Chain of Responsibility" src="/pics/banners/BeyondBasicsBlog.jpg"> <br> <p>Part of my role is to review code and to coach developers.</p> <p><b>Reviewing code</b> provides insight into a range of techniques to solve problems. Like many developers, we often steal each other’s ideas. To become a good thief, you really need to be able to identify what is valuable so that you don’t steal someone else’s rubbish code.</p> <p>Whilst <b>coaching developers</b>, I often take the code submitted for a code review and ask the person I’m coaching to review it. This technique helps to assess the fidelity of a developer to identify good and bad code. It also exposes new potential skills that can be coached or helps with confirming that a developer has mastered a skill.</p> <p>The aim of this post is to show a working solution and discuss potential problems. A follow up post will provide an alternative that will solve these problems.</p> <h3>Setup</h3> <p>The problem we are trying to solve is to validate a credit card number based on the credit card type. The credit card context model / data transfer object (DTO) is shown below.</p> <pre class="brush: c-sharp;"> public class CreditCard { public string Type { get; set; } public string Name { get; set; } public string Number { get; set; } public string Expiry { get; set; } } public interface ICreditCardValidator { void Validate(CreditCard creditCard); } </pre> <h3>Code Review</h3> <p>The solution that was submitted for a code review is shown below.</p> <pre class="brush: c-sharp;"> public class CreditCardValidator : ICreditCardValidator { public void Validate(CreditCard creditCard) { if (creditCard.Type.ToLower() == "visa") { var visaRegEx = new Regex("^4[0-9]{6,}$"); if (!visaRegEx.IsMatch(creditCard.Number)) throw new Exception("Invalid card"); } else if (creditCard.Type.ToLower() == "mastercard") { var masterCardRegEx = new Regex("^5[1-5][0-9]{5,}$"); if (!masterCardRegEx.IsMatch(creditCard.Number)) throw new Exception("Invalid card"); } else { throw new Exception(string.Format("Card type {0} is unsupported.", creditCard.Type)); } } } </pre> <div class="alert alert-info" role="alert"> <b>Stop!</b> How many issues can you spot before you continue to read on? </div> <h3>Code Smells</h3> <p>Let's run through a standard set of heuristics to identify code smells.</p> <ul> <li><b>Duplicate code</b> – both If statements uses a fairly similar pattern but it doesn’t appear to justify refactoring</li> <li><b>Long method</b> – the method length appears to be acceptable</li> <li><b>Large class</b> – the class fits on one screen and it doesn’t appear to be too large</li> <li><b>Too many parameters</b> – it only has one parameter so that's fine</li> <li><b>Overuse of inheritance</b> – no inheritance at all</li> <li><b>Not testable</b> – the class implements an interface which suggests that clients rely on a contract instead of a concrete implementation which promotes mocking and the class appears to be easily testable</li> </ul> <div class="alert alert-success" role="alert"> <b>Success!</b> The solution passed the code smell heuristics. </div> <h3>Code Problems</h3> <p>Even though the code doesn't appear to have code smells, the code is not great. Here is a list of problems with the code:</p> <ol> <li><b>Guard Exception</b> – an ArgumentNullException should be thrown before line 5 when the client calls the validator with a null credit card instance</li> <li><b>NullReferenceException</b> – the client will receive an “object reference not set to an instance of an object” exception on line 5 when the card type is null</li> <li><b>Throwing Exceptions</b> – throwing custom exceptions such as InvalidCreditCardNumberException is better than throwing a generic Exception which is harder to catch and bubble up</li> <li><b>Immutable String Comparison</b> – at least the code is case insensitive using .ToLower() although strings are immutable so the .ToLower() comparison will create a new copy of the string for each if statement. We could just use the string comparison function such as creditCard.Type.Equals("visa", StringComparison.OrdinalIgnoreCase)</li> <li><b>Constants</b> – we should avoid using magic strings and numbers in code and use constants instead for names such as credit card names. A CreditCardType Enum could be an alternative if the credit card types are fixed.</li> <li><b>Readability</b> – as the number of supported credit cards grows, readability can be improved with a switch statement</li> <li><b>Globalisation</b> – error messages can be placed in resource files to provide multilingual support</li> <li><b>Performance</b> – the regular expression is created for every credit card number that is validated which can be changed to a singleton. We can use the RegEx compile parameter to improve the execution time.</li> </ol> An alternative solution using a switch statement is shown below. <pre class="brush: c-sharp;"> public class CreditCardValidator : ICreditCardValidator { private static readonly Regex VisaRegEx = new Regex("^4[0-9]{6,}$", RegexOptions.Compiled); private static readonly Regex MasterCardRegEx = new Regex("^5[1-5][0-9]{5,}$", RegexOptions.Compiled); public void Validate(CreditCard creditCard) { if (creditCard == null) throw new ArgumentNullException("creditCard"); if (string.IsNullOrWhiteSpace(creditCard.Type)) throw new ArgumentException("The card type must be specified."); switch (creditCard.Type.ToLower()) { case "visa": if (!VisaRegEx.IsMatch(creditCard.Number)) throw new InvalidCardException("Invalid card"); break; case "mastercard": if (!MasterCardRegEx.IsMatch(creditCard.Number)) throw new InvalidCardException("Invalid card"); break; default: throw new InvalidCardException( string.Format("Card type {0} is unsupported.", creditCard.Type)); } } } </pre> <div class="alert alert-warning" role="alert"> <b>Warning!</b> Don't steal this code. It works but the design is poor. </div> <p>Even though the code was improved, the design is still poor and breaks SOLID principals.</p> <ol start="9"> <li><b>Open/Closed Principal</b> - The class might be small but is hard to extend by supporting additional credit cards without modifying the code</li> <li><b>Single Responsibility Principle</b> - The class knows too much about various credit card types and how to validate them</li> </ol> <h3>Summary</h3> <p>The post identified issues with a working solution and discussed fundamental coding practices.</p> <p><b>If you can spot more issues, please let me know. If you know how to solve the problem then I’d love you hear from you too.</b></p> <p>The <a href="/post/kill-the-switch-with-the-strategy-pattern">next post</a> will discuss how the design can be improved by applying a design pattern.</p> /post/problem-solving-beyond-the-basics /post/problem-solving-beyond-the-basics#comment /post.aspx?id=1eba48ee-e83c-46c2-8966-c54e1f2bb1ea Fri, 08 Jan 2016 15:17:00 +1300 Software Design .NET C# Jay Strydom /pingback.axd /post.aspx?id=1eba48ee-e83c-46c2-8966-c54e1f2bb1ea 0 /trackback.axd?id=1eba48ee-e83c-46c2-8966-c54e1f2bb1ea /post/problem-solving-beyond-the-basics#comment /syndication.axd?post=1eba48ee-e83c-46c2-8966-c54e1f2bb1ea