Demystifying Event-Driven Architectures and Event Sourcing: Key Differences and Synergies
Armakuni
Sep 17, 2024 · 2 min read · Engineering practice
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.
In short
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:
The code for this example is missing from the original post.
Function-Based Approach:
The code for this example is missing from the original post.
While you lose the interface implementation with a function, you can use type aliases to define callable types for abstraction:
The code for this example is missing from the original post.
Simplifying Dependency Injection
Another example is a class that uses constructor injection to manage dependencies:
Class-Based Approach:
The code for this example is missing from the original post.
Function-Based Approach:
The code for this example is missing from the original post.
Handling Deferred Dependencies
A similar simplification applies when using deferred dependencies:
Class-Based Approach:
The code for this example is missing from the original post.
Function-Based Approach:
The code for this example is missing from the original post.
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.



Discussion about this post