Question about class cohesion and readability

Hello!

When taking on the challenge, I was thinking of improving cohesion of the character class by doing something like this:

public class LowCohesionCharacter : MonoBehaviour
{
    [SerializeField] Animator animator;
    [SerializeField] AudioSource audioSource;
    [SerializeField] AudioClip shout;

    private float health = 100f;

    public void TakeHit()
    {
        KnockBack();
        Shout();
        TakeDamage();
    }

    private void KnockBack()
    {
        animator.SetTrigger("KnockBack");
    }

    private void Shout()
    {
        audioSource.PlayOneShot(shout);
    }

    private void TakeDamage()
    {
        health -= 10;
    }
}

My idea was that I wanted my public method to really read like English to be instantly understandable.
But I can see that it might be overkill in this case.

My question is: does this count as a low cohesion class?
I think I understand clearly where the risk is with tightly coupled classes, but I have a bit more difficulty in seeing the risks in low coherent classes in this example.

Cheers! :smile:

That is exactly how it should be done: you should bake your intent in your method name and such, so you don’t need comment and anything. Then when calling the methods, you know exactly what they are intended to do - like for example “TakeDamage” as opposed to “health -= 10”.

Great job!

EDIT: for more clarity, you could even use the “=>” symbol for one line methods:

public class LowCohesionCharacter : MonoBehaviour
{
    [SerializeField] Animator animator;
    [SerializeField] AudioSource audioSource;
    [SerializeField] AudioClip shout;

    private float health = 100f;

    public void TakeHit()
    {
        KnockBack();
        Shout();
        TakeDamage();
    }

    private void KnockBack() => animator.SetTrigger("KnockBack");

    private void Shout() => audioSource.PlayOneShot(shout);

    private void TakeDamage() => health -= 10;
}
2 Likes

Awesome, thanks a lot for your answer! And I always forget about the “=>” symbol for one-line methods, it is indeed quite handy!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms