Keep your code DRY

Other day my Boss was reviewing the code written by me. He had a feedback, keep the code DRY. It was great feedback, and I thought why not to share with you that what does DRY mean?

DRY stands for Do not Repeat Yourself.

clip_image002

To understand it better let is consider below code snippet:

clip_image003

I am fetching a particular movie on basis of the id. As you notice this code is inside Details method. Next in another method Edit in the controller and I am doing the same fetching a particular movie on basis of the id as shown below:

clip_image004

As you clearly notice that I am repeating the code in the same class hence CODE IS NOT DRY in above scenario. The code should not be repeated and should be kept in repository class. We could have a function FindById() in MovieRepository class and both the methods will call FindById(). A common function to find the movie by id can be created as follows:

clip_image006

And then both methods of Controllers can use them as follows:

clip_image007

In the layered architecture approach DRY code is very essential for robust software development. I hope now you have better understanding of having code DRY and you will follow this approach.

Happy Coding.

Understanding IEnumerable and IQueryable in C#

Read full article at Falafel blog

I see developers are not that confident about usage of the mentioned interfaces. In this post, I am going to discuss basic differences among IEnumerable<T> and IQueryable<T> and in which scenario to use what.

IEnumerable<T>

The IEnumerable<T> is used to iterate a read only collection. It has only one method GetEnumeartor() which allows you to iterate the read only collection using a foreach loop. It only iterates in the forward direction. IEnumerable <T> is defined in as follows:

clip_image002

Read full article at Falafel blog

The call is ambiguous between the following methods in C#

I was writing some Unit Tests on default ASP.NET MVC Movie Application. Application can be created by following tutorials here http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started or alternatively you can download sample application as well. Okay so while writing unit test, I had to pass null value for id in Edit action. Compiler was not happy me passing null and I got compile time error as given in below image,

image

Error is clearly saying that there is ambiguous between two methods. On examining Edit action found it was overloaded,

  • Id parameter
  • Instance of Movie parameter

Now when I passed null, complier was not able to decide which overloaded Edit action needed to be called. Because null can be pass for integer id value and for object Movie as well. And that’s the reason complier was throwing compile time error.

How to solve it? Of course you can change definition of Edit action. But we may not want to do it. Other option is to forcefully pass null either as movie or integer id. Null can be passed as integer id as below,

image

Remember this solution not restricted only for MVC and can work in any code written using C#. So, the call is ambiguous between the following methods in C# can be resolved as easily as given discussed above.

Convert List to List using ConvertAll in C#

I see many developers convert one list to another list using foreach. It is ok and get the job done but there is better way to convert one list to another list using ConvertAll();

Just to explain you scenario better, let us assume you got two classes as below. InternalStudent class is representing Student class internally in the project and this is not supposed to be exposed in Service etc.


public class InternalStudent
    {
        public string IName { get; set; }
        public int IAge { get; set; }
    }

Another class is Student


  public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

Now you have List of InternalStudents as below,


List<InternalStudent> lstInterStudent = new List<InternalStudent>
            {
                new InternalStudent {IName="dj",IAge=32},
                new InternalStudent{IName="pinal",IAge=36}
            };

Requirement is to convert List<InternalStudent> to List<Student>. Usually we convert one list to another list using foreach as given below,


List<Student> lstStudent = new List<Student>();
foreach(InternalStudent s in lstInterStudent)
            {
                lstStudent.Add(new Student
                    {
                        Name = s.IName,
                        Age = s.IAge
                    });
            }

There is no problem as such in this way of conversion from one generic list to another generic list. However there is better way to do this conversion.


List<Student> lstStudent = lstInterStudent.ConvertAll(x => new Student
                {
                    Age = x.IAge,
                    Name = x.IName
                });

We are using ConvertAll to convert one generic list to another generic list. I hope you find this post useful. Thanks for reading.

Single Responsibility Principle in C-Sharp: Simplified

Let us start with understanding what is SRP?

Single Responsibility Principle says every class should have single responsibility and all the responsibility should be encapsulated in the class. To explain it further assume you are creating a creating class to Calculate Salary.

Now if you have two methods in class like below. Usually we can think of these two methods in a Salary class.

  1. CalculateSalaray
  2. PrintSalary

So you can say there are two responsibilities to class. With two responsibilities Salary class can be defined as below,

 class Salary

{
 public double wageperday { get; set; }
 public int attendence { get; set; }
 public double CalculateSalaray()
 {
 return this.wageperday * this.attendence;

}

public void PrintSalaray()
 {
 Console.WriteLine(this.wageperday * this.attendence);

}

}


