Wednesday, May 08, 2019

Clean coding Tips: Isolation

It seems to be by default that classes, methods, etc are created with the public access modifier.

This is not actually the case, the default is internal class/private members, but public seems to be the de-facto choice by a lot of developers.

If you're creating a public class - you have a big responsibility. Your code can now be used by anything else in the application, or even outside it. This means if you change the internal working of it, you will affect everything that uses it - and you have no control over what that is. This means a couple of things. 

Naming is super important

Naming of public classes and methods and their expectations should be crystal clear. Don't rely on comments to convey intentions. It must be highly obvious what the class is for, what it does, and how method parameters are used. It should be specific and adhere to the Single Responsibility Principle - one reason to change. If someone comes along and adds a parameter to one of your methods to get it to do something else, this is an indication that the class's purpose was not clear enough.

If the naming is not clear, the purpose gets diluted, and the class will be modified away from its original intentions. This causes code to bloat and become more prone to bugs.

Tip: This is yet another reason to avoid "generic static helpers"!

Tests are the documentation of a contract

If your classes or methods are public, tests need to cover every possible way that the code can be used - every single path. What this means is that anyone using the code will know exactly what is expected of it because its functionality is documented by tests. Any usage of the code will already be covered by a test.

If you don't create tests, anyone can come along and change this code which can then affect any number of consumers.

Don't make life hard for yourself

Don't want this responsibility? Simple: Don't make your classes and methods public. Of course internal members should always be tested and code should be named well. But these issues take on less importance if the code is isolated.

Go with the lowest access first and only open it up as and when you need to, When you do open it up, make sure that it does what it says it will, and it is fully tested. The important thing to remember is that when a class is public, it increases its exposure, which allows it to be coupled with more code. This is a significant cause of spaghetti code and regression issues as the code is maintained.

Keep code restricted to where it is needed. If it needs to be public, it needs to be incredibly robust.

Monday, March 26, 2018

Ways to Spot Single Responsibility Violations

Classes should only have one reason to change. We should attempt to increase cohesion between things that change for the same reason, and decrease the coupling between things that change for different reasons. Classes should do one thing and one thing well.

Violations of the Single Responsibility Principle can cause code to be difficult to test and maintain, and can make it easier for bugs to manifest.

There are a few symptoms of SRP violations which can give warning signs of these issues.

Large classes/methods

Obviously large classes and methods do not always point to SRP violations as there may be a requirement for a significant amount of logic. However, it is usually a good sign.

Large methods are more likely to point to an SRP violation than large classes, or at least too much cyclomatic complexity. You'll become aware of this when you attempt to cover the method with test cases, and realise there are excessive test combinations required.

Too many injected dependencies

While this may depend a lot on how you set up your services, lots of injected dependencies may suggest that the class is doing too much, and may be violating SRP.

Too many tests per class

If a class has too many tests, or the tests need to change often, this is an indication that there may be too much complexity, too much setup, and this may point to an SRP violation.

Described with and/or, or encompassing words such as "manager"

This is a sure sign that your class or method is doing more than one thing. For example: a method called CreateOrEditRecord() or a class called "InvoiceHandler" are red flags, and should be investigated.

Logic in Views

Logic in your front end almost always means that you are violating SRP, because a view's responsibility is to render an output. As soon as you have two pieces of logic in a view, it's unlikely they'll be for the same reason, because they'll be for different elements on the page. This immediately makes it impossible to unit test the view.

Also, because of the standalone nature of views, there's a good chance you'll have to violate DRY in another view.

Move that logic up to a model, a controller, a helper, or a service where it can be properly unit tested.

Tuesday, September 20, 2016

Hololens: What Kind of Applications Can We Build?

The creative potential of Hololens and "Mixed Reality"is huge. There are a wide variety of applications we can develop for it.

I believe the demos shown so far are barely scratching the surface of what we can do with the Hololens. Once the imagination of the development community warms up, we're going to see world changing ideas. Industries will be turned upside down, lives will be changed, and millionaires will be made.

