Skip to main content

Command Palette

Search for a command to run...

Foundational Philosophies

Updated
9 min read
A

I am a Student, who finds beauty in simple things. I like to teach sometimes.

This article examines several guiding tenets and established practices that contribute to robust and maintainable software. We will look at a set of aphorisms for Python, a general design principle, insights from a classic game's engineering, and a widely adopted style guide for Python code.

The Guiding Spirit of Python

Contained within Python itself, accessible by executing import this, is a collection of 19 aphorisms by Tim Peters known as "The Zen of Python." These principles offer a perspective on writing Pythonic code. Key ideas presented include:

  • Beauty and Explicitness: "Beautiful is better than ugly. Explicit is better than implicit." This suggests that code should be clear and readily understandable, preferring straightforwardness over clever but obscure constructions.

  • Simplicity and Complexity Management: "Simple is better than complex. Complex is better than complicated." This advises striving for simplicity first. When complexity is unavoidable, it should be managed in a structured way rather than becoming convoluted.

  • Structure and Readability: "Flat is better than nested. Sparse is better than dense. Readability counts." These lines argue for code structures that are easy to follow, avoiding deep nesting and overly compact code, because the ability for humans to read and understand code is critical.

  • Handling Special Cases and Errors: "Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced."1 This presents a balance: while consistency is good, pragmatic solutions are sometimes necessary. Crucially, errors should be evident and handled, not ignored, unless there's a deliberate reason to suppress them.

  • Ambiguity and Obviousness: "In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it."2 Code should be unambiguous. Python's design often strives to provide a single, clear path for common tasks. The aphorism humorously adds, "Although that way may not be obvious at first unless you're Dutch," acknowledging that what is "obvious" can sometimes be learned.

  • Timeliness and Implementation Clarity: "Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea."3 These statements encourage action but caution against haste. A significant indicator of a potentially problematic implementation is its difficulty to articulate; conversely, ease of explanation can signal a sound approach.

  • Namespaces: "Namespaces are one honking great idea -- let's do more of those!" This strongly advocates for the use of namespaces to organize code and prevent naming conflicts, a fundamental feature of Python's architecture.

These aphorisms collectively provide a philosophical underpinning for Python development, guiding programmers towards clarity, simplicity, and practicality.

The KISS Principle in System Design

The KISS principle, an acronym for "Keep It Simple, Stupid," is a design maxim that originated in the U.S. Navy in the 1960s, often attributed to Kelly Johnson, a lead engineer at Lockheed Skunk Works. The core idea is that systems function best if they are kept simple rather than made complicated. Therefore, simplicity should be a primary objective in design, and unnecessary complexity should be avoided.

In software development, applying the KISS principle means:

  • Avoiding Over-Engineering: Solutions should not be more complicated than the problem requires. Features that are not essential, or overly elaborate ways of implementing functionality, can introduce points of failure and increase maintenance burdens.

  • Enhancing Maintainability: Simpler code is generally easier to understand, debug, and modify. This reduces the long-term cost of software ownership.

  • Improving User Comprehension: For user interfaces and APIs, simplicity often translates to a system that is easier for users to learn and operate, leading to fewer errors and greater satisfaction.

  • Reducing Development Time: Straightforward designs can often be implemented more quickly than complex ones.

While the "stupid" in KISS might seem pejorative, it is more a reminder to avoid the pitfalls of excessive intellectual sophistication for its own sake, and to consider that the design should be robust enough for even a less experienced person to understand or repair (as in Johnson's original context of aircraft design for field mechanics). Variants like "Keep It Simple and Straightforward" convey the same essential message. The principle encourages breaking down complex problems into smaller, manageable, and simpler sub-problems.

Technical Ingenuity from Doom

The original Doom, released in 1993 by id Software, was a landmark in video game technology, particularly for its 3D graphics engine developed primarily by John Carmack. While game development might seem distant from other software engineering fields, Doom's creation offers several points of technical inspiration, especially concerning performance in resource-constrained environments and innovative problem-solving.

  • Binary Space Partitioning (BSP): To render its pseudo-3D environments efficiently on the limited processing power of contemporary PCs (like the Intel 386 processor), Doom's engine utilized a data structure called a Binary Space Partitioning tree. The level geometry was pre-processed into a BSP tree. This allowed the renderer to quickly determine the order in which to draw polygons (or "segs" of walls) from back to front, or to identify potentially visible surfaces, minimizing overdraw and culling unseen areas effectively. This was a sophisticated technique for its time in a consumer application, demonstrating how algorithmic innovation could overcome hardware limitations.

  • Efficient Data Structures and Algorithms: The engine was built with a keen understanding of the hardware. Wall textures were stored as vertical columns, which suited the rendering process that drew walls column by column. Fixed-point arithmetic was used for many calculations, as floating-point units were not standard or were slow on target hardware. These choices reflect a deep attention to performance at a low level.

  • Modularity through WAD files: Doom's game data (levels, graphics, sounds, music) were stored in "WAD" (Where's All the Data?) files. This separation of the game engine from its content facilitated modifications ("mods") by the user community, an early example of how designing for extensibility can significantly prolong a software product's life and foster a community. While the internal structure of WADs was specific, the concept of packaging data separately from executable code is a widespread good practice.

  • Pragmatic Problem Solving: Carmack and the id Software team were known for their focused, pragmatic approach to solving technical hurdles. When a rendering approach proved too slow, research into academic computer graphics papers led to the adoption and practical implementation of BSP. This demonstrates a willingness to seek out and apply advanced concepts to solve immediate, critical problems.

The engineering behind Doom serves as an example of how clever algorithms, careful data representation, and a relentless focus on efficiency can achieve remarkable results, even under significant constraints.

PEP 8: Styling Python Code

PEP 8, officially titled "Style Guide for Python Code," is one of the most significant Python Enhancement Proposals. Authored by Guido van Rossum, Barry Warsaw, and Nick Coghlan in 2001, it provides conventions for writing Python code to improve its readability and consistency among different developers and projects. Adherence to PEP 8 is highly recommended for all Python developers. Its main areas include:

  • Code Layout:

    • Indentation: Use 4 spaces per indentation level. Tabs should not be used, primarily because their appearance can vary across editors and platforms, leading to confusion. For continuation lines, indentations can align wrapped elements vertically or use a hanging indent (typically an extra 4 spaces).

    • Line Length: Limit all lines to a maximum of 79 characters for code and 72 characters for docstrings and comments. This aids readability, especially when viewing multiple files side-by-side or using tools that have fixed-width displays. Long lines can be broken using Python's implied line continuation inside parentheses, brackets, and braces, or by using a backslash (though the former is preferred).

    • Blank Lines: Use blank lines sparingly to separate logical sections. Top-level function and class definitions should be separated by two blank lines. Method definitions inside a class are separated by a single blank line. Blank lines can also be used within functions to indicate logical breaks.

  • Whitespace in Expressions and Statements:

    • Surround binary operators (assignment (=, +=), comparisons (==, <, is not), Booleans (and, or)) with a single space on either side.

    • Avoid extraneous whitespace immediately inside parentheses, brackets, or braces, and before commas, semicolons, or colons. However, a space should follow a comma in argument lists or sequences.

  • Naming Conventions:

    • General Principles: Names should be descriptive. Avoid single-character names except for simple counters or iterators in short loops, or in contexts where their meaning is standard (e.g., e for exceptions, k and v for dictionary items).

    • snake_case: Function names, method names, variable names, and module names should be lowercase, with words separated by underscores as necessary to improve readability (e.g., my_variable, calculate_total_sum).

    • PascalCase (or CapWords): Class names should normally use the CapWords convention (e.g., MyClass, HttpRequest).

    • Constants: Constants should be written in all capital letters with underscores separating words (e.g., MAX_OVERFLOW, TOTAL_CONNECTIONS).

    • Protected and Private: For internal use, a single leading underscore (_protected_member) conventionally indicates that a name is intended for internal use (a weak "internal use" indicator). Two leading underscores (__private_name) trigger Python's name mangling to make it harder (but not impossible) to access from outside the class, signaling a strong "internal use only" convention.

  • Comments:

    • Block Comments: Generally apply to some (or all) code that follows them and are indented to the same level as that code. Each line of a block comment4 should begin with a # and a single space.

    • Inline Comments: Use sparingly. An inline comment is a comment on the same line as a statement. They should be separated by at least two spaces from the statement. They should start with a # and a single space.5

    • Documentation Strings (Docstrings):6 PEP 257 describes good docstring conventions. Docstrings are enclosed in triple quotes ("""Docstring goes here.""") and should be the first statement in a module, function, class, or method definition. They explain what the code does. For multi-line docstrings, the summary line should be on its own, followed by a blank line, then the more detailed explanation.

  • Programming Recommendations:

    • Comparisons to singletons like None should always be done with is or is not, never with the equality operators (== or !=).

    • Use isinstance() for type checking of objects if necessary, rather than directly comparing types with type().

    • When catching exceptions, mention specific exceptions rather than using a bare except: clause.

PEP 8 is not just about aesthetics; it is about producing code that is clear, maintainable, and less prone to errors because its structure and conventions make the underlying logic easier to follow. While there are occasions when PEP 8 guidelines might be ignored (e.g., to maintain consistency with existing code that doesn't follow it, or when an identifier has a strong conventional meaning in a mathematical context), these are exceptions. Tools like linters (e.g., Flake8, Pylint) and auto-formatters (e.g., Black, Autopep8) can help automate adherence to PEP 8.

More from this blog

Aman Pathak

58 posts

Things I would speak if the person in front of me is me