Luke Warren Dev
Software Development Tips and Stories When I feel Like It

Your Code Sucks and Other Political Statements

There is no secret sauce or trick you haven't got around to learning to start unit testing. Your code just sucks

Your Code Sucks and Other Political Statements

OK I have got your attention. Good!

There are too many devs going around that think that unit testing was some dark art that they never learned, a waste of time or they just need some of that special sauce. Sorry folks but the reality is that unit testing is not the problem, it is your code.

With that said, do not fret! In this article I will show you a few simple tricks to get from sucky code to ... erm.. not sucky code?

Anyway, let's start with a snippet:

This code is based on a certain politician in South Africa. For non-saffas, he owed some money and needed to pay it back.

using PayBackTheMoney.Services;
using System;

namespace PayBackTheMoney
{
    public class Payer
    {
        public bool TryPayMoney(DateTime timeToPayBackTheMoney, bool canDelayProcess)
        {
            if (!canDelayProcess && DateTime.Now >= timeToPayBackTheMoney)
            {
                // Damn, have to pay
                var payer = new MoneyPayerService();
                payer.Pay(7000000M);

                // Send Thuli email
                var notifications = new NotificationService();
                notifications.Send("jacob@anc.gov.za", "thuli@madonsela.gov.za", "I pay bak moneyies.\r\n Love, Jacob");
                return true;
            }

            // "HA HA HA! "Nkandla"" HA HA HA
            return false;
        }
    }
}

Think the above code is good? It isn't. Think it is unit testable? You guessed it, it isn't!

Why? A unit test by its very definition is a method that tests a very small piece of logic in isolation. It should not rely on it's dependencies to be operational and in a certain state to be tested. Those are called integration tests.

The above is littered with concrete dependencies which makes it impossible to unit test.

Have a look again at the code. This time I have commented every issue:

using PayBackTheMoney.Services;
using System;

namespace PayBackTheMoney
{
    public class Payer
    {
        public bool TryPayMoney(DateTime timeToPayBackTheMoney, bool canDelayProcess)
        {
            // We are relying on the DateTime.Now property to return the current DateTime from the system clock
            // To test this we would need to set the clock on the PC we are using every time we want to test. What a pain!
            if (!canDelayProcess && DateTime.Now >= timeToPayBackTheMoney)
            {
                // We are using the new keyword to create an instance of our money payer service. This means that we have a concrete dependency on this class
                // Who knows what the money payer service might be dependent on to perform its "duties".
                var payer = new MoneyPayerService();
                payer.Pay(7000000M);

                // Again, as above. Newing up the NotificationService ties us to it and means that we can't test this method in isolation from its dependencies
                // Point is, we can't swap it out with a fake in our test code. We would have to make sure that an SMTP server was running!
                var notifications = new NotificationService();
                notifications.Send("jacob@anc.gov.za", "thuli@madonsela.gov.za", "I pay bak moneyies.\r\n Love, Jacob");
                return true;
            }

            return false;
        }
    }
}

As you can see, this code is using the new keyword to create services that it needs to use. This is a massive issue when it comes to unit testing because to test the Payer method you need to have both an operational NotificationService, MoneyPayerService and you would need to set your computer's clock to a new date every time you needed to test under that particular instant in time. Hear that? Those are alarm bells ringing in your ears.

Don't worry dear reader, you are not completely stuffed. We can actually very easily fix this code. Simply put, we need to make our Payer class rely on abstractions rather than concretions. This means creating interfaces to describe what each of our dependencies need to do. I like to refer to them as contracts and they will act sort of like base classes.

Interfaces are like an abstract class, except they have absolutely no implementation. Like an abstract class though, classes can inherit from them and we can then use polymorphism to handle calling the right method at the right time.

Lets now look at our fixed up class:

using DecoupledPayBackTheMoney.Contracts;
using DecoupledPayBackTheMoney.Services;
using System;

namespace DecoupledPayBackTheMoney
{
    public class Payer
    {
        private readonly IMoneyPayerService _payer;
        private readonly INotificationService _notificationService;
        private readonly IDateTimeProvider _dateTimeProvider;

        /// <summary>
        /// Here we are inverting our dependencies by letting the caller pass them in
        /// </summary>
        public Payer(
            IMoneyPayerService payer,
            INotificationService notificationService,
            IDateTimeProvider dateTimeProvider)
        {
            _payer = payer;
            _notificationService = notificationService;
            _dateTimeProvider = dateTimeProvider;
        }

