In functional programming languages, such as Scala, data types and structures, are really important. I am in two minds about the use of type-defs in helping with the readability of the code manipulating non-trivial data structures.
Here is an example of a function that takes a generic collection in Scala, traverses it once in parallel and calculates its average value. Here I have used a type-def simply in order not to have (Int,Int)
all over the place:
def average(xs:GenTraversable[Int]):Int={
type IntTuple = (Int,Int)
def addIntTuples(x:IntTuple,y:IntTuple):IntTuple=(x._1+y._1,x._2+y._2)
val (sum,len)=xs.map(x=>(x,1))
.aggregate((0,0))(addIntTuples,addIntTuples)
sum/len
}
Here is another version of the above function which tries to give the reader a better idea about what the function is doing by introducing typedefs indicating what the values in the tuple represent.
def readableAverage(xs:GenTraversable[Int]):Int={
type Sum = Int
type Len = Int
type SumLen = (Sum,Len)
def add(x:SumLen,y:SumLen):SumLen=(x._1+y._1,x._2+y._2)
val (sum,len)=xs.map(x=>(x,1))
.aggregate((0,0))(add,add)
sum/len
}
The second version is longer, but it perhaps gives the reader more of an insight into how the function operates. Question is: firstly, do you consider the second version actually more readable and insightful? If so, is the added benefit worth the increase in code length?