Course outline

Dart / Foundations: values, absence, collections, and valid objects / Lesson 7

Parse and validate a nullable quantity

Convert input text to an integer, reject invalid quantities explicitly, and branch before calculating.

About 22 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Distinguish parsing failure from domain validation.
  • Use a nullable return to represent rejection.
  • Test boundary values before calculating a total.
  • Trace normalization, parsing and domain checks for a nullable quantity.
  • Validate quantity and price independently before calculating an illustrative subtotal.

Define the input contract

A text field can contain whitespace, nonnumeric text, zero, or a valid integer. This example accepts a positive integer quantity and returns null for anything else. The unit price in the calculation is expressed in cents. Decide any product-specific maximum separately and document how the interface communicates rejection. Keeping input text separate from the numeric domain value makes the calculation easier to test.

Parse then check the domain

int.tryParse returns null when it cannot parse the trimmed text. The function also rejects values below one; successful parsing alone would allow zero and negative values. The first program prints the result of one accepted and one rejected input. It does not enforce a maximum or validate price, so an application must add those rules before using the result in a real order.

dart Parse a positive quantity
int? parseQuantity(String text) {
  final value = int.tryParse(text.trim());
  if (value == null || value < 1) return null;
  return value;
}

void main() {
  print(parseQuantity(" 3 "));
  print(parseQuantity("0"));
}

tryParse handles malformed text and the range check rejects nonpositive values.

Branch before calculating

The second complete program repeats the small parser and checks the nullable result before multiplying. The invalid branch prints a diagnostic rather than inventing a total; the valid branch uses the promoted non-null value. A return of null is only one possible error contract. If callers need to distinguish empty, malformed, and out-of-range input, use a more descriptive result type and handle every variant.

dart Branch on the nullable result
int? parseQuantity(String text) {
  final value = int.tryParse(text.trim());
  if (value == null || value < 1) return null;
  return value;
}

void main() {
  final quantity = parseQuantity("3");
  if (quantity == null) {
    print("invalid quantity");
  } else {
    print(quantity * 250);
  }
}

The null branch prevents an invalid quantity from entering the calculation.

Separate feedback from trust

A user interface can validate early to provide feedback, but a server or other receiving boundary must still validate its own inputs. Check the price and safe product under the platform and domain assumptions; a valid quantity alone does not guarantee a valid order. Avoid logging private input, and keep the original text available for a user to correct instead of replacing it silently.

Verify boundary cases

Test an empty string, whitespace, "3", "0", a negative number, a fraction, and nonnumeric text. Confirm accepted input reaches the calculation and rejected input takes the error branch. Add tests for the chosen upper bound and for zero price if that is a valid domain case. Run the programs with the project’s declared Dart SDK and record the environment when reporting results.

Write the quantity contract before parsing

A text input and an accepted quantity are different things. The baseline function accepts a String, trims leading and trailing whitespace, parses an integer, and returns it only when it is at least one. Its nullable int result combines malformed text and nonpositive numbers into one rejection. That is a useful small interface when the caller needs only accept or reject, but it does not explain which rule failed. Decide whether an upper limit, allowed signs, leading zeros or special numeric syntax are part of the real product contract.

Write down examples before implementing: whitespace around 3 becomes 3, zero parses but violates positivity, and a fraction is not an integer literal. Empty and whitespace-only strings produce no integer after trimming. If the text can itself be absent, use String? and handle null before invoking trim. Do not confuse an absent text value with an entered zero, or an invalid quantity with a valid order whose unit price happens to be zero.

Separate normalization, syntax and domain

String.trim returns a new string with leading and trailing whitespace removed; it does not remove characters inside the number. int.tryParse then follows its integer syntax rules and returns null for a failed parse instead of throwing FormatException. A successful parse establishes an integer value, not permission to use it as an order quantity. Check the domain range after parsing, and keep the original input if the user must edit it.

The baseline does not impose an upper bound. A bounded example might deliberately accept 1 through 10 inclusive: 1 and 10 pass, while 0 and 11 fail even though both parse. The limit is an illustrative policy, not a claim about a real product. If only decimal digits are allowed, validate that syntax explicitly rather than assuming every format accepted by the parser matches the product policy. State whether signs or leading zeros are accepted and test that decision.