        /// <summary>
        /// Lazy-man's Dependency Injection
        ///
        /// This is our public parameterless constructor. It takes care of passing in our concrete implementations.
        ///
        /// Ideally you would be using IoC framework for this like Ninject or AutoFac
        /// </summary>
        public Payer()
            : this(new MoneyPayerService(),
                  new NotificationService(),
                  new DateTimeProvider())
        {
        }

        public bool TryPayMoney(DateTime timeToPayBackTheMoney, bool canDelayProcess)
        {
            DateTime now = _dateTimeProvider.GetCurrentDateTime();
            if (!canDelayProcess && timeToPayBackTheMoney <= now)
            {
                // Damn, have to pay
                _payer.Pay(7000000M);

                // Send Thuli email
                _notificationService.Send("jacob@anc.gov.za", "thuli@madonsela.gov.za", "I pay bak moneyies.\r\n Love, Jacob");
                return true;
            }

            // "HA HA HA! "Nkandla"" HA HA HA
            return false;
        }
    }
}

Things to note:

  • We have defined interfaces for each of our dependencies.
  • Each of our services in turn inherit from these interfaces.
  • This means that our services HAVE to implement the methods defined in the interfaces.
  • Our class now relies on these abstractions rather than concretions
  • We inject our dependencies via the constructor using what is called the strategy pattern
  • Instead of needing proper versions of each of our services to test, we could now pass some fake versions of these services which do not rely on things like the system clock or a mail server
  • We can now unit test our payer class!

Note: For simplicity, we are using what is known as "poor man's dependency injection". Ideally you would rather use an inversion of control framework like Ninject or AutoFac to handle this for you so that you are even more loosely coupled.

The full source code of both the rubbish code and the better decoupled code can be found on Github. Poke around and if you have any questions leave a comment below.

Image used is from The South Africa http://www.thesouthafrican.com/jacob-zuma-announces-his-resignation-cabinet-left-jobless/


Click here to comment

NPM for .NET Developers

NPM is essentially to JavaScript what Nuget is to .NET.

NPM for .NET Developers

What is it?

N - Node
P - Package
M - Manager

NPM is the package manager that comes bundled with Node. It is the defacto package manager for JavaScript.

NPM is essentially to JavaScript what Nuget is to .NET.

Why should we use it? Isn't Nuget good enough?

No. Nuget might have some of the commonly used JavaScript libraries but Microsoft actually advises people use npm or similar for managing their client-side dependencies.

Besides from that, Nuget installs scripts all over your project making things messy and difficult to manage.

NPM is where 99% of all the JavaScript libraries live. If you find a library that is not on NPM please email me at luke@fake-email-address.com

How to get it?

Just go to the Node download page and install the MSI. This will install both Node and NPM along with it

https://nodejs.org/en/download/

Note - You cannot download NPM directly

How do I interact with NPM?

The best way is just via the command line. This might seem daunting at first but there are only a few commands to learn

What is the package.json file?

The package.json file is where NPM stores the dependency graph for the given folder.

It is not mandatory but is advised so that you do not have to source control your dependencies.

Think of this file as the equivalent to the packages.config that Nuget uses.

Creating a package.json file is super easy via the npm init command.

Example package.json:

{
  "name": "kill",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "liberty",
  "license": "ISC"
}


Where are the dependencies files stored?

All dependencies are stored in the node_modules folder

How do I install a package?

