Coding tactics: .Net MVC

The following are some of the general guidelines I follow while coding to get a better code structure and easier test driven development. IMHO, these also make code easier to understand and debug.

  1. Do not use regions – these only hide information and are probably an indication your class is too big.
  2. Put the fields, properties and methods in alphabetical order and similarly the tests in the unit tests.
  3. Name the unit tests starting with the method name so the ones relating to same methods can be grouped together.
  4. A recommended format for naming tests is MethodName_Input_ExpectedResult. This differentiates method name, input and desired result, something other formats usually don’t. Also, all the tests for the same method are grouped together when searched for by using Resharper (Alt + \) or Visual Studio (the methods drop down on top). If the tests are put alphabetically, they will reside next to each other for the same method.
  5. Start writing unit tests with the all green (positive) condition first. This fleshes out all dependencies so the hard work is done. Now the unit test can be copied and things changed for other conditions – so work is completed quickest.
  6. Limit unit tests to assert one or two things, unless maybe if these are related to the same object.
  7. The unit tests should be guiding responsibilities of classes – Test Driven Design is a more appropriate expansion for TDD. Whenever testing a method takes too much setup and too many assertions, it’s doing too much and some if it needs to be done by another class, to be injected into the method.
  8. Do not hard code data in unit test expectations. If needed, variables should be used to check the right string/int etc is being returned. The System.Random class can be used to create random integers, doubles, or strings by using ToString() on the integer generated. The same can be extended to create random decimals if needed.
  9. Use Dependency Injection effectively – never create new instances of dependencies in methods/properties, inject them where possible.
  10. Any method which needs scrolling to read is probably too big to grok easily. An object should always tells others to do work, instead of asking for their properties and doing it.
  11. Smaller classes and methods, with less responsibilities, are usually easier to debug, especially if every class’ method validate input independently.
  12. Do not use abbreviations, name variables as per their class or utility. The class names should be per business terminology where possible, otherwise as per their utility.
  13. Private/internal methods should be avoided as their usage encourages keeping too much responsibility in a class since the method calling it is smaller. Most likely, these should be part of a new class tasked with the responsibility of what the method does. Moreover these cannot be mocked so every class calling them has to cater for what they do.
  14. ViewBag usage should be minimised/eliminated. The biggest disadvantage being no name or type safety checks, it also encourages unplanned hacks which are best avoided.
  15. Use models for all method parameters – the more specific the better. This is useful for MVC actions too. In the vast majority of cases, MVC binds them without any problem. The signature of method calls doesn’t change if the model changes and the method/action is easier to test or mock out. A whole bunch of logic can be pushed to the model which the calling class doesn’t need to know of – it can tell the model to do stuff, even passing it repositories/services etc to do work.
  16. The size of models should be an indication of complexity of the calling method/class. Too many properties/methods indicate a need to split it (and possibly the calling class/method) into multiples.
  17. At a more advanced level, the use of models allows use of custom model binders, which can add a whole level of logic before the controller is involved, like redirecting based on model properties – I’m looking at you Multi-Tenancy. The result, the controller is cleaner and more specific.
  18. Still need more reason to use models? For MVC controller actions FluentValidation validators can be attached to models and it’s integration with MVC can make sure that the validator is called automatically by the controller before the action. So the validation logic can be pulled into different classes, another responsibility off the controller! Tie this up with Dependency Injection and your custom validator can have services injected to do the validation.
  19. MVC controllers and their actions should be smallest possible. New view/condition? Create a new action or even new controller, making the calls as RESTful as possible.
  20. MVC filters provide a helpful way to take repeated pre/post action work out of controllers. Besides authorisation and exception handling, these can also allow setting of controller properties if that can be done using injected services. Coupled with well implemented Dependency Injection to provide constructor parameters, these can keep the controllers as lean as possible.
  21. Use AutoMapper to take care of converting classes to one another. For all its drawbacks, it provides a really nice way to separate concerns and take out a whole lot of distracting code responsibilities out of the controllers/service classes.
  22. When using AutoMapper, don’t utilise it’s Mapper class static methods – instead inject IMappingEngine for using the mappings and create them in profiles (classes extending AutoMapper’s Profile class) which can be automatically picked up & added on application start if DI is used well. In the profiles, use the CreateMap method available in the class instead of calling the Mapper.CreateMap static method. A good setup will also allow injecting other services into custom resolvers/converters when required for mapping.
Advertisements

