I ran across some code like this today; having a flow control flag that is visible to the whole class. My gut says this is the wrong way to handle this need for flow control (it's almost like an old time global flag in C).
(The example is in VB.Net but similar things could be done in C#.)
Public Class myClass
Private bMyFlag As Boolean ''// <------
private sub New
bMyFlag = false
end sub
private sub mySub1
bMyFlag = true
mySub3()
mySub4()
mySubN()
end sub
private sub mySub2
bMyFlag = false
mySub3()
mySub4()
mySubN()
end sub
private sub mySub3
if bMyFlag then
DoSomething()
else
DoSomethingElse()
end if
end sub
private sub mySub4
if not bMyFlag then
DoSomethingDifferent()
else
DoSomethingReallyDifferent()
end if
end sub
private sub mySubN
if not bMyFlag then
DoNotPassGo()
else
DoNotCollect200Dollars()
end if
end sub
end class
It's obvious to me that it was grafted on after the fact. I'm planning on reworking the code so that bMyFlag is a parameter passed to mySub3, mySub4, and mySuvN. However, before I do so:
Is there a valid reason for having a flow control flag that is global to the class?
Or if not, why is this considered bad practice?
In this case, bMyFlag
seems to be introducing unnecessary state which could complicate development (debugging, etc.). Some of your subroutines modify its value, and others perform different operations based on its current value. This seems to introduce unnecessary complexity that could be reduced with some refactoring. Why not just pass a boolean value to mySub1
and mySub2
, and then have those subroutines call your other functions with that value as a parameter?