Blog #8

Blog #3

 5 Jun 2017

Whilst building .NET web applications you search for and identify best practices and implement these where you can to make your code more readable, secure and maintainable.

I've taken some of my notes and tips that have guided me in the past and put them together in this blog post.
 

No "magic strings"

Never use magic strings in your code. This means hard-coding view names, link text etc. into your views.
 

Controller and Domain logic

Try to keep away domain logic from controller.  Controller should only be responsible for:

Input validation and sanitization.

Get view related data from the model.

Return the appropriate view or redirect to another appropriate action method.

I personally prefer to implement an Orchestrator design pattern in my Controllers.

These encapsulate everything that's needed to return a strongly typed View Model, whether it be calling an external web service or data store or leveraging a legacy DLL in your domain.

You can read more about that here.
 

Domain Model != View Model

The Domain Model represents the domain, while the View Model is designed around the needs of the View.  These two worlds might be (and usually are) different.

Additionally, the Domain Model is "data plus behaviours", is hierarchical and is made of complex types, while the ViewModel is just a DTO, flat, and made of strings.

To remove the tedious and error-prone object-mapping code, you can use AutoMapper.

AutoMapper has saved me a shed load of time in the past. I initially started out writing Extension Methods such as this:
 

Under the hood, ToViewModel would do something like this:
 

With AutoMaper, you don't need any of that.  You install the NuGet package and you can write code like this:
 

This will save you loads of time. You can configure more complex mappings if your object graph demands it. The out of the box functionality is works well.
 

Stored Procedures and Entity Framework

Entity Framework makes it easy to fetch data from your datasource.  When things move beyond the Customer and Orders samples you find lying about the web, my preference is to have stored procedures for the more complex scenarios.  If your application doesn't have many users, only deals with a handful of domain objects and requires basic CRUD functionality, I'd use Entity Framework for all data access.

 

If you'd like to find out more, click the image below to Download 'Make Your Code More Readable, Secure & Maintainable'.

Or View Our Diary And Book In A Call

Also included:

  • How To Simplify Windows Development Using TopShelf
  • How To Implement Dynamic Business Rules In Your Application
  • Should You Use Workflow Foundation In Your Project?

Comments

Currently there are no comments. Be the first to post one!

Post Comment

*
*
*