Use nullable values deliberately

Dart types are non-nullable by default; int? permits either an integer or null. A local final result checked against null can be used as a non-null integer in the appropriate branch, allowing multiplication without a forced unwrap. The exclamation operator asserts non-null and can fail at runtime if the assumption is wrong. Avoid replacing every rejection with zero: that changes the business meaning and can produce a plausible total for an invalid order.

A nullable result intentionally loses detail. If callers need separate messages for missing text, malformed syntax and an out-of-range number, return a structured result or maintain distinct branches before collapsing to a simpler interface. Do not show raw exception details to users merely to distinguish cases. The selected representation should make invalid paths explicit while keeping an accepted quantity available only when validation succeeded.

Validate the rest of the calculation

A valid quantity does not validate price, currency, stock or the resulting total. For a synthetic example, accept a nonnegative integer unit price in cents and multiply it only after both inputs pass their rules. A zero price may be valid even though a zero quantity is not; those are different fields with different contracts. A negative price must be rejected if the policy forbids it. The examples are teaching calculations, not payment or inventory systems.

The appropriate maximum and arithmetic constraints depend on the target platform and business domain. Define quantity and price limits and check the product under the supported numeric representation before performing a real calculation; do not infer financial correctness from a small example. Client-side feedback can improve usability, but the receiving trust boundary must validate again because clients and transmitted values can change. Avoid logging sensitive raw input.

Build a decision table for verification

Test the parser at each stage: null input if supported, empty and whitespace text, malformed and fractional text, a signed negative number, zero, one, the chosen maximum and one above it. Include the accepted 3 surrounded by spaces and confirm the original string remains available if the interface needs correction. Check both the returned value and whether the calculation was reached; a correct-looking number alone can hide a fallback.

Test a valid quantity with zero price separately from an invalid quantity, and test a forbidden negative price. Verify client and receiving-boundary rules independently. The marked standalone programs were run with synthetic inputs on Dart 3.13.7 stable Linux x64; these checks do not establish production order behavior.

Walk through a bounded order calculation

The quantity function first handles absent text, then trims and tries to parse it. A null parse result, a number below 1 or a number above the illustrative maximum 10 returns null. The total function branches on that nullable result before multiplication and independently rejects a negative unit price. With " 3 " and 250 cents it calculates 750; quantity "0" is rejected; quantity "2" with a zero price produces a valid total of zero.

The maximum and nonnegative-price rules belong to this local example. Real applications must specify their own limits, currency and numeric bounds and revalidate at the receiving boundary. Tests should also cover 1, 10, 11, malformed text and a negative price. The program does not perform payment or stock allocation; its displayed output was observed on Dart 3.13.7.

dart Walk through a bounded order calculation
int? quantity(String? text) {
  if (text == null) return null;
  final value = int.tryParse(text.trim());
  if (value == null || value < 1 || value > 10) return null;
  return value;
}
String total(String? text, int unitCents) {
  final q = quantity(text);
  if (q == null) return 'invalid quantity';
  if (unitCents < 0) return 'invalid price';
  return 'total: ${q * unitCents}';
}
void main() {
  print(total(' 3 ', 250));
  print(total('0', 250));
  print(total('2', 0));
}
Expected output
total: 750
invalid quantity
total: 0

The exact program produced the displayed output with Dart 3.13.7 on Linux x64; the surrounding walkthrough explains its decisions.

20 worked examples

1. Trim whitespace-only input

Problem: Determine the result of parsing a field containing only spaces.

  1. trim removes the leading and trailing spaces, leaving an empty string.
  2. tryParse cannot parse the empty string and returns null.
dart Trim whitespace-only input
void main() {
  final text = '   ';
  print(int.tryParse(text.trim()));
}
Expected output
null

Normalization cannot turn an empty field into a valid integer. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Normalization cannot turn an empty field into a valid integer.

2. Reject alphabetic text

