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

  • Clean Code in C#
  • Jason Alls
  • 395字
  • 2021-06-18 18:28:12

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.

主站蜘蛛池模板: 内丘县| 峨边| 沭阳县| 南平市| 扎鲁特旗| 江山市| 绍兴县| 游戏| 开封市| 同德县| 芦溪县| 平顺县| 常宁市| 石家庄市| 定日县| 衡阳县| 米脂县| 长乐市| 嘉禾县| 澎湖县| 河西区| 荆州市| 镇康县| 岢岚县| 兴业县| 施秉县| 叶城县| 汉阴县| 沙田区| 尖扎县| 大新县| 临朐县| 衡阳县| 济南市| 桐城市| 保定市| 攀枝花市| 乃东县| 长寿区| 张家界市| 商水县|