Implementing the Liskov Substitution Principle
Understand the importance of the Liskov substitution principle with an example.
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.txt
as the name of the file. When the program stops execution, press any key to return to the terminal. Now, enter thecat sample.html
command 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:
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 also have a class that derives from it, which is called the MdTextProcessor
class. It overrides the ...
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy