Terminology (4)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.
- Module
- A file or package with its own names; other code sees only what it exposes.
- Export
- Marking a name so code outside its module may use it.
- Encapsulation
- Putting data and the operations responsible for it behind an API with a stated contract.
- #private field
- A JavaScript field private at run time, unlike TypeScript’s compile-time private.
What a public boundary controls
A public API is the set of definitions callers may use across a module or object boundary. Encapsulation keeps implementation choices behind that API and gives state changes a controlled route. A hidden field can still be reachable through a returned reference, so inspect both the visible names and the values an operation hands back.
TypeScript modules expose named bindings with export. Class private restricts checked TypeScript access, while JavaScript # fields enforce private names at runtime. Neither choice alone specifies whether a returned object is shared or independent.
01Exported names
Choose the pricing names the receipt may depend on
A bakery needs a receipt calculator that callers can use without depending on its pricing helpers. A second report must sort the recorded item names without changing till order. Order creation then needs a clear refusal path for quantities below one. These jobs use separate small projects with a supplied main and a shop API.
The receipt needs the shop’s price calculation. This reduced probe also tries to call its rounding helper directly. Trace both names across the file boundary before predicting the result.
shop/pricing.ts exports price; roundUp has no export.
import { price, roundUp } from "./shop/pricing";
console.log(price(3));
console.log(roundUp(2.5));
// ── shop/pricing.ts ──
function roundUp(value: number): number {
return Math.ceil(value);
}
export function price(units: number): number {
return roundUp(units * 1.5);
}
npx tsc --strict --target ES2022 --module Node16 --moduleResolution Node16 --types node --outDir out main.ts && node out/main.js
Start each probe in a fresh project directory. The first part is the entry file; each `// ── path ──` marker starts another file. For TypeScript, use the declared ES2022 CommonJS workflow with local TypeScript and Node types; set package.json’s type field to commonjs while preserving its other fields. For Go, initialize the module as lab. Rust uses main.rs and edition 2024. The first C++ probe builds main.cpp with shop/pricing.cpp; the later header-only probes build main.cpp alone with the same declared flags.
02Hidden fields
Trace the access path to a hidden field
The shop also stores a stock count. Before relying on an update method, check what happens when an outside caller tries to write the hidden field directly. Visibility and checking a proposed value are separate decisions.
count is declared private; main writes it through (stock as any).
import { Stock } from "./shop/stock";
const stock = new Stock(5);
(stock as any).count = -3;
console.log(stock.report());
// ── shop/stock.ts ──
export class Stock {
private count: number;
constructor(count: number) {
this.count = count;
}
report(): string {
return `count ${this.count}`;
}
}
03What a module hands out
A private list is still exposed when a method returns the list itself
The report needs item names, so Shelf has an accessor. Before handing its result to a sorting report, test whether the returned access path permits an element write and which stored data that write reaches.
items() returns this.#items.
import { Shelf } from "./shop/shelf";
const shelf = new Shelf(["apple", "fig"]);
shelf.items()[0] = "pear";
console.log(shelf.describe());
// ── shop/shelf.ts ──
export class Shelf {
#items: string[];
constructor(items: string[]) {
this.#items = [...items];
}
items(): string[] {
return this.#items;
}
describe(): string {
return this.#items.join(" ");
}
}
04Repair the bakery till
Export what main needs, hand out a copy, refuse invalid orders
The bakery needs three focused repairs in separate supplied projects. Expose a line-total calculator, including signed adjustments. Give a sorting report independent mutable item data while preserving till order. Then make the supplied order-creation API refuse quantities below one.
This lab is a small project: the editor has a tab for each file. Files marked supplied are read-only. Run and Check compile all the files together.
Repair the bakery till
Make receipt calculation callable, preserve till order during reporting and handle refusal when an order is requested.
In the frontend A component exposes a rendering API while keeping a formatting binding local. Optional
A receipt component can accept an amount through props while keeping its formatting helper local to the file. This controls which names another module imports; bundled helper code is still available to the runtime.
function formatAmount(amount: number) {
return `${amount} credits`;
}
export default function ReceiptAmount({ amount }: { amount: number }) {
return <p>{formatAmount(amount)}</p>;
}
Another module imports ReceiptAmount and supplies amount. formatAmount is a module-local binding because it has no export; the component calls it while rendering.
Sources: React: importing and exporting components,Svelte: $props.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?