I'm going to make some assumptions on its abilities, but try and highlight some of the many directions we can take in creating for the interface of the future.

Presence Sharing

One of the most interesting uses for the Hololens is allowing others to share your experience, and interact with it. This opens up many prospects for communication and collaboration in virtually every industry.

Think about how cool GoPro cameras are and what we're able to do with them. Now imagine seeing the video live and being able to interact with it.

This particular feature also has plenty of promise for gaming, with users interacting with the same virtual objects, the same reality, or in the same game area.

Reality Overlays

Probably the main purpose of Hololens is its ability to overlay the imagined onto the real. We have seen some examples of this, and there is so much more to come. Interfaces will probably make up the bulk of these overlays, and there is plenty of scope for variety in how these work. But the possibilities go much further than just interfaces.

We've seen game characters and levels merge with the real world. What about augmenting our environment with photo-realistic people, new fixtures and furniture, or movie scenes? Or changing our atmosphere with movement, light, and sound? Virtual Reality might do this better. But having the real world still in view gives a certain edge to the atmosphere.

Gesture Controlled Augmentations

The use of gesture controlled interfaces might have been around for a while, but it takes on a new potency in the realm of artificial reality. Rather than interacting with things on a screen, you'll now be able to "physically" interact with "objects" in your world.

And while the recognisable gestures are still quite simple, this will only get more complex with time. As the Kinect technology gets better at recognising more fingers and more intricate movements, it will allow for more advanced control in much the same way as musical instruments or crafts.

Reality Recognition

Let's not forget that the Hololens cameras can be used to process the real world and the things in it. Measuring distances, identifying objects, detecting movement and more can all lend to the interaction.

How far can we take this real world processing? Imagine, tailoring your experience based on what the Hololens sees, such as popping up an information snippet of a visible landmark, finding your friends in a crowd, or identifying danger.


Like gesture controls, voice finds new opportunities in this context. It's part of the experience, narrating what you see, talking over the internet, recognising commands, sometimes recording. What else?


There are probably several more Hololens abilities that I've missed, so please leave a comment if you can think of any. Each of the items above has the potential for some groundbreaking new applications. Combine two or more concepts and the possibilities increase exponentially.

We just need to start thinking differently about what we can do. Rather than extrapolating our current computers and software to this new paradigm (which we should still do), we should try to think about what new possibilities all these new capabilities afford us, separately as well as combined.

I didn't want to get too deep into these possibilities, I really just wanted to highlight them, to get people thinking about how they might use each of them.

It'll probably take a few years for the world to realise what Augmented Reality can do for it. But all ideas are built on other ideas.

We're just getting started.

Thursday, December 17, 2015

Microsoft Certified Solutions Developer!

After 3 years, 3 exams, and an excessive amount of study I have achieved the Microsoft Certified Solutions Developer - Web Applications certification.

I realise that many people don't put a huge amount of emphasis on exams, valuing real world experience instead. But I have found that what I learned studying for these exams has been extremely valuable to my profession, helping me make more informed decisions in my day to day work.

There is no substitute for real world experience, but real world experience leaves a lot of gaps and doesn't always teach the best habits. The exams have enabled me to fill in these gaps and develop a real technical proficiency which I may not have had without them.

Born to Learn just posted this blog talking about a recent study which found 4 advantages certified staff have over non-certified staff, there are some interesting findings!

Tuesday, October 27, 2015

Amazing Things You Can Do With Azure Storage Queues

Load Balancing and Workload distribution

Queues can be used to organise the distribution of a workload across multiple processors.

A common technique is to post messages to a queue which are a key to a task which needs to be performed, and have multiple worker processes pick these tasks from the queue to perform in parallel.

This can be combined with other storage mechanisms to perform complex tasks. Say you were trying to render an animation. The queue could be loaded with keys, which point to an entity in Table storage. This entity could contain the Url of an image stored in blob storage. A worker process would pick up the message from the queue, reference the entity from the table and download the image from blob storage. It could then perform compute intensive tasks on the image while other worker processes picked up other images.

In this way, cloud storage can be used to augment worker roles and perform powerful parallel operations.