Problem: Parse a nonnumeric quantity without throwing for invalid syntax.

  1. The word dozen is not a valid integer literal.
  2. tryParse returns null, which the caller can classify as rejection.
dart Reject alphabetic text
void main() {
  final value = int.tryParse('dozen');
  print(value == null ? 'invalid' : 'accepted');
}
Expected output
invalid

The nullable result separates failed parsing from numeric values. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: The nullable result separates failed parsing from numeric values.

3. Reject a parsed negative

Problem: Apply the positive quantity policy to -4.

  1. tryParse successfully returns the integer -4.
  2. The value is below one, so the domain check rejects it.
dart Reject a parsed negative
void main() {
  final value = int.tryParse('-4');
  print(value != null && value >= 1 ? 'accepted' : 'rejected');
}
Expected output
rejected

Successful parsing does not establish a positive quantity. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Successful parsing does not establish a positive quantity.

4. Accept a signed positive integer

Problem: Parse +4 and apply the positive policy.

  1. The plus sign is accepted as part of this integer literal.
  2. The parsed value 4 satisfies the minimum of one.
dart Accept a signed positive integer
void main() {
  final value = int.tryParse('+4');
  print(value != null && value >= 1 ? value : null);
}
Expected output
4

Parsing and the policy together admit this signed positive value. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Parsing and the policy together admit this signed positive value.

5. Reject fractional syntax

Problem: Check whether 2.5 can enter an integer quantity calculation.

  1. The decimal point makes 2.5 unsuitable for int.tryParse.
  2. The parser returns null rather than silently rounding or truncating.
dart Reject fractional syntax
void main() {
  print(int.tryParse('2.5'));
}
Expected output
null

Integer parsing does not choose a fractional rounding policy. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Integer parsing does not choose a fractional rounding policy.

6. Interpret leading zeros

Problem: Parse the decimal text 003 under the default radix.

  1. The text is a valid decimal integer representation.
  2. Its parsed numeric value is 3; formatting zeros are not retained in the integer.
dart Interpret leading zeros
void main() {
  print(int.tryParse('003'));
}
Expected output
3

Parsing produces a value rather than preserving input formatting. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Parsing produces a value rather than preserving input formatting.

7. Reject above a chosen maximum

Problem: Apply an illustrative 1 through 10 limit to parsed quantity 11.

  1. The syntax parses successfully as integer 11.
  2. The upper-bound comparison rejects 11 because it exceeds 10.
dart Reject above a chosen maximum
void main() {
  final n = int.tryParse('11');
  print(n != null && n >= 1 && n <= 10 ? 'accepted' : 'range');
}
Expected output
range

A documented maximum is a separate domain rule. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: A documented maximum is a separate domain rule.

8. Check inclusive endpoints

Problem: Evaluate quantities 1 and 10 against the same illustrative range.

  1. The lower comparison permits 1 because it uses >=.
  2. The upper comparison permits 10 because it uses <=.
dart Check inclusive endpoints
bool allowed(int n) => n >= 1 && n <= 10;
void main() {
  print(allowed(1));
  print(allowed(10));
}
Expected output
true
true

Inclusive operators accept both specified boundary values. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Inclusive operators accept both specified boundary values.

9. Branch before multiplication

Problem: Calculate a total only after parsing quantity 2 successfully.

  1. The nullable result is checked against null before multiplication.
  2. The non-null branch multiplies 2 by 150 to produce 300 cents.
dart Branch before multiplication
void main() {
  final q = int.tryParse('2');
  if (q == null) { print('invalid'); } else { print(q * 150); }
}
Expected output
300

Flow analysis permits use of the checked local value in the valid branch. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Flow analysis permits use of the checked local value in the valid branch.

10. Avoid force-unwrapping a rejection

Problem: Handle malformed quantity text without using the null assertion operator.

  1. tryParse returns null for no.
  2. The null branch prints invalid and never attempts arithmetic.
dart Avoid force-unwrapping a rejection
void main() {
  final q = int.tryParse('no');
  if (q == null) { print('invalid'); } else { print(q * 150); }
}
Expected output
invalid