1. You will first want to create the package.json file (if you don't have one already).

Enter npm init into your command terminal and follow the prompts. Some things you can just leave blank and defaults will be used.

2. Find the package you want to install.

Most packages are pretty well named but it is worth checking on the NPM website to confirm the exact name of the package you wish to install.

Website: https://www.npmjs.com/

3. Install the package

Enter npm install <<name_of_package>> --save into your terminal to install the package.

For example, to install jQuery we would enter npm install jquery --save. This will install the latest version of jQuery.

Notes

  • --save indicates that you want to add the package to the package.json file.
  • install can be shortened to just i. Example: npm i jquery --save

How do I uninstall a package?

Uninstalling a package means 2 things:

  1. Remove the package and it's dependencies from node_modules
  2. Remove the entry from package.json

So to uninstall we simply enter npm uninstall <<name_of_package>> --save into our command window.

For example, npm uninstall jquery --save

I pulled down a project and the node_modules folder is missing!

Because all packages are stored in the package.json file we don't actually need to save the node_modules folder in source control.

Just enter npm install to restore all the packages for the given folder you are in.


Click here to comment

Getting Started with Angular

Making the move to Angular (2 +) from AngularJS can seem quite daunting. This article will seek to demystify that process.

Getting Started with Angular

Names have changed

With the new version of Angular you might be tempted to refer to it as Angular 2 with the former as Angular 1. That would be a mistake. Angular is now on version 4 and that number is set to move fast now that Angular will be following Semver.

You should refer to Angular 1.x as AngularJS and Angular 2+ as Angular.

Languages have changed

You have probably heard about Angular's switch to Typescript as the preferred programming language. This, though, is nothing to be afraid of if you already have experience in JavaScript and a statically typed language such as C#.

Typecript is really just a superset of JavaScript, adding typing, object orientation and other useful things that you would find in the newer versions of JavaScript, like classes.

It will take a bit of getting used to but, once you have, you will love it.

Why should I care about the Angular, can't I just stick with AngularJS

Well, no, you can't.

Support for AngularJS is being dropped which is a big issue. On top of that, developers are going to be moving their efforts into building components for Angular. Meaning, your application is basically already outdated and will only have access to old directives and libraries.

Aside from that, Angular adds all sorts of performance enhancements and is just so much easier to organise and reason about through it's web component and module architecture.

How do I get started?

Firstly, go read the Tour of Heroes tutorial. Just do it, it covers all the basics and will take you a few hours.

Secondly, install the Angular-CLI.

Note - Your will need to have Node and NPM installed for this

This is done by opening a command window and simply running: npm install @angular/cli -g

The -g part installs the CLI globally and will make it available on your PATH.

Next, cd to a directory where you want to create an angular app and run: ng new your-app-name

Tadah! You now have an Angular app.

Want to see it?

Simply type npm start or ng serve and navigate to localhost:4200

Note - npm start really just runs ng serve. Take your pick

Conclusion

It really is super easy to get up and running with Angular. In future articles I will break down some of the basics but the Tour of Heroes tutorial does an excellent job should you not wish to wait.


Click here to comment

CI and CD Pipeline for Rework

My first YouTube Video

CI and CD Pipeline for Rework

Short post here.

Just wanted to notify my loyal reader base of a YouTube video that I have put up showing how the continuous integration and continuous delivery pipeline works for Rework. The video was filmed via live stream on my LiveCoding.tv channel but I also uploaded it to YouTube

So, without further adieu:



Click here to comment

Introducing the Model Builder - You Don't Need Automapper

This post is quite simple. You don't need Automapper, all you need is a model builder.

Introducing the Model Builder - You Don't Need Automapper

Now I am a big fan of "don't reinvent the wheel" but at times we as developers need to learn where to draw the line. In this article I will show you a very simple pattern that gives you more control and avoids needing to bring in yet another dependency - AutoMapper.

Disclaimer: I like and use Automapper in many of my projects and will continue to. It is a great library but sometimes you just don't need it.

Example ModelBuilder

All our model builder class does is either create a Model class from its entity/domain class equivalent OR parse a Model class back to a entity/domain class.

public class ModelBuilder
{
    public ProvinceModel Create(Province province)
    {
        Require.NotNull(province);
        Require.NotNullOrEmptyOrWhitespace(province.Name);

        return new ProvinceModel
        {
            Id = province.Id,
            Name = province.Name
        };
    }

    public Province Parse(ProvinceModel model)
    {
        Require.NotNull(model);
        Require.NotNullOrEmptyOrWhitespace(model.Name);

        return new Province
        {
            Id = model.Id,
            Name = model.Name
        };
    }
}

Wondering what that Require stuff is? Those are just some handy methods contained in the Rework Nuget Package (yes, this is a shameless plug).

ModelBuilder In Action:

I usually either inject my model builder in the constructor for the class that needs to use it, or just instantiate it right there in the constructor. The later does make it a concrete dependency rather than an abstraction but sometimes this makes sense IMO.

You could, either create a model builder for each entity-domain relationship you have or just put them all in one. You are reading this blog so I will assume that you are smart and can figure out what you prefer ;).

For completeness, here is how you actually use the thing:

    public ProvinceController(IProvinceService service)
    {
        // Init my service and create my model builder
        _service = service;
        _builder = new ModelBuilder();
    }

   public object Post(ProvinceModel model)
    {
        Province province = _builder.Parse(model);
        _provinceService.Create(province); // My "service" is creating the province in the DB
        return _builder.Create(province);
    }

Click here to comment

2 Simple Steps to Start .NET Development

After recently taking on board a .NET newbie at work, it became apparent that it is not obvious what hardware and software you need to become a .NET dev

2 Simple Steps to Start .NET Development

In this article I will be talking about what you need to start developing for the full .NET Framework.

Disclaimer

While following these steps will just about get you there to develop for .NET Core, you can actually use a much simpler setup if only targeting .NET Core.

For more info, on .NET Core head on over to this article. Have a browse around the site for all sorts of other information too.

