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){
return;
}
if(item is 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)
{
}
}
public class BackpackItem: Item
{
public BackpackItem(String name)
{
Name = name;
}
public override void AddToHero(Hero hero)
{
}
}
: add Item, .
: SRP, , .
? ( ?)