SOLID (1/5) - Single Resposibility Principle
The single-responsibility principle (SRP) is a computer-programming principle that states that every class in a computer program should have responsibility over a single part of that program's functionality, which it should encapsulate. All of that module, class or function's services should be narrowly aligned with that responsibility.
In the following example we have a TodoList class which only handles it's own functionality logic, and then we have a Persistance class which handles the saving logic, hence keeping the concerns separeted.
using System;
using System.Collections.Generic;
namespace Journal
{
public class TodoList
{
private readonly List<string> _entries = new List<string>();
private static int _count = 0;
public int AddEntry(string entry)
{
_entries.Add($"{++_count} : {entry}");
return _count;
}
public void RemoveEntry(int index)
{
_entries.RemoveAt(index);
}
public override string ToString()
{
return string.Join(Environment.NewLine, _entries);
}
}
public class Persistance
{
public void Save(TodoList todoList)
{
// saving logic
}
}
class Program
{
static void Main(string[] args)
{
var todoList = new TodoList();
todoList.AddEntry("dentist");
todoList.AddEntry("shopping");
todoList.AddEntry("wash the car");
Console.WriteLine(todoList);
var persistance = new Persistance();
persistance.Save(todoList);
}
}
}
Comments
Post a Comment