Es gibt zwei Probleme hier zu adressieren: Lesbarkeit und Verständlichkeit
Die „Lesbarkeit“ Lösung ein Stil Problem ist und als solche ist offen für Interpretation . Meine Präferenz ist dies:
if (var1 == true && // Explanation of the check
var2 == true && // Explanation of the check
var3 == true && // Explanation of the check
var4 == true && // Explanation of the check
var5 == true && // Explanation of the check
var6 == true) // Explanation of the check
{ }
oder dies:
if (var1 && // Explanation of the check
var2 && // Explanation of the check
var3 && // Explanation of the check
var4 && // Explanation of the check
var5 && // Explanation of the check
var6) // Explanation of the check
{ }
Das heißt, diese Art von komplexen Check ziemlich schwierig sein kann, um geistig zu analysieren, während Sie den Code scannen (vor allem, wenn Sie nicht der ursprüngliche Autor). Betrachten sie eine Hilfsmethode zu abstrahieren einige der Komplexität zu schaffen weg:
/// <Summary>
/// Tests whether all the conditions are appropriately met
/// </Summary>
private bool AreAllConditionsMet (
bool var1,
bool var2,
bool var3,
bool var4,
bool var5,
bool var6)
{
return (
var1 && // Explanation of the check
var2 && // Explanation of the check
var3 && // Explanation of the check
var4 && // Explanation of the check
var5 && // Explanation of the check
var6); // Explanation of the check
}
private void SomeMethod()
{
// Do some stuff (including declare the required variables)
if (AreAllConditionsMet (var1, var2, var3, var4, var5, var6))
{
// Do something
}
}
Wenn nun visuell das Scannen der „Somemethod“ Methode, die tatsächliche Komplexität der Testlogik ist versteckt, aber die semantische Bedeutung ist für die Menschen erhalten zu verstehen, bei ein hohes Niveau. Wenn der Entwickler die Details wirklich verstehen muss, kann die AreAllConditionsMet-Methode untersucht werden.
Dies ist formal bekannt als das "Decompose Conditional" Refactoring-Muster, denke ich. Werkzeuge wie Resharper oder Refactor Pro! kann machen diese Art von Refactoring einfach!
In allen Fällen besteht der Schlüssel zu lesbarem und verständlichem Code darin, realistische Variablennamen zu verwenden. Während ich verstehe, dass dies ein künstliches Beispiel ist, sind "var1", "var2" usw. nicht akzeptable Variablennamen. Sie sollten einen Namen haben, der die zugrunde liegende Natur der Daten widerspiegelt, die sie darstellen.
Einfache, leicht-to-do und effektiv. –