最佳实践:为验证方法调用的条件是什么? [英] Best practice: Validate conditions for method calls?
问题描述
我想在几乎每一个PROGRAMM有时方法不需要被称为所有的时间,但只在特定条件下。
它,它很容易检查的方法必须被调用。一个简单的if-说明书可以做的伎俩。
I guess in almost every programm sometimes methods don't need to be called all the time but under specific conditions only. It it very easy to check if a method must be called. A simple if-statment can do the trick.
if (value == true)
{
DoSomething();
}
但如果你有很多条件的验证可以变得复杂和代码变长和更长。
所以我写了一个名为每次
和本身将检查和验证,如果她的代码需要执行的方法,该方法的代码。
But if you have many conditions the validation can get complicated and the code gets longer and longer. So I wrote code with the method called every time and the method itself will check and validate if her code needs to be executed.
DoSomething(value);
...然后... ...
... then ...
public void DoSomething(bool value)
{
if (value == true)
{
// Do Something here ...
}
}
现在我有做事的方法有两种。我并不完全确定哪条路是正确的方式。
也许甚至有另一种选择
Now I have two ways of doing things. I am not exactly sure which way is the right way. Or maybe there is even another option?
推荐答案
的清洁守则 - 敏捷软件工艺的手册提倡不写方法接受一个布尔参数,因为每一种方法应该做的一件事,只有一件事。如果一个方法接受一个布尔参数来决定做什么,它会自动做了两件事:决定的什么的做,实际上的做的东西。该方法应被重构到两种不同的方法做一些和一个单一的方法决定要调用哪些两种方法
Clean Code — A Handbook of Agile Software Craftsmanship promotes not to write methods accepting a single boolean parameter because each method should do one thing and one thing only. If a method takes a boolean parameter to decide what to do, it automatically does two things: deciding what to do and actually doing something. The method should be refactored into two separate methods doing something and a single method deciding which of the two methods to call.
此外,评价用的布尔值价值==真
是多余的和不必要的。本身的价值表示布尔状态(真正
/ 假
),也不需要被比作
再次如此。 也就是说,最好的做法是用 如果(值)
而不是 如果(价值== true)而
(或 IF((价值==真)==真
;这似乎是愚蠢的,但不从的做法不同,很多如果(价值==真)
)。
Furthermore, evaluating a boolean value using value == true
is redundant and unnecessary. The value itself represents a boolean state (true
/ false
) and does not need to be compared to true
again. That said, the best practice is using if (value)
instead of if (value == true)
(or if ((value == true) == true
; this seems idiotic but does not differ much from the approach of if (value == true)
).
这篇关于最佳实践:为验证方法调用的条件是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!