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: |

best-secure-messaging-apps-shutterstock-1892950018.jpg Hui said the time period and nature of some offences “overlapped” and thus their prison terms could be served concurrently. The judge ordered Ng to be jailed for a total of six years and six months. Write your hashtags in the language of your target audience. Telegram desktop app: In the upper left corner, click the Menu icon (the one with three lines). Select “New Channel” from the drop-down menu. In handing down the sentence yesterday, deputy judge Peter Hui Shiu-keung of the district court said that even if Ng did not post the messages, he cannot shirk responsibility as the owner and administrator of such a big group for allowing these messages that incite illegal behaviors to exist.
from us


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