Thursday, February 11, 2016

Refactoring - Eagerly Initialized Attribute

A Fibonacci sequence has each element equal to the sum of the previous two elements.

The first two elements are 1 and 1 so the sequence shows like this:

1, 1, 2, 3, 5, 8, etc

Asked to implement a function to return one element of the series, a smarty pants developer thought to save some time at the initialization of the program and to use a lazy initialized variable:

var fibonacci = [Int]()
fibonacci.append(1)
fibonacci.append(1)

func getFibonacci(index:Int) -> Int {
    if index >= fibonacci.count {
        for i in fibonacci.count ... index {
            fibonacci.append(fibonacci[i-1] + fibonacci[i-2])
        }
    }
    return fibonacci[index]
}

This is interesting but not very straight forward. One needs to think a bit.

The developer realizes that in the current context, only the first 50 elements in the sequence are used.

So, thinking of the future developers who might try to understand what on earth his code is doing, he is simplifying the funtionality by initializing the elements just from the start:

var fibonacci = [Int]()
fibonacci.append(1)
fibonacci.append(1)

for i in 2...50 {
    fibonacci.append(fibonacci[i-1] + fibonacci[i-2])
}

We can even of further and simplify the code a but further, taking advantage of the Swift shortcut of initializing an array:

var fibonacci = [1,1]

for i in 2...50 {
    fibonacci.append(fibonacci[i-1] + fibonacci[i-2])
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.