Reputation: 277
So I have some code centered around a do while loop.
string token;
var count = 0;
var checkDataLength= data.Length == 16;
do
{
count = 0;
token = GenerateToken(data, start, end);
if (checkDataLength)
{
if (Mod120Check(token))
{
count += 1;
}
}
if (IsCompliant(token))
{
count += 1;
}
}
while (count > 0);
return token;
Basically, I am generating a token and for this token to be valid, has to FAIL the Mod120Check and the IsCompliant check. I cannot change how those methods return the data.
While the above code works, I feel that its ugly and I was wondering if anyone had a better way of doing it?
Thanks
Upvotes: 5
Views: 244
Reputation: 1435
Try this:
do
{
token = GenerateToken(data, start, end);
}
while (checkDataLength && Mod120Check(token) || IsCompliant(token))
Just moving your conditions to the while
.
(!) Notice that IsCompliant(token)
will only be called if checkDataLength && Mod120Check(token)
states false
. It shouldn't cause any colateral effects, but it could, depending on what your IsCompliant
method does.
Upvotes: 17
Reputation: 7111
You're right, it is ugly. You are using count
in an unexpected way (it gets reset to zero at the top of every loop, and can go positive for two different reasons). When I see count
, I expect something to start at zero and count up (or start high and count done). Try this instead:
var count = 0;
to var goodEnough = false;
up at the topcount = 0;
statementcount += 1;
statements to goodEnough = true;
while (count > 0);
to while (!goodEnough);
This emphasizes that you are starting in a "not good enough" state, and you will loop until some condition makes it good enough to continue past the loop.
Upvotes: 2