Inversion of Control (IOC): Code

A follow up on my previous blog about IOC — this time we’re writing a very simple and short code (bare minimum) to illustrate the idea, and how to implement it.

We’re going to write a web framework to illustrate IOC since many of you will be familiar with a web application and/or framework. Once you get the idea, you can implement it on other domains.

Interface

We will create the bare minimum code for an interface that application developers just have to implement.

It doesn’t have to be pre-determined but for simplicity, that’s what we’ll do. Here’s the basic class that only has one method —- to handle “GET” requests.

web application interface

Framework

Next, we’ll create the web framework which will serve different web applications. We’ll keep this to a bare minimum so as not to introduce unnecessary distractions, it’ll just have:

  • A way to register a URL (so we don’t have to create a separate module for it)
  • A way to process a GET request (the one that calls our application)
  • A loop to process inputs (the one making the call)

The register method expects a web-application interface that will be associated with the provided url.

web framework

To simulate a URL submitted from a web browser (or application), we’ll just type-in the URL ourselves (that’s where the input function is for).

We also included a way to quit the framework by passing a “quit/”-ending URL to it. You can also just press Ctrl-C to halt it.

Web Application

Okay, now we’re actually going to write our application. For simplicity sake, we’ll create 2 applications to handle Reports and Services requests. They both implement the WebApplication interface since that’s the type of web-app parameter that register expects.

They do anything useful, just returning a string of what they do and the parameters passed on to it.

Main Application

Think of this as the web server (like Apache, NGINX, Gunicorn, etc.). It runs the web framework we created and receives the web traffic, which it then forwards to our web framework. The web framework in turn, forwards the action to the registered application.

Testing

Running this, we’ll see the prompt and we can type-in the URL we registered so the framework can delegate or process it. If you pass an unregistered URL, it’ll tell you so.

We also included a very simple way to split the URL and the parameters, so we can test each URL with different parameters.

Obviously, this isn’t a real web server or framework, but doing this allows you to more easily understand the frameworks out there and how they work (but way better and more robust that this crude example).

Hope you learned something new and have enjoyed too! 🙂

Leave a Comment