A branch handles rejection without assuming a non-null result. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: A branch handles rejection without assuming a non-null result.

11. Accept a zero unit price

Problem: Calculate a valid quantity of three with a free unit price.

  1. The quantity 3 is positive and the example permits nonnegative prices.
  2. Multiplying 3 by zero produces a valid zero-cent total.
dart Accept a zero unit price
void main() {
  const q = 3;
  const unitCents = 0;
  print(q * unitCents);
}
Expected output
0

A valid free price is distinct from a rejected zero quantity. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: A valid free price is distinct from a rejected zero quantity.

12. Reject a negative unit price

Problem: Check a separately supplied price before calculating a subtotal.

  1. The quantity is positive, but the unit price -5 violates the nonnegative policy.
  2. The price branch reports invalid price and skips multiplication.
dart Reject a negative unit price
void main() {
  const q = 2;
  const price = -5;
  if (price < 0) { print('invalid price'); } else { print(q * price); }
}
Expected output
invalid price

Quantity validation alone cannot validate a price. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Quantity validation alone cannot validate a price.

13. Compute a small subtotal in cents

Problem: Multiply four accepted items by a unit price of 125 cents.

  1. Both values satisfy this example’s positive quantity and nonnegative price rules.
  2. Four times 125 is 500 cents.
dart Compute a small subtotal in cents
void main() {
  const quantity = 4;
  const unitCents = 125;
  print(quantity * unitCents);
}
Expected output
500

Integer units and cents make the small example’s arithmetic explicit. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Integer units and cents make the small example’s arithmetic explicit.

14. Handle absent input before trim

Problem: Classify a null text field separately from parsing.

  1. The text reference is null, so the conditional does not call trim.
  2. The function returns missing instead of attempting integer parsing.
dart Handle absent input before trim
String classify(String? text) {
  if (text == null) return 'missing';
  return int.tryParse(text.trim()) == null ? 'invalid' : 'parsed';
}
void main() { print(classify(null)); }
Expected output
missing

A nullable source requires an absence policy before string methods. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: A nullable source requires an absence policy before string methods.

15. Return separate rejection categories

Problem: Classify an empty field and a parsed negative quantity.

  1. An empty trimmed field returns the empty category before parsing.
  2. The text -2 parses but fails the minimum and returns range.
dart Return separate rejection categories
String classify(String text) {
  final normalized = text.trim();
  if (normalized.isEmpty) return 'empty';
  final n = int.tryParse(normalized);
  if (n == null) return 'syntax';
  return n < 1 ? 'range' : 'accepted';
}
void main() {
  print(classify('  '));
  print(classify('-2'));
}
Expected output
empty
range

Distinct outcomes give callers more precise feedback than null alone. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Distinct outcomes give callers more precise feedback than null alone.

16. Retain the original text

Problem: Normalize a copy of an input while preserving the user’s original string.

  1. trim returns a new string containing 8 without its outer spaces.
  2. The original variable still holds the untrimmed text and has length three.
dart Retain the original text
void main() {
  final original = ' 8 ';
  final normalized = original.trim();
  print(normalized);
  print(original.length);
}
Expected output
8
3

String normalization does not mutate the original value. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: String normalization does not mutate the original value.

17. Revalidate at the receiving boundary

Problem: Reject a transmitted quantity of 0 despite a client’s earlier validation.

  1. The receiving function independently parses the submitted text 0.
  2. Its positive check rejects zero instead of trusting a previous client decision.
dart Revalidate at the receiving boundary
bool receive(String text) {
  final n = int.tryParse(text);
  return n != null && n >= 1;
}
void main() { print(receive('0')); }
Expected output
false

The receiving boundary owns its own validation contract. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: The receiving boundary owns its own validation contract.

18. Account for a small quantity batch

Problem: Count accepted positive inputs and rejected inputs in a batch.

  1. The inputs 2 and 1 parse as positive quantities.
  2. The text x fails parsing and 0 fails the domain rule, giving two rejections.
