官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 眉山市| 闽侯县| 浙江省| 简阳市| 英山县| 梅州市| 尚志市| 高平市| 舟曲县| 和政县| 桃江县| 富川| 龙口市| 岚皋县| 乌审旗| 阳新县| 乐业县| 淮安市| 青田县| 陕西省| 福鼎市| 紫阳县| 延安市| 峡江县| 大姚县| 安远县| 东平县| 子洲县| 友谊县| 丹巴县| 泰州市| 云南省| 拉萨市| 成都市| 柳州市| 潜江市| 仪征市| 德昌县| 德惠市| 临高县| 无棣县|