jeudi 5 mars 2015

Slam valve pattern

Something I've seen a sprinkling of times over the past few decades is slam valve type code where there is a contrived value which decrements/increments to force a loop to exit once a certain value has been breached or where a number of iterations have passed.


A bit abstract for you?


Some concrete examples:


File read


In this case, a file is being read in a data factory overnight so needs to be processed by a certain time in order for the system to be available in the morning. N.B. it doesn't matter if the file completes.



int linesRead = 0;

const int SillyAmount = 1000000;

while (!EOF)
{
text = ReadLine();
// Do Some complicated processing with the text
linesRead++;

if (linesRead > SillyAmount)
break;
}


Service conversation


In this example an object is gradually enhanced via service calls until the data is good enough to be processed later on.



int conversationLines = 10;

while (conversationLines > 0 && conversation.Status != Complete)
{
conversation.Next();
// Process conversation
conversationLines--;
}


Questions.


(1) Is there a design pattern or similar for this sort of thing?


(2) In the absence of (1) and given that you're artificially exiting a loop, could this be deemed a code smell?


Aucun commentaire:

Enregistrer un commentaire