Friday, February 18, 2022

Ports and Adapters, Part 2

Ports and Adapters part 2

Approach, not reproach

Many programming tutorials are difficult to follow.  I do not necessarily expect this one to be any different, but I'll try.  I'm going to start with relatively broad concepts, any of which may lead to a new post drilling down into that topic in further detail one day.

Take a client-centric view of the solution

We have nobody to blame but ourselves.  We've all done it.  You hit Google, or StackOverflow, and you grab a chunk of code that interfaces with some library we want to use.  Then we change the shape of our code, introducing abstractions that don't really gel that well with the ones around it, in order to make that adopted code work.
Don't do that.

Design the API you want to use

Think about things from your own application's point of view.  Do you need a database client?  Or do you need a way to get data based on a few 'key' criteria?  What level of abstraction do you really want to be working with as you write your code?

Test first

I prefer a TDD (Test Driven Development) approach to writing code.  When one first encounters the notion, it seems backwards.  It was certainly very different from practices I'd spent years on.  But in the end, following this discipline beats the hell out of attempting to add unit tests to the tangled messes many of us naturally weave otherwise.  I've been called good (or sometimes better than that) at what I do, but when I look around at my code, what I see is still more of a mess than I'd like.
TDD really helps with that.  I think that topic deserves a post of its own.
Use your concept to build some code.  Mock the responses you intend your own API to provide.  Call your own API.  It's all a kind of unit/integration testing hybrid, it's all provably correct.  It also works the way you think as a developer, long before you've actually decided which database or messaging system you'll be using.

Adapt your concept to a real-world library

When you've achieved that level, it's finally time to replace the mocked service provider with a real one... And testing that can appear very difficult.  I'll discuss techniques for that in future posts.

But first, a word about using code that demonstrates use of a library:

There's nothing wrong with learning how to use a library that way.  It should teach you the general usage patterns, pre-requisites, etc.  But that doesn't mean you should copy that demo function into your production application and start to use it!

At a bare minimum paste it into a new source file.  Better yet, use a test-driven approach to create a new file that implements the subset of capabilities you need.
Enjoy!

That's really all you have to do to get dependencies out of your own code.  It sounds easy, and sometimes it is.  Actually, a lot of the time it is, once you figure out how to think about it.

No comments:

Post a Comment