dart Account for a small quantity batch
void main() {
  var accepted = 0;
  var rejected = 0;
  for (final text in ['2', 'x', '0', '1']) {
    final n = int.tryParse(text);
    if (n != null && n >= 1) { accepted++; } else { rejected++; }
  }
  print(accepted);
  print(rejected);
}
Expected output
2
2

Counting both categories accounts for all four inputs. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Counting both categories accounts for all four inputs.

19. Specify a radix deliberately

Problem: Parse the binary digits 101 with an explicit radix.

  1. The radix argument tells tryParse to interpret the digits in base two.
  2. Binary 101 represents four plus one, so the result is 5.
dart Specify a radix deliberately
void main() {
  print(int.tryParse('101', radix: 2));
}
Expected output
5

Radix changes the interpretation and should follow the input contract. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Radix changes the interpretation and should follow the input contract.

20. Integrate quantity and price validation

Problem: Evaluate an order with quantity 10 and unit price 20 cents under a maximum of 10.

  1. The parsed quantity 10 meets both inclusive quantity bounds.
  2. The nonnegative price 20 passes its own rule, so the subtotal is 200 cents.
dart Integrate quantity and price validation
void main() {
  final q = int.tryParse('10');
  const price = 20;
  if (q == null || q < 1 || q > 10 || price < 0) {
    print('invalid');
  } else { print(q * price); }
}
Expected output
200

Both field contracts are checked before the small calculation. The exact program produced the shown output with Dart 3.13.7 on Linux x64.

Why this result follows: Both field contracts are checked before the small calculation.

Common errors and fixes

A numeric zero is accepted as a positive quantity

Why it happens
Parsing success was mistaken for domain validity.
How to fix it
Check the positive range after parsing.
Prevent it next time
Test zero and negative inputs separately.

A null result is force-unwrapped

Why it happens
The caller assumed parsing could not fail.
How to fix it
Branch on null and report an invalid input.
Prevent it next time
Test malformed and empty text through the public call.

A rejected quantity appears as a free order

Why it happens
The caller substituted zero for every parsing failure.
How to fix it
Keep rejection distinct from a valid zero-price calculation.
Prevent it next time
Test invalid quantity and valid free price as separate cases.

20 practice exercises

1. What does parseQuantity(" 3 ") return?

Show hint

Trace trim, parsing and the minimum check in order.

Show worked solution

It trims the spaces, parses integer 3, and returns it because it is positive. The caller can then calculate with the numeric value.

The surrounding spaces are removed to produce "3". int.tryParse returns integer 3, and the minimum check accepts it because 3 is at least 1. The function returns 3, not the original text or null.

Check your solution

  • The trimmed text is "3".
  • The returned value is integer 3.

2. Why does parseQuantity("0") return null?

Show hint

Ask whether zero fails parsing or the subsequent rule.

Show worked solution

Zero parses successfully but violates this example’s positive-quantity rule. The null result signals rejection; it must not be treated as a valid free order.

int.tryParse("0") succeeds and produces 0. The following value < 1 condition is true, so the positive-quantity contract returns null. This rejection differs from a valid order with a positive quantity and a zero unit price.

Check your solution

  • Parsing "0" yields integer 0.
  • The domain check returns null because 0 is below 1.

3. A field contains three spaces. Return an empty-field message rather than a generic numeric syntax message.

Show hint

Trim and check isEmpty before parsing.

Show worked solution

Trim the input and test isEmpty before int.tryParse. Three spaces become empty, so return the empty-field message; a nonempty malformed value such as x should proceed to the separate syntax rejection. Keep the original text for correction if needed.

Check your solution

  • Three spaces produce empty-field feedback.
  • x produces syntax feedback rather than empty-field feedback.

4. Compare +7, -7 and 7x under a positive integer policy, identifying syntax and range failures.

Show hint

Parse each value before applying positivity.

Show worked solution

tryParse accepts +7 and -7 as signed integers but returns null for 7x. Accept 7, reject -7 as out of range and reject 7x as malformed syntax. The two rejection reasons should remain distinct when feedback needs them.

Check your solution

  • +7 is accepted and -7 fails range.
  • 7x fails syntax.

