Sunday, April 5, 2015

Clean Code Practices : Conditions

 

It is said

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

so that we have to make sure the code we write should be easily read and understood by the other developers. This post I will be discussing practices we can follow to make our conditional statements clean. In this post I will mention code dirty and clean to you to understand the difference

Principles:-

  1. Clear Intent
  2. Use the right tool
  3. Bite-size logic
  4. Sometimes code isn’t the answer

 

1.Use Positive Conditionals

When you write conditions always try to use positive conditionals rather using negative because humans are more comfortable in grabbing positive things.

Dirty
if (!isNotlogggedIn)
            {
            }

see above example it is bit confusing to understand the meaning in first time.

Clean
  1. if (logggedIn)
  2.             {
  3.             }

 

2.Use Ternary operator

see the following example first.

Dirty

  1. int bookingFee;
  2.  
  3.           if (isEarlyBirdBooking)
  4.           {
  5.               bookingFee = 5000;
  6.           }
  7.  
  8.           else
  9.           {
  10.               bookingFee = 8000;
  11.           }

we can see the variable “bookingfee” is referenced two places and this code has 11 lines of code. For this kind of conditions you can use the ternary operator to make the code cleaner.

Clean

  1. int bookingFee = isEarlyBirdBooking ? 5000 : 8000;

so that you can see, this has

  • less code
  • intention of the logic is short and clearly presented

3.Avoid using ‘Stringly’ types

see the following example first

Dirty

  1. if (user.Type= "Administrator")

in this sample we are checking a condiition against a string. Which might lead to many issues. There could be case mismatch, also developer might make spelling mistakes. To avoid these try to use enums rather using string values.

Clean

  1. if(user.UserType==UserType.Administrator)

if you use enums

  • there will be no typos
  • You will get the intellisense support from visual studio as it shows all possible values for user type
  • Also you can easily search where a specific user type is used in the code. Rather using enums if you use sting and then you search it will search commented code and all other unwanted stuff.

 

 

Monday, February 9, 2015

Event Initializer in C# 6.0

 

Take the following sample class which has a property and an event listener

  1. public class Lecturer
  2.     {
  3.         public string Name { get; set; }
  4.         public EventHandler<EventArgs> Speaking;
  5.  
  6.     }
.

In C# 6.0 when you initialize a new object wire up delegate to the event inside the object initialization syntax. Before C# 6.0 it was illegal.

  1. static void Main(string[] args)
  2.       {
  3.           EventHandler<EventArgs> log = (e, o) => Console.WriteLine("Speaking");
  4.  
  5.           Lecturer mathsLecturer = new Lecturer
  6.           {
  7.               Name = "Perera",
  8.               Speaking += log
  9.           };
  10.       }

Also you can directly assign the lambda to the event as follows.

  1. static void Main(string[] args)
  2.         {
  3.             EventHandler<EventArgs> log = (e, o) => Console.WriteLine("Speaking");
  4.  
  5.             Lecturer mathsLecturer = new Lecturer
  6.             {
  7.                 Name = "Perera",
  8.                 Speaking += (e, o) => Console.WriteLine("Speaking")
  9.             };
  10.         }

 

Happy Coding !!!

Sunday, February 8, 2015

Dictionary Initializer in C# 6.0

 

After C# 3.0 is released we had the ability of initializing lists and dictionaries using following syntax.

  1. Dictionary<string, User> userList = new Dictionary<string, User>
  2.             {
  3.                 { "admin",new User("Sammani") },
  4.                   { "Guest",new User("Hemal") },
  5.             };

Here we add the key value pairs inside the “{ }”. In c# 6.0 it has a new syntax as follows which gives more look like working with key value pairs.

  1. Dictionary<string, User> userList = new Dictionary<string, User>
  2.           {
  3.               [ "admin"]=new User("Sammani") ,
  4.                ["Guest"]=new User("Hemal")
  5.           };

you can the number of characters are almost same in both the syntax but in c# 6.0 syntax looks more a like key value pair.

This is another syntax sugar added in c# 6.0.

Happy Coding

Sunday, January 4, 2015

Primary Constructor in C# 6.0

 

In my previous post I explain about Auto Property Initializer in C# 6.0. Now lets see another new feature in C# 6.0 which is Primary constructor.

First we will see the following code.

  1. public class Country
  2. {
  3.     public string Name { get; private set; }
  4.  
  5.     public Country(string name)
  6.         {
  7.         Name = name;
  8.         }
  9.  
  10. }

here we have a class which has a property with a private setter and assigning the value for the name property inside the constructor.

Now in C# 6.0 you can write the above code in a more simplified manner as follows.

  1. public class Country(string name)
  2.     {
  3.         public string Name { get;}=name;
  4.  
  5.  
  6.     }

