Let's apply the "Naming as a Process" approach to refactor this code:
- First, let's extract the main logic into a separate method with an "obvious nonsense" name:
Sprite.OnLastFrame = (anim) =>
{
Applesauce();
};
private void Applesauce()
{
if (Scene != null && !Dead && Sprite.CurrentAnimationID == "idle" && !level.InCutscene && idleTimer > 3f)
{
if (Calc.Random.Chance(0.2f))
{
var next = "";
if (Sprite.Mode == PlayerSpriteMode.Madeline)
next = (level.CoreMode == Session.CoreModes.Hot ? idleWarmOptions : idleColdOptions).Choose();
else
next = idleNoBackpackOptions.Choose();
if (!string.IsNullOrEmpty(next))
{
Sprite.Play(next);
if (Sprite.Mode == PlayerSpriteMode.Madeline)
{
if (next == "idleB")
idleSfx = Play(Sfxs.char_mad_idle_scratch);
else if (next == "idleC")
idleSfx = Play(Sfxs.char_mad_idle_sneeze);
}
else if (next == "idleA")
idleSfx = Play(Sfxs.char_mad_idle_crackknuckles);
}
}
}
}
- Now, let's make the name honest:
private void probably_PlayRandomIdleAnimationAndSound_AndStuff()
- Let's make the name completely honest:
private void PlayRandomIdleAnimationAndSoundIfConditionsMet()
- Now, let's refactor to make it do the right thing:
Sprite.OnLastFrame = (anim) =>
{
PlayRandomIdleAnimationAndSoundIfConditionsMet();
};
private void PlayRandomIdleAnimationAndSoundIfConditionsMet()
{
if (!ShouldPlayIdleAnimation()) return;
var next = ChooseNextIdleAnimation();
if (string.IsNullOrEmpty(next)) return;
PlayIdleAnimation(next);
PlayIdleSound(next);
}
private bool ShouldPlayIdleAnimation()
{
return Scene != null && !Dead && Sprite.CurrentAnimationID == "idle" && !level.InCutscene && idleTimer > 3f && Calc.Random.Chance(0.2f);
}
private string ChooseNextIdleAnimation()
{
if (Sprite.Mode == PlayerSpriteMode.Madeline)
return (level.CoreMode == Session.CoreModes.Hot ? idleWarmOptions : idleColdOptions).Choose();
else
return idleNoBackpackOptions.Choose();
}
private void PlayIdleAnimation(string animationName)
{
Sprite.Play(animationName);
}
private void PlayIdleSound(string animationName)
{
if (Sprite.Mode == PlayerSpriteMode.Madeline)
{
if (animationName == "idleB")
idleSfx = Play(Sfxs.char_mad_idle_scratch);
else if (animationName == "idleC")
idleSfx = Play(Sfxs.char_mad_idle_sneeze);
}
else if (animationName == "idleA")
idleSfx = Play(Sfxs.char_mad_idle_crackknuckles);
}
- Make the names intent-revealing:
Sprite.OnLastFrame = (anim) =>
{
TryPlayIdleAnimationAndSound();
};
private void TryPlayIdleAnimationAndSound()