Pitch.validated constructor

Pitch.validated({
  1. required String step,
  2. required int octave,
  3. double alter = 0.0,
  4. AccidentalType? accidentalType,
})

Creates a pitch after validating and normalizing its step.

The step is upper-cased before validation; a FormatException is thrown when it is not a diatonic letter or when octave falls outside the MIDI-representable range [-1, 10]. Parsers should prefer this factory over the raw constructor so malformed input fails with a clear message instead of an assertion or a later crash.

Implementation

factory Pitch.validated({
  required String step,
  required int octave,
  double alter = 0.0,
  AccidentalType? accidentalType,
}) {
  if (!isValidStep(step)) {
    throw FormatException(
      'Invalid pitch step "$step" (expected one of C D E F G A B)',
    );
  }
  if (octave < -1 || octave > 10) {
    throw FormatException(
      'Invalid octave $octave (expected a value between -1 and 10)',
    );
  }
  return Pitch(
    step: step.toUpperCase(),
    octave: octave,
    alter: alter,
    accidentalType: accidentalType,
  );
}