This is what is called primary constructor in C# 6.0 . Notice the parameters added just right of the class definition. This tells the compiler to add a constructor to the Country class with one parameters: name. So we don’t need to create separate constructor with parameters and then assign the values to the property , compiler do all those for us.

For one class only one primary constructor is allowed. If you want to have constructors with some more parameters you can create new constructor and also call the primary constructor inside it. See the following example.

  1. public class Country(string name)
  2.     {
  3.         public string Name { get; } = name;
  4.     public List<string> Regions { get; private set; }
  5.     public Country(List<string> regions, string name):this(name)
  6.     {
  7.         Regions = regions;
  8.     }
  9. }

Here when you call the constructor with two parameters it will assign the value to the property “Regions” and it has call the primary constructor it will set the value to the property “Name”. Hope you understand the concept behind this.

Hope this is helpful.

Happy Coding !!!!!!

Friday, January 2, 2015

Auto Property Initializer

 

Anyone who have worked with properties in a class must have experienced that it was little annoying that we have to have private fields and assigned if we want to have default values for properties.

See the following example which we used to do when we have collection property.

  1. public class Country
  2.     {
  3.         private List<string> _regions = new List<string>();
  4.         public List<string> Regions { get { return _regions} set { value = _regions; } }
  5.  
  6.     }

but this is no more needed. We can simply write it as below.

  1. public class Country
  2.     {
  3.         public List<string> Regions { get; set; }=new List<string>();
  4.  
  5.     }

Also this is useful when you want to assign default values for read only fields.

Before C# 6.0

  1. public class Country
  2.   {
  3.       public string Name { get; }
  4.       public Country()
  5.       {
  6.           this.Name = "Sri Lanka";
  7.       }
  8.  
  9.   }

In C# 6.0

  1. public class Country
  2.   {
  3.       public string Name { get; }="Sri Lanka";
  4.  
  5.   }

 

This is syntactic sugar added in c# 6.0. hope this is helpful.

 

Happy Coding !!!!!!

Monday, December 15, 2014

Injecting a service into a view in MVC 6

 

Asp.net MVC 6 supports injecting service to view using a class.

Example :- When country combo box value get changed , region com

Only restriction is that class should be

  • Public
  • Non-nested
  • Non-Abstract

1. Create a Asp.Net Project in Visual Studio 2015

image

 

image

 

2. Create a folder name services and add a service class.

  1. using System;
  2. using System.Threading.Tasks;
  3.  
  4. namespace ViewInjection.Services
  5. {
  6.     public class EmployeeService
  7.     {
  8.         public async Task<int> GetEmployeesOnLeaveCount()
  9.         {
  10.             return await Task.FromResult(5);
  11.         }
  12.  
  13.         public async Task<int> GetEmployeesOnSiteCount()
  14.         {
  15.             return await Task.FromResult(
  16.                 10);
  17.         }
  18.  
  19.         public async Task<int> GetEmployeesOnWorkCount()
  20.         {
  21.             return await Task.FromResult(97);
  22.         }
  23.     }
  24. }

 

2. Create a View to show Employee statistics and add the inject statement to the top of the file.

  1. @inject ViewInjection.Services.EmployeeService EmployeeService
  2. @{
  3.      ViewBag.Title = "Employee Page";
  4. }

3. Call the service as below

  1.  
  2. @inject ViewInjection.Services.EmployeeService EmployeeService
  3. @{
  4.      ViewBag.Title = "Employee Page";
  5. }
  6.  
  7. <h3>Employee Stats</h3>
  8. <ul>
  9.     <li>On Leave: @await EmployeeService.GetEmployeesOnLeaveCount()</li>
  10.     <li>On Site:@await EmployeeService.GetEmployeesOnSiteCount()</li>
  11.     <li>On Work:@await EmployeeService.GetEmployeesOnWorkCount()</li>
  12. </ul>

4. Register the EmployeeService class in the Startup.cs file.

  1. public void ConfigureServices(IServiceCollection services)
  2.       {
  3.           // Add EF services to the services container.
  4.           services.AddEntityFramework(Configuration)
  5.               .AddSqlServer()
  6.               .AddDbContext<ApplicationDbContext>();
  7.  
  8.           // Add Identity services to the services container.
  9.           services.AddDefaultIdentity<ApplicationDbContext, ApplicationUser, IdentityRole>(Configuration);
  10.  
  11.           // Add MVC services to the services container.
  12.           services.AddMvc();
  13.           
  14.           services.AddTransient<ViewInjection.Services.EmployeeService>();
  15.  
  16.       }

5. Add a action method in HomeController.cs

  1.  
  2. public IActionResult EmployeeStaticstics()
  3. {
  4.     return View();
  5. }

6.Run your code you will see the output as below.

image

Happy Coding !!