5. A shop currently accepts whole quantities only. Compare how "2.9" and "3.0" behave under that rule and specify what must change before fractional quantities are accepted.

Show hint

Do not invent a rounding policy from integer parsing.

Show worked solution

Both strings fail the current integer syntax rule, even though 3.0 has a whole numerical value. A fractional-quantity feature needs an explicit decimal representation, precision, rounding and domain range, with independent tests; silently truncating either input would change the contract.

Check your solution

  • Both inputs are rejected by the current integer rule.
  • A fractional policy specifies precision and rounding before acceptance.

6. For an inclusive range 2–8, classify 1, 2, 8 and 9 and produce a report retaining each original index and range reason.

Show hint

Validate each integer and preserve its source position.

Show worked solution

Accept 2 at index 1 and 8 at index 2; reject 1 at index 0 and 9 at index 3 for range. Return indexed outcomes rather than silently filtering, and verify the four outcomes account for the four inputs.

Check your solution

  • The accepted indices are 1 and 2.
  • Indices 0 and 3 retain range rejections.

7. Distinguish a missing nullable text field from a present malformed field containing abc.

Show hint

Check the String? reference before invoking trim.

Show worked solution

If text is null, report missing without calling trim. Otherwise trim and use tryParse; abc returns null and receives a syntax message. Both may prevent calculation, but the user feedback identifies different corrective actions.

Check your solution

  • Null yields missing.
  • abc yields invalid syntax.

8. A caller uses parseQuantity("x")! * 50. Diagnose the failure and write a safe branching policy.

Show hint

The parser can return null; do not assert it away.

Show worked solution

The exclamation operator forces a non-null assumption, but malformed x causes the parser to return null, so the assumption fails at runtime. Store the result, branch on null and report invalid quantity; multiply by 50 only in the non-null branch.

Check your solution

  • x takes the rejection branch.
  • A valid quantity 2 produces 100.

9. Calculate a valid quantity 5 at zero cents per unit and contrast it with quantity 0 at the same price.

Show hint

Validate quantity independently from price.

Show worked solution

Quantity 5 passes positivity and a zero unit price is allowed by this policy, so its total is zero cents. Quantity 0 fails the quantity rule and must produce rejection, not another zero total that appears to be a free order.

Check your solution

  • Quantity 5 produces a valid total of 0.
  • Quantity 0 is rejected.

10. A parsed quantity is 4 and price is -25 cents. Reject the price before computing, then evaluate a corrected price of 25.

Show hint

The price has its own nonnegative rule.

Show worked solution

Reject -25 as an invalid price without multiplying. With the corrected nonnegative price 25, multiply 4 by 25 to get 100 cents. A valid quantity does not authorize a negative price or prove the rest of the order is valid.

Check your solution

  • The negative price takes a rejection path.
  • The corrected price produces 100 cents.

11. For lines ("2", 120), ("x", 50) and ("3", 40), calculate accepted subtotals and identify the rejected line.

Show hint

Branch on each parsed quantity before multiplication.

Show worked solution

The first line produces 240 cents and the third 120 cents. The second quantity cannot be parsed, so reject that line without inventing a subtotal. Keep its position in the report so the caller can correct it; accepted subtotal sum is 360 cents.

Check your solution

  • Accepted line subtotals are 240 and 120 cents.
  • The second line is rejected; accepted subtotals sum to 360.

12. Return separate empty, syntax and range messages for " ", "x" and "0" under a positive policy.

Show hint

Check trimmed emptiness, then parse, then compare the number.

Show worked solution

Whitespace becomes empty and receives empty feedback. x is nonempty but fails parsing and receives syntax feedback. 0 parses successfully but violates the positive range and receives range feedback; no rejected case reaches arithmetic.

Check your solution

  • The three outcomes are empty, syntax and range in order.
  • None of the three inputs produces a total.

13. A form has quantity " 6 " and signed token " A ". Normalize the quantity while preserving both original fields for correction and signature verification.

Show hint

Apply trim only to the field whose contract allows it.

Show worked solution

