Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Thursday, 24 September 2015
( F# | Xunit )

Referencing Calculator.add

image

module Calculator let square x = x * x let add x y = x + y let mult x y = x * y

and then

//module Program // Declaring myself in the same namespace // so don't need to do an open module Mateer.Demo.Calculator.Program // open namespace //open Mateer.Demo.Calculator // open the module! //open Mateer.Demo.Calculator.Adder [<EntryPoint>] let main args = printfn "add 5 and 3 is %d" (Adder.add 5 3) 0

and

// specific //namespace global namespace Mateer.Demo.Calculator // need an = and indents when multiple modules in 1 file module Adder = let square x = x * x let add x y = x + y module Multiplier = let mult x y = x * y

Testing

image

xunit2 added via nuget.  TestDriven.Net as the test runner.

| | # 
# Friday, 29 May 2015

To get XUnit2 working with AutoFixture using R# test runner:

Run powershell as administrator: Set-ExecutionPolicy RemoteSigned

Install-Package AutoFixture.XUnit2   **be careful not to install AutoFixture.Xunit
(This installs AutoFixture and XUnit2)

Install-Package xunit.runner.visualstudio
(Test runner for xunit)

Install-Package xunit

https://github.com/djhmateer/githubscratch/tree/master/MaybeTest2

| | # 
# Monday, 14 July 2014
( Resharper | Xunit )

Resharper Manage Extensions

image

| | # 
# Thursday, 12 June 2014

http://www.manning.com/seemann/

“I think Dependency Injection is like sauce béarnaise.  It’s assumed to be difficult and so few employ it”

DI is a set of software design principles and patterns that enable us to develop loosely coupled code

http://blog.ploeh.dk/2014/06/10/pure-di/ – an updated article on Constructor Based DI

Overview

2.5 years it took Mark to write this book.  It is concise, yet deep.  I’ve done an hours overview of the book, and looked at the source code (which doesn’t compile nicely in VS2013 but am sure will be ok).  It looks like a book which is much more than an DI book, and covers ‘good code’.

A DI Tasting Menu – 1.1 Writing Maintainable Code

DI may seem like a rather backward way of coding – there is much FUD (Fear, Uncertainty and Doubt) involved.  We must learn about the purpose of DI:

Writing Maintainable Code

Ultimately the purpose of programming is to deliver working software as efficiently as possible

You’ll find yourself maintaining and extending code

One of the ways to make maintainable code is through loose coupling

  • Deliver working software efficiently
  • Write maintainable code
  • Loose coupling (makes code extensible which makes it maintainable)
  • DI enables loose coupling

Hairdryers and Plugs

Through the use of sockets and plugs – a hair dryer can be loosely coupled to the wall outlet

  • Replace 1 end without changing the other
  • Liskov Substitution Principle – replace one implementation of an interface with another without breaking client or implementation
  • If unplug from wall, neither should break down.  “Null Object design pattern”

UPS

Way of intercepting one implementation with another of the same interface is known as the Decorator design pattern

Power Strip

Composite design pattern

Power Adapter

Adapter design pattern – match 2 related yet separate interfaces

Hello DI

In c:\dev\test\hellodi  page 46

class Program {
    static void Main(string[] args) {
        IMessageWriter writer = new ConsoleMessageWriter();
        var salutation = new Salutation(writer);
        salutation.Exclaim();
    }
}

public interface IMessageWriter {
    void Write(string message);
}

public class ConsoleMessageWriter : IMessageWriter {
    public void Write(string message) {
        Console.WriteLine(message);
    }
}

public class Salutation {
    private readonly IMessageWriter writer;

    public Salutation(IMessageWriter writer) {
        if (writer == null) {
            throw new ArgumentNullException("writer");
        }

        this.writer = writer;
    }

    public void Exclaim() {
        this.writer.Write("Hello DI!");
    }
}

2014-07-08 07.46.36

The Salutation class depends on a custom interface called IMessageWriter, and it requests an instance of it through it’s constructor.

The ConsoleMessageWriter class wraps the BCL Console class.  This is a simple application of the Adapter pattern as we are getting 1 Interface to work with another.

“You may be wondering about the benefit of replacing a single line of code with two
classes and an interface with a total line count of 11, and rightly so. There are several
benefits to be harvested from doing this.”

“In this example, DI adds an overhead of 1,100%, but, as complexity increases from one line of code to tens of thousands, this overhead diminishes and all but disappears.”

Benefits Gained from Loose Coupling

  • Late binding
    • Services can be swapped with other services
    • Valuable in standard software but perhaps less so in enterprise where runtime env is well defined
  • Extensibility
    • Code be be extended and reused in ways not planned for
  • Parallel Dev
    • Code be be dev’d in parallel
    • Valuable in large complex applications
  • Maintainability
    • Classes with clearly defined responsibilities are easier to maintain
  • Testability
    • Classes can be tested

Late Binding

static void Main(string[] args) {
    //IMessageWriter writer = new ConsoleMessageWriter();

    // Late binding - using reflection to create instance of IMessageWriter
    // without knowing concrete type at compile time
    var typeName = ConfigurationManager.AppSettings["messageWriter"];
    var type = Type.GetType(typeName, true);
    var writer = (IMessageWriter) Activator.CreateInstance(type);
        
    var salutation = new Salutation(writer);
    salutation.Exclaim();
}

Extensibility

Want to add security by only allowing authenticated users to write messages.  So can add the feature without changing any of the existing features.

Decorator - way of intercepting one implementation with another of the same interface

Decorate the old ConsoleMessageWriter instance with the new SecureMessageWriter class.  The salutation class is unmodified because it only consumes the IMessageWriter interface

// Decorator - way of intercepting one implementation
// with another of the same interface
public class SecureMessageWriter : IMessageWriter
{
    private readonly IMessageWriter writer;
       
    public SecureMessageWriter(IMessageWriter writer){
        if (writer == null) {
            throw new ArgumentNullException("writer");
        }
        this.writer = writer;
    }

    public void Write(string message){
        if (Thread.CurrentPrincipal.Identity.IsAuthenticated){
            this.writer.Write(message);
        }
    }
}

and call it differently

IMessageWriter writer = new SecureMessageWriter(new ConsoleMessageWriter());
var salutation = new Salutation(writer);
salutation.Exclaim();

2014-07-08 07.46.50

Loose coupling enables you to write code which is open for extensibility but closed for modification.  Open/Closed principle.  Only place where you need to modify the code is at the app’s entry point – we call this the composition root

Parallel Development

SecureMessageWriter and ConsoleMessageWriter don’t depend on each other so could be dev’d in parallel.  All that is needed is a common interface

Maintainability

As the responsibility of each class becomes clearly defined and constrained, maintenance becomes easier.

Single Responsibility Principle – each class should have only a single responsibility

Adding new features becomes simpler because it’s clear where changes should be made.  More often than not, we don’t even need to change existing code, but can add new classes, and recompose the app.  This is Open/Closed Principle again

Testability

Test Doubles – implementations of dependencies that act as stand-ins for real or intended implementations

  • Stubs
  • Mocks
  • Fakes

Ctrl U L – Run all unit tests in sln (R#) – and auto display window
Ctrl U D – Debug unit test
Ctrl U R – Run unit test(s)

public class SalutationTests {
    [Fact]
    public void InjectedMessageWriter_Exclaim_WriteCorrectMessage() {
        var writerMock = new Mock<IMessageWriter>();
        var sut = new Salutation(writerMock.Object);
            
        sut.Exclaim();

        // Verify Salutation.Exclaim method has passed correct message to injected
        // Writer by calling the Write method
        writerMock.Verify(w => w.Write("Hello DI!"));
    }
}

Interesting tests for his SecureMessageWriter on identity

Seams

We have a seam between ConsoleMessageWriter and Salutation

Stable Dependencies

  • Class or module already exists
  • Expect that new versions won’t contain breaking changes
  • Never expect to have to replace the class or module

Most types in the BCL as stable.  DI containers.  Specialised libraries. 

Volatile Dependencies

Introducing seams is extra work

A dependency should be considered volatile if any of the following are true:

  • Set up and configure a runtime environment eg a db.  We hide the db behind a seam, so can replace it by automated unit tests.  Message Queues, web services, file system
  • Dependency doesn’t exist yet
  • Dependency isn’t installed on all machines eg expensive 3rd party library
  • Dependency contains nondeterministic behaviour eg random numbers, date and time

DI Scope

We break up responsibilities into different classes.  One responsibility we take away from classes is the task of creating dependencies.

SRP – classes should only deal with their given area of responsibility without concerning themselves with how the dependencies are created

Object Composition

This is often the foremost motivation for introducing DI.

image

Modules can be composed into applications.  Only aspect discussed in Martin Fowler’s original article in 2004 (IoC and DI pattern)

Lifetime Management

What is objects want to share an instance of another object eg a db connection

Interception

Can modify a dependency before passing onto the class consuming them eg SecureMessageWriter above.  Example of decorator pattern.  This is moving along towards Aspect-Oriented Programming.

With interception we can apply Cross-Cutting concerns eg logging, auditing, access control, validation etc..

DI in 3D

  • Object composition (DI started out as a series of patterns aimed at solving this)
  • Object lifetime
  • Interception

Summary

DI is the best way to enable loose coupling – an important part of maintainable code

The benefits we can reap from loose coupling aren’t immediately apparent – they become visible over time as the complexity of the code base grows.

DI must be pervasive.  You can’t easily retrofit loose coupling onto an existing codebase

| | # 
# Wednesday, 24 July 2013
( F# | Unit Testing | Xunit )

New project. F# Library
Get rid of script file

image
Add in xunit

Xunit

http://blogs.jetbrains.com/dotnet/2013/01/resharper-plugins-for-unit-testing-mspec-xunitnet-and-silverlight/

http://xunitcontrib.codeplex.com/releases – need this plugin for R#

image
Ctrl U L – Run all Unit Tests in solution

| | #