Chapter 1. Introduction
The Grain of a Programming Language
Like wood, a programming language has a grain. In both carpentry and programming, when you work with the grain, things go smoothly. When you work against the grain, things are more difficult. When you work against the grain of a programming language, you have to write more code than necessary, performance suffers, you are more likely to introduce defects, you usually have to override convenient defaults, and you have to fight against the tooling every step of the way.
Going against the grain involves constant effort with an uncertain payoff.
For example, it has always been possible to write Java code in a functional style, but few programmers did before Java 8—for good reasons.
Here’s Kotlin code that calculates the sum of a list of numbers by folding the list with the addition operator:
valsum=numbers.fold(0,Int::plus)
Let’s compare that to what was required in Java 1.0 to do the same.
The mists of time will pass over you while transporting you to 1995…
Java 1.0 does not have first-class functions, so we have to implement functions as objects and define our own interfaces for different types of function. For example, the addition function takes two arguments, so we have to define the type of two-argument functions:
publicinterfaceFunction2{Objectapply(Objectarg1,Objectarg2);}
Then we have to write the fold higher-order function, hiding the iteration and mutation required by the Vector class. (The 1995 Java ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access