Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Static check
- Analysis of source against the selected language rules before execution; the shown ordinary runtime branches are included.
- Dynamic check
- A check of values or an operation while the program runs.
- Type assertion
- An operation that states or checks an expected type; its effect depends on the native language and form used.
- Parse
- Convert text into a value under a particular grammar, with the conversion’s own success/failure behavior.
- Bounds check
- Establish that an index lies in the collection’s valid range.
Three places to establish a guarantee
Static checking reasons about source before execution, using declared and inferred types. Runtime checks inspect an operation or value during execution. A program can pass its source checker and still encounter an out-of-range index or outside data that does not satisfy its assumptions.
Application validation adds the rules for acceptable input: its shape, token format and allowed range. Establish which layer checks each requirement and how failure is represented. A converted number alone may not carry enough information to decide whether an import succeeded.
01Before the run
Check a branch this run does not take
A rail reservation importer totals passenger-count requests, combines boarding counts with operational notes, and answers berth-number lookups. Zero can clear a request; malformed count text must be reported as skipped. Before repairing those entry points, the team needs to establish which mistakes its checker catches and which require inspecting a running value.
The boarding announcement helper has a special branch for waits over 60 minutes. The call supplies 15 minutes. Inspect both branches and predict the result of the selected check/build-and-run command.
package main
import "fmt"
func boardingText(gate string, minutes int) string {
if minutes > 60 {
return "Gate " + gate + minutes
}
return fmt.Sprintf("Gate %s in %d minutes", gate, minutes)
}
func main() {
fmt.Println(boardingText("B4", 15))
}
go run main.go
Save one complete example at a time under the selected filename, using the language setup from the first reading. The shown command runs only after its check/build step succeeds. Predict that result before executing the example.
02While it runs
An outside index needs a runtime policy
The lookup probe reads gate 1 and then gate 3 from a three-element list. Compare the operations shown in the selected native; they need not fail at the same point.
package main
import "fmt"
func main() {
gates := []string{"A1", "B2", "C3"}
row := 3
fmt.Println(gates[1])
fmt.Println(gates[row])
}
03Values from outside
A declared type does not validate an imported value
A transport seat count arrives as text or JSON. Each probe uses its selected conversion or assertion, then reports the result. Predict what the operation actually establishes.
package main
import (
"encoding/json"
"fmt"
)
func main() {
var flight map[string]any
json.Unmarshal([]byte(`{"code": "NT7", "seats": 155}`), &flight)
seats, ok := flight["seats"].(int)
fmt.Println(seats, ok)
asFloat, ok := flight["seats"].(float64)
fmt.Println(asFloat, ok)
}
04Where to check
Carry conversion success separately from the count
parsePassengers reports results for the literal strings 12, x and 0. Predict those lines, including the valid zero. These are conversion probes; the import file’s complete token format is a separate requirement.
package main
import (
"fmt"
"strconv"
)
func parsePassengers(text string) (int, bool) {
passengers, err := strconv.Atoi(text)
return passengers, err == nil && passengers >= 0
}
func main() {
for _, text := range []string{"12", "x", "0"} {
if passengers, ok := parsePassengers(text); ok {
fmt.Printf("%s: %d\n", text, passengers)
} else {
fmt.Printf("%s: invalid\n", text)
}
}
}
05Repair the rail reservation importer
Passenger requests, boarding records, then berth lookup
Total passenger-count requests in the reservation file, count malformed count tokens as skipped, and keep zero as a real value. The existing file format is one nonempty ASCII digit token: leading zeros are valid, while signs, fractions and numeric prefixes are not.
Then combine typed boarding-count records while leaving operational notes out of the total. Finally answer signed one-based berth requests against the supplied manifest. Complete readers and callers are supplied; notes and missing berths require their own policy.
Repair the rail reservation importer
Validate a complete count token, distinguish a boarding entry’s kind, then check signed requests against existing berths.
In the frontend A typed component can still hold an unconverted form string. Optional
The import screen keeps the count text exactly as typed until its submission boundary applies the file-format policy. Giving the parent or component a TypeScript type does not change the runtime value supplied by a text input.
'use client';
import { useState } from 'react';
export function CountText() {
const [text, setText] = useState('0');
return (
<label>
Passenger request
<input
type="text"
value={text}
onChange={(event) => setText(event.target.value)}
/>
<output>{text.length} UTF-16 code units</output>
</label>
);
}
The input event supplies a string, and the setter retains that string for a subsequent render. Starting with "0" does not make later input a number or establish the request format.
Sources: React: input value,Svelte: input bindings.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?