Quick Index
Overview


This page contains a listing of lessons learned regarding algorithms and the object oriented approach.

Return Type


Critically Important


The purpose of most algorithms (methods) is to compute a result and return it.

If we return the wrong object (and especially an unexpected type) the object user (message sender) won't be able to use the result (and all of the algorithm work will be for nothing).

If the message sender expects that we return "Foo" and we return an integer, they most certainly will throw a run time exception (e.g. a major bug occurs).

Start With Return Type


A good approach is to start an algorithm (or code) by jotting getting the correct return type.

If the method summary says to return a "CrazyCollection" then we could look up how to construct it. Let us assume "fromSize(sz)".

Then we might start our logic like this:

let result = CrazyCollection.fromSize(??)

//TODO

return result


A good start -- we know we're returning the correct type of object.

Keep it Simple (KIS)


Sometimes an algorithm (method) gets long or condition nesting is gets deep. Or maybe it simply "feels overwhelmingly complex".

This is usually an indicator (flag) that we should step back and take a fresh look at the problem

Reuse Code -- Share the Work


We always want to take a look to see if we can call other methods and let them do work for us.

Reinventing the wheel is not only redundant but means we have to start retesting the reinvention.

Reuse -- delegate -- call other methods.

Knowing Context is Key


For the previous lesson learned (reuse code) we need to know what other methods and objects are within our context (scope).

In some cases, the context is simple -- e.g. the challenge for this chapter has a context that is MyArray. So we want to look often at its method summary (protocol).

If we try to use methods not in our context, that would be like visiting McDonalds and asking for a Pizza Hut pizza.

Keyword 'this'


Understanding the keyword 'this' is essential.

Loop Over a Collection in Reverse


It is helpful to be able to loop in reverse (especially indexes).

With practice it will become simple. In essense it is (human language):

let lastIndex = collection size minus one
Loop over indexes from lastIndexes down to zero {
	loop block here
}

Print Statements -- Delete or Comment Out


We do not want to leave "print" statements in algorithms or code (except for rare case where the method description calls for a print).

Reason: we assume that collections may be very large (million or more elements) and a print statement would "hang" (effectively block) the program.

Print statements can be helpful for debugging and work in progress, but we should comment those out before "finishing" the logic.