Implementing the Liskov Substitution Principle
Understand how to apply the Liskov Substitution Principle in C# by analyzing a text processing example. Learn to adjust class inheritance and method overriding to avoid unexpected behavior, ensuring your derived classes maintain base class functionality without breaking existing code. This lesson guides you through practical steps to adhere to SOLID principles while enhancing software design.
We'll cover the following...
We have the following console application that reads the textual content of a file, encloses every paragraph in the p HTML tags, and makes conversion of specific Markdown markers into equivalent HTML tags.
Note: Run the following code. The program will ask for the file to convert. Enter
sample.txtas the name of the file. When the program stops execution, press any key to return to the terminal. Now, enter thecat sample.htmlcommand to see the content after conversion.
using System.Text;
using System.Text.RegularExpressions;
namespace TextToHtmlConvertor;
public class TextProcessor
{
public virtual string ConvertText(string inputText)
{
var paragraphs = Regex.Split(inputText, @"(\r\n?|\n)").Where(p => p.Any(char.IsLetterOrDigit));
var sb = new StringBuilder();
foreach (var paragraph in paragraphs)
{
if (paragraph.Length == 0)
{
continue;
}
sb.AppendLine($"<p>{paragraph}</p>");
}
sb.AppendLine("<br/>");
return sb.ToString();
}
}We have the TextProcesor.cs file with the following content:
We also have a class that derives from it, which is called the MdTextProcessor class. It overrides the ConvertText method, written on lines ...