Die verflixte Namensgebung

Den richtigen Namen zu finden ist wohl eine der schwierigsten Aufgaben überhaupt.
Doch das ist nicht wirklich was Neues, Steve McConnell hat schon 1993 in Code Complete geschrieben:

You can’t give a variable a name the way you give a dog a name – because it’s cute or it has a good sound. Unlike the dog and its name, which are different entities, a variable and a variable’s name are essentially the same thing.
..
The most important consideration in naming a variable is that the name fully and accurately describe the entity the variable represents.

Heute kam mir dann diese Frage in die Quere: how do you call this anti-pattern?
Und sofort ist mir ein Gestank (Neudeutsch: Code Smell) aufgefallen:

NotActive = !mytable.active;

Yups. Ein Bool der mit Not anfängt. Sicher, ist noch immer besser als würde die Variable “X” getauft worden sein, aber besser als ganz schlecht ist noch lang nicht gut.

Und warum stinkt das jetzt?
Man muss um die Ecke denken. Wenn ich die Variable auf true setze, meine ich false. Wenn ich wissen will ob das Ding aktiv ist muss ich auf false prüfen.

Da kann dann solcher Code rauskommen:

if (!NotActive) DoSomething();

oder

if (NotActive == false) DoSomething();

oder ganz kreativ (alles schon gesehen)

if (NotActive)
else DoSomething();

Kern des Problems ist das Not als Prefix im Variablennamen. Besser wär hier als Name z.B.: IsInactive.

if (!IsInActive) DoSomething();

Trotzdem ist auch das nicht optimal. Erstens weil trotzdem noch eine Verneinung drinnen ist und ich außerdem aus der Variable nicht erkennen kann was jetzt eigentlich (in)aktiv sein soll. Zweiteres hängt natürlich vom Kontext ab.

Viel leserlicher ist schon:

if (MenuItemIsActive) DoSomething();

Beim zweiten Codebrocken in der Frage wirds dann auch nicht besser:

control.enabled = !mytable.Enable_yes_no

Das _yes_no ist natürlich total überflüssig, ein reines “Enabled” liest sich eindeutig besser.

Darum sollte man bei Booleschen Variablen keinesfalls negative Namen verwenden, damit wird der Code unleserlich und vor allem unnötig kompliziert.