As of Martin SRP means, “Class should have a single reason to change”. Reason to change can be seen as a Responsibility. On seeing closely you will find above class has two reasons to change,

  1. When formula for calculate salary is changing
  2. When print logic is changing

Since Salary class has two responsibility so there are two reasons to change it. We can say Salary class is not following Single Repository Principle.

We can summarize that

image

Next we need to find that how could we divide two responsibility in two separate class. So above Salary class can be divided into two separate classes. One class to CalculateSalary and another to PrintSalary.

Below is the class CalculateSalary. This class got only one responsibility to calculate salary.

class CalculateSalary
 {
 public double wageperday { get; set; }
 public int attendence { get; set; }
 public double CalculateSalaray()
 {
 return this.wageperday * this.attendence;

}
 }

&nbsp;

Another class is PrintSalary. This class also got only one responsibility to print salary.

 class PrintSalary
 {

public void PrintSalaray(double salary)
 {
 Console.WriteLine(salary);

}
 }

Let us understand what we done now is divided Salary class in two separate classes. Salary class had two responsibilities and two reasons to change. Now we have created two classes respectively for CalculateSalary and PrintSalary.

image

Now at client these two classes can be used as below,

static void Main(string[] args)
 {
 CalculateSalary clcObject = new CalculateSalary();
 clcObject.wageperday = 300;
 clcObject.attendence = 20;
 var salary = clcObject.CalculateSalaray();
 PrintSalary prntObject = new PrintSalary();
 prntObject.PrintSalaray(salary);
 Console.ReadKey(true);

}

As of now you should have idea about Single Responsibility Principle. To summarize Single Responsibility Principle says a class should have single responsibility and only one reason to change. I hope you find this post useful. Thanks for reading.

Evolution of C Sharp Language: Picture Blog

I was working on something and suddenly a mail popped up. I did not know the sender but I found he/she was a job aspirant. I found him/her very impatient and gist of his/her mail was, “Sir tomorrow I got a job interview. Could you please help me with different versions of C Sharp with specific features in each versions? I just want to know the features name “

I found this question very interesting. Since majority of the time we focus on implementation of a feature. We discuss how a particular feature can be implemented in greater extent but we tend to forget in which version of C Sharp that particular feature got introduced. For a junior level programmer interview, this could be a vital question that list different features of C Sharp version wise. I am trying to answer this question pictorially below,

image

I am sure taking a high level look on this picture before going to interview could be a help. I hope you find this picture post useful. Thanks for reading.

Method Caller Information in C Sharp 5.0

Before we understand Method Caller Information feature of C# 5.0, we need to understand Optional Parameter feature of C# 4.0.

C Sharp 4.0 introduced Optional Parameter feature . According to this feature, in function call only required parameters are needed to be passed. If value of Optional Parameters are not provided then they will take default constant value. To understand it better, let us take following function as example.


static void Display(string Name, int age,string Nationality="Indian")
{

Console.WriteLine("Hey " + Name + " you are " + age + " old " + Nationality);
}

In function Display, Nationality is an optional parameter. So while calling this function you will get intellisense suggesting you that if not provided parameter Nationality will take constant string value “Indian”

image

You can call Display function omitting value of parameter Nationality as following

static void Main(string[] args)
{
Display("dj", 28);
Console.ReadKey(true);

}

In output you will notice that value of parameter Nationality is set to default string constant “Indian”

image 
Now you can see that Optional Parameters has taken the default constant value. C# 5.0 gives us liberty or allow us to attribute optional parameter with caller info attributes. By providing caller info attributes at the runtime optional parameter value will be replaced by dynamic values for caller info attributes. There are three caller info attributes are available,

image

Let us go ahead and rewrite Display function with Method Caller Information attribute on optional parameters.

image

You see in above function definition [see the rectangle], we have attributed three optional parameters with method caller information. We can display method caller information as following,


static void Display(string Name,
int age,
string Nationality="Indian",
[CallerMemberName] string Caller = "",
[CallerFilePath] string file="",
[CallerLineNumber] int line=0)
{

Console.WriteLine("Hey " + Name + " you are " + age + " old " + Nationality);
Console.WriteLine("This function is called  from member " + Caller + " file " + file + " line " + line);
}

Now when you call the function you will get method caller information printed. Expected output would be as following

image 
Method Caller Information is particularly very useful in logging of the application. For high level logging, I would consider using Method Caller Information attributes along with optional parameters. I hope you find this post on Method Caller Information in C# 5.0 useful. Thanks for reading.