Keep both original strings unchanged. Parse a trimmed copy of the quantity to obtain 6, while passing the exact token " A " to signature verification; trimming that token could change its meaning. The numeric value and original form state have separate roles.

Check your solution

  • The quantity parses to 6 and its original text remains available.
  • The token retains both surrounding spaces.

14. A client validated 4, but the server receives 0; a later request contains valid 4 but the caller lacks permission. Define both receiver outcomes.

Show hint

Revalidate received data and check authorization independently.

Show worked solution

Reject the received 0 at the server’s quantity boundary despite the earlier client check. For the later valid 4, perform the authoritative permission check and reject if unauthorized. Syntax/domain validation and authorization are separate gates.

Check your solution

  • The received 0 fails the quantity rule.
  • The valid 4 is still rejected without permission.

15. For ["3", "bad", "0", "2"], report accepted values and original indices of syntax and range errors.

Show hint

Enumerate rather than filtering away positions.

Show worked solution

Accept 3 at index 0 and 2 at index 3. Record syntax rejection at index 1 and range rejection at index 2. The four outcomes account for all input positions, allowing the caller to correct the right fields.

Check your solution

  • Accepted pairs are (0, 3) and (3, 2).
  • Syntax index is 1 and range index is 2.

16. A product policy forbids leading zeros except for the single character 0. Classify 03, 3 and 0 before applying the positive rule.

Show hint

Validate the textual format separately from numeric value.

Show worked solution

Reject 03 for formatting, even though integer parsing would yield 3. Accept the format of 3 and 0; the subsequent positive quantity rule accepts 3 and rejects 0. This shows syntax policy and domain validation are separate.

Check your solution

  • 03 fails the formatting policy.
  • 3 is accepted and 0 fails positivity.

17. A decimal-only quantity contract forbids hexadecimal notation. Reject 0x10 even if the parser could interpret it.

Show hint

Validate allowed digits before calling tryParse.

Show worked solution

After trimming, require one or more ASCII decimal digits under this stated policy before parsing. The token 0x10 contains x and is rejected by the syntax policy; 10 passes that check and parses as decimal ten, subject to the quantity range.

Check your solution

  • 0x10 is rejected as nondecimal syntax.
  • 10 parses to ten before range validation.

18. A target has a documented maximum safe subtotal M. Explain how to check quantity q and nonnegative unit price p before multiplication.

Show hint

For positive p, compare q with an integer bound derived from M.

Show worked solution

Validate q and p first. If p is zero the subtotal is zero; otherwise require q <= M ~/ p before multiplying, provided M and the operands are within the target’s documented representable bounds. Reject larger values rather than relying on an overflowed product.

Check your solution

  • For M=100, q=5 and p=20 the product 100 is allowed.
  • For M=100, q=6 and p=20 the request is rejected.

19. Repair int.tryParse(text) ?? 0 when zero is a valid numeric value but malformed text must be rejected.

Show hint

Preserve null until the failure branch is handled.

Show worked solution

Store the nullable result and branch on null before using it. Text "0" parses to a valid zero, while "bad" yields null and receives an invalid-input outcome. Replacing null with zero erases this difference and may create a false success.

Check your solution

  • "0" yields numeric zero.
  • "bad" is rejected instead of becoming zero.

20. Design a 1–6 quantity and nonnegative-price order boundary. Classify ("6", 10), ("7", 10), ("2", -1), and ("2", 0).

Show hint

Check parse, quantity bounds and price before multiplication.

Show worked solution

Accept the first pair with total 60; reject the second for quantity above six and the third for negative price. Accept the fourth as a valid free order with total zero. Keep each rejection distinct from either accepted total and apply target-specific numeric bounds in production.

Check your solution

  • The accepted totals are 60 and 0 cents.
  • The other pairs fail quantity and price respectively.

Key takeaways

  • Parse text and validate the domain as separate steps.
  • Handle nullable rejection before performing a calculation.
  • A parsed integer may still fail the quantity range.
  • Handle null before arithmetic instead of substituting a plausible value.
  • A free unit price and a rejected quantity represent different outcomes.

Official references