Demystifying Event-Driven Architectures and Event Sourcing: Key Differences and Synergies
If you’re transitioning to a programming language like Python or TypeScript that supports multiple paradigms but come from an object-oriented programming (OOP) background, you might prefer sticking with OOP practices. While using classes is entirely valid, you may end up creating unnecessary boilerplate code. Here’s how you can simplify common single-method class patterns by using functions, reducing boilerplate and enhancing code clarity.
Simplifying Single-Method Classes
Single-method classes are designed to represent a specific action, often wrapping state or dependencies needed for the method’s execution. Here’s how you can simplify these classes.
Refactoring Simple Actions
The simplest case involves a class that only wraps a function without any dependencies. For instance, a class that performs addition can be simplified:
Class-Based Approach:
python
Copy code
Function-Based Approach:
python
Copy code
While you lose the interface implementation with a function, you can use type aliases to define callable types for abstraction:
python
Copy code
Simplifying Dependency Injection
Another example is a class that uses constructor injection to manage dependencies:
Class-Based Approach:
python
Copy code
Function-Based Approach:
python
Copy code
Handling Deferred Dependencies
A similar simplification applies when using deferred dependencies:
Class-Based Approach:
python
Copy code
Function-Based Approach:
python
Copy code
Summary
For classes with a single method, consider using functions to streamline your code. While this approach may seem to move away from OOP, it retains the concept of encapsulating behavior while reducing boilerplate. Type aliases can offer named abstractions for these functions, maintaining clarity and improving communication. In object-oriented languages, command classes might still be necessary, but in multi-paradigm languages, functions often provide a more concise and readable alternative.
Meet the speakers
View all insights
Exploring how modern serverless technology and historical strategies guide the evolution of cloud-native computing
Energy sustainability in the tech sector is increasingly under the microscope, and rightly so. Front-runners are benefitting by using green-credentials as a competitive advantage. For the rest, regulations are on the way. We’re here to discuss both sides. What to expect from upcoming regulations, an