Suppose a FileWriter class that needs validation that it will not erase a file already present, if one is found. It would have two functions:
public bool FileExists(string filePath) //...
public bool WriteFile(string filePath, string text) //...
The main concern is to not erase a file already present. A first interface is actually just interaction via a console:
public void Save()
{
FileWriter fileWriter;
//...
if (fileWriter.FileExists(filePath))
{
Console.WriteLine("File already exists. Continue? Press 'y' for yes");
if (Console.ReadKey().KeyChar != 'y')
return;
}
fileWriter.WriteFile(filePath, text);
}
And some time later comes a second interface, this one with a GUI, that needs the same user interaction:
public void SaveButton_click(object sender, EventArgs e)
{
FileWriter fileWriter;
//...
if (fileWriter.FileExists(filePath))
{
if (DialogResult.Yes != MessageBox.Show("File already exists. Continue?", "", MessageBoxButtons.YesNo))
return;
}
fileWriter.WriteFile(filePath, text);
}
Save for the way the interaction is made, the logic is the same. What pattern can be used to not duplicate this logic? Is a callback function to perform the check the best approach?
Formatted as C#, but doesn't have to be C# specific.