Should SRP always be followed?

I find it difficult to understand whether it is sometimes possible to violate the principle of shared responsibility, or if it should be avoided at all costs.

Please note that the following code has been simplified to save only the relevant part.

I have a class Herothat represents a character, it can have several different ones Items.
I have a multiples class inheriting from Items, for example, QuestItemsand BackpackItems.
When I want to add Itemto mine Hero, depending on the type Item, I have to act differently.
I tried 2 different ways to make the first comply with SRP:

 public abstract class Item
{
    private string _Name{get;set;}

    public string Name
    {
        get
        {
            return _Name;
        }
        protected set
        {
            if (_Name != value)
            {
                _Name = value;
            }
        }
    }
}

public class QuestItem: Item
{
    public QuestItem(String name)
    {
        Name = name;
    }
}

public class BackpackItem: Item
{
    public BackpackItem(String name)
    {
        Name = name;
    }
}
public class Hero
{
   public void AddItem(Item item){
      if(item is QuestItem){
         //Do stuff to add QuestItem
         return;
      }
      if(item is BackpackItem){
         //Do stuff to add BackpackItem
         return;
      }
   }
}

: SRP
: , Item, AddItem Hero, .

, SRP:
AddItem

public void AddItem(Item item){
          item.AddToHero(this);
       }

Items :

 public abstract class Item
{
    private string _Name{get;set;}

    public string Name
    {
        get
        {
            return _Name;
        }
        protected set
        {
            if (_Name != value)
            {
                _Name = value;
            }
        }
    }
  public abstract void AddToHero(Hero hero);
}

public class QuestItem: Item
{
    public QuestItem(String name)
    {
        Name = name;
    }
    public override void AddToHero(Hero hero)
    {
       //Do my stuff to add my QuestItem to Hero
    }
}

public class BackpackItem: Item
{
    public BackpackItem(String name)
    {
        Name = name;
    }
    public override void AddToHero(Hero hero)
    {
       //Do my stuff to add my BackpackItem to Hero
    }
}

: add Item, . : SRP, , .

? ( ?)

+4
2

, Heros "" ? , - (, ) .., ?

, , . , .

SRP, , - , , KISS. , , , . , , , , , , .

, , () ; .

+2

, SRP , hard, . " " ( ) .

( !) . : , , A, B, C,... A, B, C,...

, "". ""! , - ItemAdderService!

+1

Source: https://habr.com/ru/post/1656385/


All Articles