Wednesday, March 21, 2007

why pipelining? (response to Andreas)

Andreas added a comment to about this post.

The question was why would you pipeline?

Perhaps a definition is in order - I define this as encapsulating the conditional call check inside the function to:
- reduce duplication of code
- to remove the possibility that the check is not made before the function is called and
- ensure that the function is only executed when appropriate

I noted that this was different to Design by Contract (DbC), as in DbC if you fail the preconditions, then the application will throw an exception.

Consider this code, without Pipelining:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


private void OKButton_Click(object sender, EventArgs e)
{
string cleanText = string.Empty;
if (removeCheckbox.Checked)
{
cleanText = ReplaceUnderscoresWithSpaces(sampleTextBox.Text);
}

System.Windows.Forms.MessageBox.Show(string.Format("Cleaned text: {0}", cleanText));
}

private string ReplaceUnderscoresWithSpaces(string p)
{
return (p.Replace("_", " "));
}
}


This, rewritten with pipelining would be as follows:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void OKButton_Click(object sender, EventArgs e)
{
string cleanText = ReplaceUnderscoresWithSpaces(sampleTextBox.Text, removeCheckbox.checked);

System.Windows.Forms.MessageBox.Show(string.Format("Cleaned text: {0}", cleanText));
}

private string ReplaceUnderscoresWithSpaces(string p, bool execute)
{
string temp = p;
if (execute)
{
temp = p.Replace("_", " ");
}

return (temp);
}
}

(Changes in bold)

Now, forgetting the simplicity of this example (and some of the other minor issues), it shows that:
- the function identifies what it needs to execute,
- the conditional is inside the function, not dispersed throughout the code
- there is less complexity in the calling code
- the conditions of execution are in the function

But this technique is only useful for functions that do not have a side effect if they are not executed. I only do this when it's necessary to do so. But it's still a nice technique to remove duplication and clean up the calling code.

No comments: