• 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.

var shout = string => {
	return string.toUpperCase() + '!!';
}

shout('crumbs');

// CRUMBS!!

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.

var sayLoudly = string => {
	return string.toUpperCase();
}

var exclaim = string => {
	return string + '!!';
}

var shout = compose(sayLoudly, exclaim);

exclaim('crumbs');

// crumbs!!

shout('crumbs);

// CRUMBS!!

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.

Scroll Up