SOLID, composition, common patterns and clean code
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeEncapsulation is the practice of bundling data and methods that operate on that data within a class, and restricting access to some of the object's components. This protects the internal state and prevents unintended interference, making code safer and easier to maintain.
Inheritance allows a class to inherit properties and methods from another class. For example, a Car class can inherit from a Vehicle class, gaining its speed and acceleration methods, while adding its own features like honk.
Polymorphism lets you use a single interface to represent different types. For instance, you can call draw() on a list of shapes, and each shape (circle, rectangle) will implement its own version of draw().
Abstraction hides complex implementation details and exposes only what’s necessary. It helps by simplifying interfaces, so users don’t need to understand the inner workings to use a class or method.
Composition is preferred because it allows you to build classes by combining behaviors, rather than relying on rigid hierarchies. This makes code more flexible and easier to change, as you can swap components without affecting unrelated parts.
A class that only handles printing invoices, like InvoicePrinter, follows the Single Responsibility Principle. It doesn’t manage invoice data or calculations, just the printing logic, making it easier to maintain and test.
The Open/Closed Principle means classes are open for extension but closed for modification. You can add new functionality by extending classes, rather than changing existing code, which reduces the risk of breaking features.
Singletons can introduce global state, making code harder to test and maintain. They can also create hidden dependencies and issues in multi-threaded environments if not implemented carefully.
The Factory pattern centralizes object creation, allowing you to instantiate different types based on input or configuration. This decouples client code from concrete classes and makes it easier to add new types.
The Adapter pattern allows incompatible interfaces to work together by wrapping one interface with another. This is useful when integrating third-party libraries or legacy code with your system.
The Decorator pattern lets you add behavior to objects dynamically. For example, you can wrap a data repository with a logging decorator to record operations, without modifying the original repository class.
Dependency injection allows you to pass mock or stub dependencies into a class, making it easier to test in isolation. You don’t have to rely on real implementations, which can be slow or difficult to set up.