Learn How to Code with Python: Beginner to Advanced Guide
The principle “Don’t Repeat Yourself” (DRY) states that every piece of knowledge in a system should have a single, unambiguous, authoritative representation. The idea was popularized in *The Pragmatic Programmer* by Andrew Hunt and David Thomas. While often reduced to “avoid copy-paste,” DRY is fundamentally about knowledge duplication, not textual duplication. In Python, duplication typically appears as repeated conditionals, validation rules, or business logic scattered across functions or modules. When the same rule exists in multiple places, changing it requires modifying each instance consistently. This multiplies maintenance risk. DRY reduces cognitive load. Developers can reason about a system more effectively when logic resides in one place. Fewer duplicated pathways mean fewer opportunities for divergence and defects. However, DRY must be applied with judgment. Premature abstraction can introduce complexity. DRY is about reducing accidental complexity, not creating clever indirection. 2 What is the core objective of DRY? Avoid writing long functions Eliminate duplication of knowledge Reduce the number of files Prevent use of object-oriented programming Question text WET — “Write Everything Twice” — describes codebases where logic is duplicated rather than abstracted. It may arise from haste, lack of refactoring, or fear of abstraction. In Python, WET often appears as repeated blocks handling similar data transformations or validations. While initially faster to implement, duplication becomes expensive when requirements evolve. The primary risk is inconsistency. If two similar functions are updated differently, behavior diverges. Bugs become subtle and difficult to trace. WET increases surface area for failure. Each duplicated segment becomes a separate maintenance obligation. Over time, the cost compounds. 2 What is the main long-term risk of WET code? Slower execution speed Increased inconsistency during changes More Python imports Reduced readability due to indentation Question text Functions are the first line of defense against repetition in Python. If logic appears twice, it should likely become a function. For example, validation logic used in multiple API endpoints should be encapsulated in a reusable function. This ensures uniform behavior across the application. Well-designed functions isolate change. When business rules evolve, developers modify one implementation point. However, abstraction should reflect stable concepts. Extracting code that is unlikely to repeat again can create artificial coupling. 2 What is a primary mechanism in Python for implementing DRY? Using more comments Creating reusable functions Avoiding classes Using global variables Question text Object-oriented programming supports DRY through encapsulation and inheritance. Shared behavior can be defined in base classes and extended in subclasses. For instance, a base `User` class may contain authentication logic reused across different user types. This prevents duplication in subclasses. Composition also supports DRY. Instead of inheritance, shared behavior can be delegated to reusable components. Yet excessive inheritance hierarchies may introduce rigidity. DRY should simplify architecture, not overengineer it. 1 Which OOP mechanism directly supports DRY by sharing behavior? Inheritance Printing debug statements Using constants Avoiding modules Question text A common misconception is that eliminating duplication always improves quality. Sometimes small duplication is clearer than premature abstraction. Overly abstracted code can become cryptic. Indirection layers may require developers to navigate multiple files to understand simple behavior. In Python, clarity is emphasized by design philosophy (see The Zen of Python). Readability matters as much as conciseness. The balance lies in eliminating meaningful duplication while preserving directness and clarity. 1 When can duplication be preferable? When abstraction reduces clarity When using Python 3 When performance is critical When writing tests Question text Configuration values duplicated across files are a common DRY violation. Hardcoding identical constants in multiple modules creates maintenance risk. Centralizing configuration in a single module ensures consistent behavior. Environment variables or configuration objects support this pattern. In Python frameworks like Django, settings are centralized to avoid duplication of configuration knowledge. Centralization reduces errors and improves transparency of system behavior. 2 Why centralize configuration? To reduce indentation To ensure consistent values across the system To improve runtime speed To avoid importing modules Question text Test duplication is as dangerous as production code duplication. Repeated setup logic across test cases increases brittleness. Using fixtures (e.g., in pytest) reduces repeated setup code and enforces uniform test environments. Shared test utilities promote maintainability. When setup changes, only one fixture requires modification. However, tests should remain explicit. Over-abstracting test logic can obscure intent. 2 What tool in pytest helps reduce duplicated test setup? Decorators Fixtures Comments Lambda functions Question text Duplicated SQL queries scattered across a codebase are a maintenance hazard. Changes to schema or filtering rules must be applied everywhere. Using ORM abstractions centralizes database access logic. For example, SQLAlchemy allows reusable query definitions. Encapsulating queries within repository functions prevents leakage of database logic across modules. Centralization ensures consistency and reduces accidental divergence. 2 Why encapsulate database queries? To reduce database size To centralize change points To remove indexes To avoid using Python Question text DRY and SOLID are complementary but distinct principles. SOLID emphasizes object-oriented design quality, while DRY targets knowledge duplication. For instance, the Single Responsibility Principle (SRP) from SOLID discourages classes with multiple reasons to change. This indirectly supports DRY by localizing logic. Poor adherence to SOLID often leads to duplication because responsibilities are not clearly partitioned. Together, these principles improve modularity, maintainability, and scalability. 2 How does SRP indirectly support DRY? By increasing inheritance By localizing logic to one responsibility By reducing Python syntax By preventing loops Question text Experienced developers sometimes write WET code intentionally at first. This allows patterns to emerge organically. Abstracting too early risks guessing wrong abstractions. When duplication appears multiple times, abstraction becomes justified. In Python development, iterative refactoring is common. First make it work, then make it clean. DRY is a refinement principle, not a starting constraint. 1 When is it reasonable to allow temporary duplication? When abstraction patterns are not yet clear When writing documentation When using type hints When importing libraries Question text