Chapter 3: Reusability

Have you ever wondered how the System.out.print function works (print function in Kotlin/JVM)? It’s one of the most basic functions used again and again and yet, would you be able to implement it yourself if it would vanish one day? Truth is that this is not an easy task. Especially if the rest of java.io would vanish as well. You would need to implement the communication with the operating system in C using JNI, separately for each operating system you support1. Believe me, implementing it once is terrifying. Implementing it again and again in every project would be a horror.

The same applies to many other functions as well. Making Android views is so easy because Android has a complex API that supports it. A backend developer doesn’t need to know too much about the HTTP(S) protocol even though they work with it every day. You don’t need to know any sorting algorithms to call Iterable.sorted. Thankfully, we don’t need to have and use all this knowledge every day. Someone implemented it once, and now we can use it whenever we need. This demonstrates a key feature of Programming languages: reusability.

Sounds enthusiastic, but code reusability is as dangerous as it is powerful. A small change in the print function could break countless programs. If we extract a common part from A and B, we have an easier job in the future if we need to change them both, but it’s harder and more error-prone when we need to change only one.

This chapter is dedicated to reusability. It touches on many subjects that developers do intuitively. We do so because we learned them through practice. Mainly through observations of how something we did in the past has an impact on us now. We extracted something, and now it causes problems. We haven’t extracted something, and now we have a problem when we need to make some changes. Sometimes we deal with code written by different developers years ago, and we see how their decisions impact us now. Maybe we just looked at another language or project and we thought “Wow, this is short and readable because they did X”. This is the way we typically learn, and this is one of the best ways to learn.

It has one problem though: it requires years of practice. To speed it up and to help you systematize this knowledge, this chapter will give you some generic rules to help you make your code better in the long term. It is a bit more theoretical than the rest of the book. If you’re looking for concrete rules (as presented in the previous chapters), feel free to skip it.