• Social

Software composition: functions

Software development is “the act of breaking a complex problem down into smaller problems, and composing simple solutions to form a complete solution to the complex problem.”

The above quote is taken from Eric Elliots fantastic series on Software Composition and encapsulates the core idea that you should strive to understand in order to become a good software developer.

Writing your code with this intention in mind, streamlines the development process and results in an organised, reasonable, legible codebase. Overall, the process will be more enjoyable for yourself and any other future developer who may need to maintain and build upon it in future. You can understand this principle by looking at the simple functions below.

Imagine you wanted to create a shout function that took a string and converted  it to uppercase and added a number of exclamation marks at the end of it. If you were to write it in the lazy way you might write the following.

[pastacode lang=”javascript” manual=”var%20shout%20%3D%20string%20%3D%3E%20%7B%0A%09return%20string.toUpperCase()%20%2B%20′!!’%3B%0A%7D%0A%0Ashout(‘crumbs’)%3B%0A%0A%2F%2F%20CRUMBS!!” message=”” highlight=”” provider=”manual”/]

The above is fine in most cases but what happens if you don’t want to shout quite so forcefully… (Maybe you’ve trod on a grape rather than a plug socket?)

In that instance, we could refactor the above the above code to the following which gives us more flexibility and thus would be better software composition.

[pastacode lang=”javascript” manual=”var%20sayLoudly%20%3D%20string%20%3D%3E%20%7B%0A%09return%20string.toUpperCase()%3B%0A%7D%0A%0Avar%20exclaim%20%3D%20string%20%3D%3E%20%7B%0A%09return%20string%20%2B%20′!!’%3B%0A%7D%0A%0Avar%20shout%20%3D%20compose(sayLoudly%2C%20exclaim)%3B%0A%0Aexclaim(‘crumbs’)%3B%0A%0A%2F%2F%20crumbs!!%0A%0Ashout(‘crumbs)%3B%0A%0A%2F%2F%20CRUMBS!!” message=”” highlight=”” provider=”manual”/]

In the refactored code, you will notice the new compose function which helps merge two functions together to create a new one. This isn’t a native javascript function but you can read more about the compose function here which demonstrates it is a function which takes a list of functions and returns a single function.

The above may look confusing but hopefully serve as an indication of a broader concept of the best way to be composing your software.

Other terms for the above is called functional programming, or declarative programming which are ideas that incorporate the above but for more information on these I will be posting more about them in future.

I would also recommend Eric Elliots series on software composition or ‘Professor Frisbys Mostly Adequate Guide to Functional Programming’ which both provide an in depth look into the broader world of software composition.