Skip to main content
Blog Sep 17, 2024 · Armakuni ·2 min read

Demystifying Event-Driven Architectures and Event Sourcing: Key Differences and Synergies | Armakuni

Simplify your code by replacing single-method classes with functions in multi-paradigm languages like Python and TypeScript.

Demystifying Event-Driven Architectures and Event Sourcing: Key Differences and Synergies | Armakuni

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.

Related reading.

Contact Armakuni.

Most engagements start with an AWS-funded discovery. First conversation is with an engineer, not a sales exec.