Potential Violation Of the Single Responsibility Principle

The current implementation of HealthEffect.cs handles both healing and damage, which can be seen as a violation of the single responsibility principle as it emphasizes two responsibilities.
To adhere to this principle while avoiding code duplication, I found this solution through online research:

using RPG.Attributes;
using System;
using UnityEngine;

namespace RPG.Abilities.Effects
{
    public abstract class HealthBaseEffect : EffectStrategy
    {
        [SerializeField] protected float healthChange = 0f;

        public override void StartEffect(AbilityData abilityData, Action finished)
        {
            foreach (var gameObject in abilityData.GameObjects)
            {
                if (gameObject.TryGetComponent<Health>(out var health))
                {
                    ApplyEffect(abilityData, health);
                }
            }

            finished?.Invoke();
        }

        public abstract void ApplyEffect(AbilityData abilityData, Health health);
    }
}

And creating different effect strategies like healing or damaging this way:

using RPG.Attributes;
using UnityEngine;

namespace RPG.Abilities.Effects
{
    [CreateAssetMenu(fileName = "Healing Effect", menuName = "GameDevTV/GameDevTV.UI.InventorySystem/Action Item/Abilities/Effects/Healing", order = 2)]
    public class HealingEffect : HealthBaseEffect
    {
        public override void ApplyEffect(AbilityData abilityData, Health health)
        {
            health.Heal(healthChange);
        }
    }
}
using RPG.Attributes;
using UnityEngine;

namespace RPG.Abilities.Effects
{
    [CreateAssetMenu(fileName = "Damage Effect", menuName = "GameDevTV/GameDevTV.UI.InventorySystem/Action Item/Abilities/Effects/Damage", order = 5)]
    public class DamageEffect : HealthBaseEffect
    {
        public override void ApplyEffect(AbilityData abilityData, Health health)
        {
            health.TakeDamage(abilityData.User, -healthChange);
        }
    }
}

This way, we can create complex behaviours by combining these effects easier.
An typical example would be if you have an ability that shoots an arrow which deals damage and then heals the character, you could implement this by having both a DamageEffect and a HealingEffect on the ability

2 Likes

Privacy & Terms