Double figures run (finally)

Run on 05 Apr 2015

My 10 miles run on 05 Apr 15

For last Sunday’s run, recorded here, the route was simple, run 5 miles, run back!

It went so well I finished with nearly the exact pace I was aiming for:

Timing for my 05 Apr 15 run

My last long(er) run was half a decade ago – 14 Feb 2010 to be exact, when I managed to stumble across the finish of Liversedge half marathon:

Timing 2010 Liversedge half marathon

The timing, as mentioned in the picture, was after hitting the wall at around 8 miles mark. For the last 5 miles, it took all my will power to continue “running” (i.e. not walk) – fun times! Things didn’t get better after that. I hadn’t started recording my runs so… a few longer runs later I pulled my leg muscle, a week or two before the marathon I was supposed to run.

Distances runLong story short, I’ve not had a really long satisfying run after that, for whatever reason, as can be witnessed on my Runtastic statistics page, shown here.

This 10 miles run may not be noteworthy, but running that distance easily has given me more confidence than I ever imagined. Suddenly running a marathon is not so damn daunting.

As the pace was not taxing, even with just one energy gel I didn’t hit the wall thingy, but now I have the option to do so. If you’re not aware, energy gels are used to provide immediate energy to the body and stave of hitting the wall for as long as possible. I wasn’t aware of these when I ran at Liversedge, after all I’d run 8 miles without any problem – what could possibly go wrong!

I tried out faster paces in the gym yesterday – till 4 mins/km for a short while. It does seem I can handle a bit more this Sunday, when I run the Sheffield half marathon – hopefully a better performance to talk about.

Visual Studio project templates: a (possible) boon for micro services

During my talk on micro services at Leeds Sharp recently, it dawned on me that Visual Studio project templates are not something very well known. So here’s a quick primer on them, which can be useful for a large number of similar projects – a usual requirement for micro services. For our implementation of micro service we went down the route of using shared libraries to control their structure and make them easier to setup. This needed some custom code e.g. base repository for Entity Framework classes, wrapper for API calls etc; which was repeated for every micro service – hence a need for project templates.

Any Visual Studio project can be converted to a template by clicking File –> Export Template… This will get a pop up like the one shown below:

Project Template Wizard Start

Micro Services Project

The areas outlined in red are customisations in the above sample micro service project that are likely to be repeated in any new micro service. This includes a line that needs to be added to the NinjectWebCommon.cs file in Ninject MVC to make it work with a Web API project, the kind of project we used for micro services. These and any other customisations, including any Nuget packages etc will be included in the project template created. On clicking next we get to the final screen:

Project template wizard

This gives us the option of adding icon & preview image and some other details. The output location, outlined in red, is where Visual Studio looks for any such templates to show when getting us the new projects wizard. Click Finish and we are done. So the next time a new project is required, the new template (with the chosen icon) is visible:

Project template in action

Now we click OK after putting the name and location of our new micro service and we get the new project with the required custom items:

Micro Service Project template implemented

That’s about it, there’s the option to have multiple projects in a template – more like a solution template, but it’s not possible via a wizard and was too much effort for what we needed. A bit of googling will set you on the road if you need something along those line e.g. multiple custom projects per solution.

So there you have it, a way to ease initiation/propagation of something like micro services. There is the obvious pain of having to update all the previous projects for things missed out or implemented incorrectly, but that’s just something waiting to be learnt with or without templates.

Resharper Templates – supercharge your coding

Resharper_AltInsertResharper can help with a lot of repetitive tasks which can take a bit of time everyday. For example, the templates provided by Resharper are quickly available by using Alt+Insert when a project/folder/class are selected in the Solution Explorer, an example shown on the right. This will give you options as per the item selected on the solution explorer. In the example given here, the entries for “MS Test class” and “NUnit Test class” are custom file templates, which will not be available out of the box. Their creation is explained below.

The options provided here are the Resharper templates which can be edited by selecting the Resharper –> Templates Explorer… menu. This gives the Templates Explorer screen where the Live, Surround and File Templates can be selected, as shown below. The New/Edit Template Icon can be used to create/edit the respective type of template.

Resharper_FileTemplates

To add standard repeated items like copyright to a class/enum, click on File Templates sub-tab in the Templates Explorer tab, select C# in the Scopes column on the left, and double click the Class/Enum item, which should be at the top of the ‘In quicklist’ items on the right.