Asynchronous Processing and Temporal Decoupling

It might sound like something you do with a sonic screwdriver, but temporal decoupling simply means that senders and receivers don't need to be sending and receiving messages at the same time. With messages stored on the queue, they can be processed when the receiver is ready to do so, and the sender is not held up.

This can be useful for performing background tasks which are not critical to the main operation of a program, for example, a web application, rather than providing a slow response, can just queue up a thumbnail generation process and respond to the user quickly. A game, which requires the utmost UI responsiveness, might store replay data asynchronously using queues.

Thursday, August 20, 2015

NuGet Like a Boss: Part 1 - Don't Check in Packages

After suffering like many with so many Package Restore woes in my projects I decided to make notes on the best way to deal with Nuget packages.

Ignore the packages folder

Not doing this means you check in the packages which are huge. This is annoying and kind of defeats the purpose of Nuget. When you ignore (and therefore don't check in) your packages folder, anyone getting your source code can run package restore on the solution and Nuget will download the packages automatically.


First, add a file named .tfignore. This may require some Command prompt renaming as some set ups don't like files beginning with a dot. When you get past this annoyance, open the file in notepad and enter the following:


That tells TFS to ignore the packages folder. For some bizarre reason, this doesn't include the respositories.config file. You'll need to add a second line as follows:


You'd think this would be it, but you may notice that your packages folder is already in your Pending changes. To get around this, create a folder called .nuget (command prompt trickery may be required) and in there create a file called NuGet.config. It must go in this folder, even if you have another NuGet.config at solution level. Enter the following text:

<?xml version="1.0" encoding="utf-8"?>
    <add key="disableSourceControlIntegration" value="true" />

This should ensure that your packages stay out of source control.

Finally ensure that .tfignore and NuGet.config are added to source control so that these settings should apply for anyone using the project.


Be aware that the .tfignore file may not work if someone has already checked in the packages folder. Delete this from source control and you should be good.

Monday, August 10, 2015

Developing for the Cloud - An Introduction

When you create a web application for the cloud, there are many things that need to be done differently. It's not just a case of saying "I'm doing cloud" and all you're really doing is putting it on someone else's VM. Doing this, the costs are much higher than if the application is designed with cloud in mind. This might be fine from an infrastructure point of view, but the cloud can have profound impacts on development from the ground up.

Azure allows us, and also forces us, to engineer our applications completely differently.

Forces? Well, this is because when you're hosting in an App Service plan, you're billed based on compute time and resource usage. This forces you to write more efficient code. You can't just write code that performs unnecessary operations and get away with it - the efficiency of code now directly translates to dollars. This demands that you think twice when writing code, espcially loops, to ensure you're being efficient. Caching becomes a major priority so that you're not hitting a database unless you absolutely have to.

With the weight of costs, you need to start thinking about more efficient ways of doing everything. Luckily Azure offers many services to help increase application efficiency. The most basic example is storing images and other static resources in Blob storage. This is fast, lightweight, and extremely cheap.

Scripts and CSS can be offloaded to localised CDNs. This also increases speed and significantly decreases cost.

Some data can shift from SQL to NoSQL models such as Table Storage, DocumentDB, or Graph data with its powerful relational features. An application might use all of these data types simultaneously for different purposes. For example, a shopping cart site might use SQL to store a user's identity information, Table storage to manage their shopping cart, DocumentDB to store product details, and Graph data to build "You might also like" links.

Need to run asynchronous/background tasks such as generating thumbnail images? Use Web jobs to run scripts, executable, and third party libraries completely outside of the typical web application Request/Response lifetime. Use queues to decouple logic from the main workflow, or use multiple worker threads to perform parallel processing.

We can also take advantage of Azure Search (powerful search services), Service bus (host web services locally but expose them via the cloud), Azure machine learning (predictive analytics, data mining, and AI), and Notification hubs (push messages down to clients).

Then, we can host our applications in App Service plans (instead of Virtual Machines) and take advantage of Visual Studio Online's build and Continuous Integration features. We can also leverage elastic scaling and Application Insights.

There are many more features in Azure and more appearing every day.

To summarise, developing for the cloud is very different from building a website that will be isolated on a local server. It's a far more distributed model where separation of concerns is much more pronounced than we're used to. Developers and architects will need to think differently when designing applications.

This is just an intro to cloud features. In the future I will go into cloud architectural design patterns which allow us to design our applications to be resilient in failure-heavy environments.

Tuesday, June 23, 2015

How to Be an Organised Developer (and spend more time coding!)

As a developer your main focus is to write code. But over time, you'll find that there is a lot more to development than this. If you're not aware of this, you might one day wake up and realise that the notepad file you used for passwords and connection strings has gotten out of hand.

Being more organised from the start can help keep you focussed on coding and help you stay more efficient. If you move jobs you'll pick up a lot of information in the first few weeks, you'll want to organise it well from the start. If you stay in the same job for years, the 'other stuff' you accumulate can get messy and cumbersome.

Like good code, making an effort to organise yourself well from the start can pay dividends later on, when it comes to navigating and maintaining all your stuff. Here's a list of some of the "stuff" you'll find yourself accumulating as a developer, and how to keep it well organised.

OneNote (or Equivalent)

An essential tool for all developers.

The main thing this is useful for is storing essential information such as test data, database names, licence numbers for tools such as Resharper and Linqpad, and lists.

You can also use it for debugging information, screen grabs, functional specs, checklists and pretty much anything you can think of. OneNote allows you to organise all this quite effectively with its use of tabs and pages.

Note that by "equivalent", I don't mean Notepad++. You need your notes in one well organised and secure location (save your notebooks remotely), you don't want to have to worry about hitting "Save", and you also need to be able to paste in screen grabs, tables and other rich content. Evernote might come close but OneNote is trusted in enterprise environments which can give it the edge.

Logging Access

Pretty soon you're going to need to access logs for auditing, testing or debugging purposes. Remember to record all details in your note software.

Product Documentation/Wikis

As a developer you will probably be responsible for writing a lot of documentation. Make sure it's in an easily discoverable place and well maintained. Good code should be self-documenting, yes, but other stakeholders need to know what the code is doing from a non-technical perspective.


You'll always have a selection of really important links. This might include:

  • Product documentation/wikis
  • Test Harnesses
  • ALM tools (TFS, Git)
  • Communication tools (Sharepoint, Trello)
  • Administration tools (Timesheets, financial, personnel software)
  • Development learning materials, tutorials, blog posts, communities etc. 
Figure out the best way to organise these based on your needs and make sure they're backed up and accessible everywhere (use Chrome/Firefox Sync or a bookmarks manager).

SQL Files

Most developers will probably have a collection of SQL files of common, useful queries, for logging, basic CRUD, etc. Make sure these are in an easy to access, secure, backed up and preferably remote location.


Specifically in Web Development, tools such as iMacros can be invaluable for automating frequent tasks such as logging in to test sites or running common actions on test harnesses. Remember, keep them well organised and backed up remotely using Dropbox/OneDrive etc.

Powershell Scripts and batch files

You might also have some PC management tasks that need to be automated. Powershell is fantastic for these kind of tasks, and is becoming even more useful with the advent of DSC.

Linqpad Scripts

Similarly, Linqpad allows for frequently used code to be stored and used in a lightweight manner without all the project overhead.

Code Toolbox

Finally, all developers should have a code toolbox, or a collection of libraries and code snippets they use regularly in their projects. This is a lot to go into so I will create a new blog on it, but basically it could consist of
  • Project templates 
  • Emailing library 
  • Cloud storage library 
  • Logging classes 
  • MVC Html helpers etc
The idea is to allow for Rapid Development by having everything you frequently need at your fingertips and not having to worry about finding code for frequently performed tasks such as input forms or membership features. As I said, I'll give this topic a blog of its own soon.


Hopefully this has inspired you to ditch that pile of text files and get your administrative stuff in order. Doing so will make you more efficient and help you focus on what's really important - writing code.

How do you organise yourself? Is there anything I've missed? Leave a comment!