주제: coding-practice
-
파이썬 명령줄 도구 설계하기: argparse, main(), 종료 코드
인터페이스는 콘솔 스크립트로 등록한 main(argv) -> int 함수 안에 두고, argparse의 type과 choices로 값을 검증하고, 종료 코드 관례(0은 성공, 2는 사용법 오류, 1은 그 외 실패, sysexits 코드는 문서화한 경우에만)를 따르고, 결과는 stdout에 진단 메시지는 stderr에 남기고, SIGINT와 broken pipe를 처리합니다.
-
.NET 의존성 주입 관례: 라이프타임, 스코프, 그리고 captive dependency 함정
Microsoft.Extensions.DependencyInjection은 IServiceCollection에 transient, scoped, singleton 라이프타임으로 서비스를 등록하고, 공개 생성자를 통해 주입합니다. 문서화된 규칙은 scoped 서비스를 singleton에 주입하지 말 것, 컨테이너가 만든 것은 컨테이너가 정리하게 둘 것, 서비스 로케이터 방식의 호출을 피할 것, 그리고 스코프 검증을 켜서 captive dependency가 요청 사이에 상태를 누출시키는 대신 시작 시점에 바로 실패하게 할 것입니다.
-
Comments that carry information the code cannot
Write comments for why, for constraints and for non-obvious consequences; do not restate what the code says. Keep comments next to the code they describe, delete them when the reason disappears, and prefer a better name or a test to a comment.
-
Refactoring in small, verified steps
Refactoring changes structure without changing behaviour; doing it in tiny steps with tests green between steps, and separating refactoring commits from behaviour changes, keeps it safe and reviewable.
-
Technische Schulden als bewusste Entscheidung mit Buchführung
Cunninghams Metapher: Nicht ganz richtiger Code ist ein Kredit, jede Minute Mehrarbeit daran ist der Zins. Die Metapher trägt nur, wenn die Schuld bewusst aufgenommen, notiert und regelmässig bewertet wird; als Sammelbegriff für alles Unschöne oder als Entschuldigung für Schlamperei ist sie wertlos.
-
Working practices for an AI agent changing a codebase
Read before writing, reproduce before fixing, change in small verified steps, run the project's own checks, never retry writes blindly, and report exactly what was tested; a methodology for agents that edit code.
-
TypeScript narrowing: unions, unknown and any
TypeScript shrinks a union type inside a branch after typeof, instanceof, in, equality and truthiness checks or a user-defined type predicate; discriminated unions plus a never check give exhaustiveness. unknown accepts any value but forbids using it until narrowed, whereas any switches checking off.
-
Technical debt as a metaphor and as a decision
Technical debt describes the future cost of a shortcut; the metaphor is useful when the debt is deliberate and tracked, and misleading when it excuses careless work or is used to describe every imperfection.
-
Naming identifiers so that code reads as intent
Choose names that state what a thing is or does in the domain's vocabulary, at a length proportional to its scope; avoid encodings, abbreviations and misleading types, and rename as understanding improves.
-
Consistent naming and casing of JSON fields
Pick one case convention for property names and apply it everywhere: Google's JSON style guide and ProtoJSON use lowerCamelCase, many APIs use snake_case. Beyond case, keep names meaningful, enums as strings, timestamps as RFC 3339 strings and 64-bit integers as strings.
-
Context managers in Python: guaranteeing clean-up
The with statement runs __enter__ and __exit__ around a block so that files, locks and connections are released even when an exception occurs; contextlib.contextmanager turns a generator into one.
-
Validating JSON with JSON Schema
JSON Schema describes the allowed shape of a document (types, required keys, enumerations, formats, bounds) and lets any language validate inputs before processing them; keep additionalProperties explicit.
-
Docstrings that tools and readers can use
PEP 257 defines where docstrings go and how they are formatted; a consistent style (Google or NumPy) with a one-line summary, argument and return descriptions and raised exceptions makes them usable by readers, editors and documentation generators.
-
Floating-point numbers: why 0.1 + 0.2 is not 0.3
Binary floating point represents most decimal fractions approximately, so arithmetic accumulates rounding error; compare with tolerances, sum carefully, use integers or decimal types for money and counts, and print with enough digits to round-trip.
-
Automated formatting and linting as a team contract
Delegating layout to a formatter and mechanical checks to a linter removes style debates from review; EditorConfig, PEP 8 and tools such as Ruff show how the contract can be encoded in the repository.
-
Feature scaling and categorical encoding: what to transform, and fit it on training data only
Distance- and gradient-based models need numeric features on comparable scales (StandardScaler, MinMaxScaler, RobustScaler); categorical columns become numbers by one-hot, ordinal or target encoding depending on cardinality and model type. Every transformer is fitted on the training split and applied unchanged to validation, test and production rows.
-
Protocol classes: structural typing for duck-typed Python
A typing.Protocol declares the methods and attributes a consumer needs; any object that has them satisfies the type without inheriting from it. Define protocols next to the code that depends on them, keep them minimal, and use runtime_checkable only where isinstance is really needed.
-
Reproducibility of a machine-learning experiment: seeds, environment, data and the limits of determinism
Rerunning an experiment and getting the same number requires fixed random states passed explicitly, pinned library versions, an identified dataset and split, and awareness that GPU kernels and library releases can still change results; the protocol makes runs repeatable where possible and documents where they are not.
-
Structured extraction from documents with JSON Schema, validation and bounded retries
Define the target record as a JSON Schema with additionalProperties false, ask the model for exactly that shape, validate every response with a real validator, retry a bounded number of times with the validation error in the prompt, and route what still fails to a person instead of guessing.
-
NULL in SQL: three-valued logic and its traps
NULL means unknown, so comparisons with NULL yield unknown rather than true or false; WHERE filters drop unknown rows, NOT IN with a NULL matches nothing, and aggregates skip NULLs. Use IS NULL, IS DISTINCT FROM and COALESCE deliberately.
기계 판독 가능: JSON