This should open up the edit template tab where anything that’s needed for all class definitions can be added. So if the copyright is added as shown, it will come up for each class created and would replace the class name where the $CLASS$ item has been added.

Resharper_EditTemplate

Resharper_AddMacro

The $ enclosed words are parsed as macros by Resharper and can be selected by clicking the link for the respective macro shown on the right hand side of the edit template screen under Parameters sub-section, as in the picture above. Clicking on the link brings up the “Choose Macro” dialog box shown to the right.

The above process will have to be carried out for any other file templates e.g. enum to get the same copyright etc.

Live templates are templates available in the files and are used by typing their shortcut and pressing the tab key. This will print out the template with ‘hotspot’ (the place to type code) at the first of the macro location. The other locations can be accessed using the tab key.

To create a new live template, like for NUnit test class, select Live Templates tab in the Templates Explorer and click on the icon for New Template shown before. Here the Class template can be copied over and alterations made as needed for a NUnit test class. The macros will have to be selected under the Parameters sub-section above. The resulting dialog ‘Choose Macro’ dialog box is shown.

The $END$ is a Resharper macro where the cursor is placed after all the editable parts of the template are filled one by one by using the Tab key. This allows continuing the flow of typing while filling in a template.

Resharper_AddTemplate

Creating a template as explained above will create a new template as named under the ‘Not in quicklist’ section on the right when Templates Explorer is opened and C# selected. To show this template in the quicklist drag the template into the ‘In quicklist’ section. This will show the template when Alt+Insert is clicked after selecting an artefact in Solution Explorer.

Resharper_ImportExport

Sharing the templates: To share the templates, select Resharper –> Manage Options… and click on Import/Export Settings –> ‘Export to File’ option highlighted on the right.

Then the relevant settings to export can be highlighted, select OK and provide an appropriate name for the file to share.

To import the settings select the ‘Import from File’ option from Resharper –> Manage Options… –> Import/Export Settings and choose the file required.

This will bring the appropriate templates in the C# section but only in ‘Not in quicklist’ section in the Templates Explorer. To see them on pressing Alt+Enter at the right location, drag the template into the ‘In quicklist’ section from Resharper –> Templates Explorer –> File Templates –> C#.

Youth

I came across my old diary while collating stuff for house move. Along with assorted notes was Youth, a poem, more like an essay, by Samuel Ullman, supposedly a favourite of US General Douglas MacArthur, of the World War II fame, who apparently popularised it in Japan. Worth a read:

Youth is not a time of life; it is a state of mind; it is not a matter of rosy cheeks, red lips and supple knees; it is a matter of the will, a quality of the imagination, a vigour of the emotions; it is the freshness of the deep springs of life.

   Youth means a temperamental predominance of courage over timidity of the appetite, for adventure over the love of ease.  This often exists in a man of sixty more than a body of twenty.  Nobody grows old merely by a number of years.  We grow old by deserting our ideals.

   Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul.  Worry, fear, self-distrust bows the heart and turns the spirit back to dust.

   Whether sixty or sixteen, there is in every human being’s heart the lure of wonder, the unfailing child-like appetite of what’s next, and the joy of the game of living.  In the center of your heart and my heart there is a wireless station; so long as it receives messages of beauty, hope, cheer, courage and power from men and from the Infinite, so long are you young.

   When the aerials are down, and your spirit is covered with snows of cynicism and the ice of pessimism, then you are grown old, even at twenty, but as long as your aerials are up, to catch the waves of optimism, there is hope you may die young at eighty.

Platforms and Services: why you(r company) need(s) them

This is a gist of the Steve Yegge‘s phenomenal(ly long) Google Platforms Rant, which lists the only three things he thinks were done well by his former company and are the only things his current company hasn’t got right. The most important of these was Platforms. The hows & whys are a fascinating and a long read and the discourse is much posted on the internet. Steve has since offered his apology/follow up to the accidental disclosure of what was supposed to be a private memo. At least that’s my understanding of the story, as are the following lessons from the post, laid out for those short of time.

Continue reading

It’s all my fault – own All your work

 

It's not how good you are, it's how good you want to be.
What more can you ask for…
This post springs from one of the ideas in “The world’s best-selling book”, some of which are listed here. Rather pithily, this one states: It’s all my fault.
Which is the author’s way of asking you to take total responsibility for any piece of work you have touched. As the book continues: “If you accept responsibility, you are in a position to do something about it … … There are no excuses.”