Avoiding duplication

Code can be either DRY or WET. WET code stands for Write Every Time and is the opposite of DRY, which stands for Don't Repeat Yourself. The problem with WET code is that it is the perfect candidate for bugs. Let's say your test team or a customer finds a bug and reports it to you. You fix the bug and pass it on, only for it to come back and bite you as many times as that code is encountered within your computer program.

Now, we DRY our WET code by removing duplication. One way we can do this is by extracting the code and putting it into a method and then centralizing the method in such a way that it is accessible to all the areas of the computer program that need it.

Time for an example. Imagine that you have a collection of expense items that consist of Name and Amount properties. Now, consider having to get the decimal Amount for an expense item by Name.

Say you had to do this 100 times. For this, you could write the following code:

var amount = ViewModel
.ExpenseLines
.Where(e => e.Name.Equals("Life Insurance"))
.FirstOrDefault()
.Amount;

There is no reason why you can't write that same code 100 times. But there is a way to write it only once, thus reducing the size of your codebase and making you more productive. Let's have a look at how we can do this:

public decimal GetValueByName(string name)
{
return ViewModel
.ExpenseLines
.Where(e => e.Name.Equals(name))
.FirstOrDefault()
.Amount;
}

To extract the required value from the ExpenseLines collection within your ViewModel, all you have to do is pass the name of the value you require into the GetValueName(string name) method, as shown in the following code:

var amount = GetValueByName("Life Insurance");

That one line of code is very readable, and the lines of code to get the value are contained in a single method. So, if the method needs to be changed for whatever reason (such as a bug fix), you only have to modify the code in one place.

The next logical step to writing good functions is to have as few parameters as possible. In the next section, we'll look at why we should have no more than two parameters, as well as how to work with just parameters, even if we need plenty more.