CSHARPPROGLIB Telegram 6315
🔥 Избавляемся от if-else деревьев

Когда логика программы разрастается, мы часто пишем целые деревья if-else или switch. Но такой код тяжело читать и сопровождать.

Вместо if-ветвей можно использовать паттерн State. Он выносит каждое состояние в отдельный класс. Объект делегирует своё поведение текущему состоянию, а переходы происходят прозрачно.

Код с if'ами:
public class Document
{
public string State { get; set; } = "Draft";

public void Publish()
{
if (State == "Draft") State = "Moderation";
else if (State == "Moderation") State = "Published";
else Console.WriteLine("Документ уже опубликован");
}
}


Код со State:
public interface IDocumentState
{
void Publish(Document doc);
}

public class Draft : IDocumentState
{
public void Publish(Document doc) => doc.State = new Moderation();
}

public class Moderation : IDocumentState
{
public void Publish(Document doc) => doc.State = new Published();
}

public class Published : IDocumentState
{
public void Publish(Document doc) => Console.WriteLine("Уже опубликован");
}

public class Document
{
public IDocumentState State { get; set; } = new Draft();
public void Publish() => State.Publish(this);
}


Теперь добавление нового состояния — просто новый класс, без переписывания всей логики.

🐸 Библиотека шарписта

#sharp_view
Please open Telegram to view this post
VIEW IN TELEGRAM
1👍155😁3😢3



tgoop.com/csharpproglib/6315
Create:
Last Update:

🔥 Избавляемся от if-else деревьев

Когда логика программы разрастается, мы часто пишем целые деревья if-else или switch. Но такой код тяжело читать и сопровождать.

Вместо if-ветвей можно использовать паттерн State. Он выносит каждое состояние в отдельный класс. Объект делегирует своё поведение текущему состоянию, а переходы происходят прозрачно.

Код с if'ами:

public class Document
{
public string State { get; set; } = "Draft";

public void Publish()
{
if (State == "Draft") State = "Moderation";
else if (State == "Moderation") State = "Published";
else Console.WriteLine("Документ уже опубликован");
}
}


Код со State:
public interface IDocumentState
{
void Publish(Document doc);
}

public class Draft : IDocumentState
{
public void Publish(Document doc) => doc.State = new Moderation();
}

public class Moderation : IDocumentState
{
public void Publish(Document doc) => doc.State = new Published();
}

public class Published : IDocumentState
{
public void Publish(Document doc) => Console.WriteLine("Уже опубликован");
}

public class Document
{
public IDocumentState State { get; set; } = new Draft();
public void Publish() => State.Publish(this);
}


Теперь добавление нового состояния — просто новый класс, без переписывания всей логики.

🐸 Библиотека шарписта

#sharp_view

BY Библиотека шарписта | C#, F#, .NET, ASP.NET


Share with your friend now:
tgoop.com/csharpproglib/6315

View MORE
Open in Telegram


Telegram News

Date: |

So far, more than a dozen different members have contributed to the group, posting voice notes of themselves screaming, yelling, groaning, and wailing in various pitches and rhythms. On June 7, Perekopsky met with Brazilian President Jair Bolsonaro, an avid user of the platform. According to the firm's VP, the main subject of the meeting was "freedom of expression." Find your optimal posting schedule and stick to it. The peak posting times include 8 am, 6 pm, and 8 pm on social media. Try to publish serious stuff in the morning and leave less demanding content later in the day. Your posting frequency depends on the topic of your channel. If you have a news channel, it’s OK to publish new content every day (or even every hour). For other industries, stick with 2-3 large posts a week. Clear
from us


Telegram Библиотека шарписта | C#, F#, .NET, ASP.NET
FROM American