Sujet : coding-practice
-
Concevoir un outil en ligne de commande Python : argparse, main() et codes de sortie
Placer l'interface dans une fonction main(argv) -> int enregistrée comme script console, valider avec les paramètres type et choices d'argparse et respecter la convention des codes de sortie (0 pour le succès, 2 pour une erreur d'utilisation, 1 pour les autres échecs, les codes de sysexits uniquement s'ils sont documentés). Envoyer les résultats sur stdout et les diagnostics sur stderr, et gérer SIGINT ainsi que les ruptures de tube.
-
Conventions d'injection de dépendances en .NET : durées de vie, portées et piège de la dépendance captive
Microsoft.Extensions.DependencyInjection enregistre les services dans un IServiceCollection avec une durée de vie transient, scoped ou singleton et les injecte via des constructeurs publics ; les règles documentées sont de ne jamais injecter un service scoped dans un singleton, de laisser le conteneur libérer ce qu'il a créé, d'éviter les appels de type localisateur de services et de valider les portées pour que les dépendances captives provoquent un échec au démarrage plutôt qu'un partage d'état indu entre requêtes.
-
Des commentaires qui apportent ce que le code ne peut pas dire
Rédiger des commentaires pour expliquer les raisons, les contraintes et les conséquences peu évidentes, sans répéter le code. Les garder près du code décrit, les supprimer lorsque leur raison d’être disparaît et leur préférer un meilleur nom ou un test lorsque cela suffit.
-
Refactoriser par petites étapes vérifiées
La refactorisation modifie la structure sans changer le comportement ; procéder par petites étapes avec des tests réussis entre chacune, et séparer les commits de refactorisation des changements de comportement, permet de la sécuriser et de faciliter sa revue.
-
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.
Lisible par machine : JSON