Why you should avoid creating objects

This isn’t always a problem and obviously, you can’t completely avoid creating objects somewhere.

The issue is that the code that directly creates the object becomes coupled to that object.

For example, let’s look at this simple function,.

def process(todo):                                                                                   
    todo_manager = TodoManager()                                                                     
    todo_manager.manage(todo) 

The only way to verify that process works is by using the actual TodoManager class. What if manage makes some API calls or database queries. You’d have to actually call those endpoints or have a database to run a query against.

Writing a unit test would be very hard. Unit tests are great because it lets you test that at least some aspects of your code work as you expect.

This process function is actually very simple and we can decouple the todo manager by providing it as an argument to the function.

def process(todo, todo_manager):                                                                     
    todo_manager.manage(todo) 

If you have a bunch of related functions that all need todo_manager, you could also create a class and pass the todo_manager into the constructor.

Leave a comment