Step 1 - Get some hardware

To do .NET development using the full .NET framework you are going to need a windows computer. Ideally something with decent specs and a bit of RAM. You will be spending a lot of time in GUI RAM heavy tools.

My current machine is an Acer Aspire S7 Ultrabook with an Intel Core i7 CPU, 8 Gigs RAM and a 256 SSD. You don't need something this powerful but I'd say an i5 with 8 Gigs of RAM is probably the minimum specs you want to run.

Step 2 - Install some software

You only really need to install one bit of software to start programming in .NET and that is Visual Studio. Visual Studio is an IDE that you will pretty much find yourself living in during most of your development.

At the time of writing, I am using Visual Studio 2015 Enterprise but you will get on just fine with the free Visual Studio Community Edition. You can download Visual Studio from here.

Optional Step 3

Web Development

If you are wanting to also build websites using the popular ASP.NET framework you are also going to need to enable some windows features.

Go into you programs and features settings and enable Internet Information Services (aka IIS) as well as the ASP.NET framework.

Example of what I have enabled:

What  features I have enabled

Database

You will probably find yourself needing a database at some point or another. Generally speaking, you will probably be using Microsoft SQL Server although you could get on just as well with MYSQL or some other relational database technology.

Scott Hanselman has a great blog post on installing MS SQL Server as well as the Management Tools that will make your life a bit easier - both are free.

Comment below if you have any questions.


Click here to comment

New Version of Rework Available

My helper is slowly becoming something useful

New Version of Rework Available

Happy to make a quick announcement that Rework is slowly getting useful!

A new version is out and features some more handy string functions for truncating strings. The library is still very light but does help eradicate some silly boilerplate code

Check it out on Nuget and Github or simple install it with the Nuget Package Manager command Install-Package Rework


Click here to comment

C# 6: Shorten all the things with expression-bodies

Let's see how you can use expression-bodies

C# 6: Shorten all the things with expression-bodies

Let's see how you can use expression-bodies to make your code a lot shorter and more readable.

If you are still writing code like this:

public string FullName 
{ 
    get 
    { 
        return String.Format("{0} {1}", First, Last); 
    } 
}

You really should read my string interpolation post , and write it like this:

public string FullName 
    {
         get 
         { 
               return $"{First} {Last}"; 
         }
     }

The thing is, it gets even better with expression-bodies:

public string FullName => $"{First} {Last}";

That is all.


Click here to comment

C# 6: Get rid of String.Format with Interpolated Strings

So I don't know about anyone else but I am loving Visual Studio 2015 and C# 6.

C# 6: Get rid of String.Format with Interpolated Strings

So I don't know about anyone else but I am loving Visual Studio 2015 and C# 6.

My current favourite feature is the string interpolation. Yes, yes, I know that PHP (and others) have had this for ages but here it is...

Often we would have to do stuff like this:

string first = "Luke"; 

string last = "Warren"; 

string fullName = String.Format("{0} {1}", first, last); 

What a pain!

Now, with string interpolation, we can shorten that last statement to:

string fullName = $"{first} {last}";

Simple but very handy! Just remember the dollar sign before the string. VS will show some nice syntax highlighting to help you out too.

More info: https://msdn.microsoft.com/en-us/library/dn961160.aspx


Click here to comment

Moving Blog from Wordpress to Umbraco

I have finally got around to porting my blog to Umbraco!

Moving Blog from Wordpress to Umbraco

I know I have said in the past that WordPress was probably the way to go for blogging, but in my recent whirlwind romance with Umbraco, I decided to port my blog over.

The main reason was based on the fact that I am much more comfortable in the ASP.NET based Umbraco and hope to make regular feature additions as the blog evolves. Although that is possible with Wordpress, I'd rather stick to my strengths.

In an effort to make my life easier I am also "outsourcing" some other sections of the site, such as the about and contact me sections. This means that the old and rather half-arsed vanilla MVC site that used to occupy this domain has been put down (in a humane and gentle fashion of course).

This site is fully geared towards blogging. The topics will be mainly programming related as usual but you might hear the occasional rambling/rant about the latest goings on in rugby (despite my best effort not to).

All you need to know about me is available via the links in the header of every page. The best place to find out more about me professionally will be via my LinkedIn page. To get hold of me, send me a message via LinkedIn, email or Twitter.

Over the course of the next few weeks I will be moving over my old blog content and killing my wordpress.com site. I will make a post notifying everyone when that takes place although I am sure neither you nor I will miss it.

For those wondering you can find my old blog at lukejkw.wordpress.com

Thanks for reading


Click here to comment