Telegram Oop Example

There have been many calls for an OOP example. Here is one:

This example is called the TelegramProblem. There is a description of an inspiration to this example at LinesComposeThemselves.

Imagine you were to write a text editor, which required automatic word-wrap (first, let us consider the case with no hyphenation).

An Oop Approach would consider each letter as a separate entity capable of sending and receiving messages and performing its own calculation. So how would such entities act together to adjust their line lengths? Let's look at the case where there are too many letters crammed into a line, so they'll want to move some words down. (I will refer to the letters in the first person).

This model for the problem is easily modeled by objects interacting by passing messages. Here is the procedural algorithm:

 for each letter in text
   if currentIndex > lineLength then
endLine(lastSpace)
moveToNextLine()
backupTo(lastWordBeginning)
   else
if it's a space then 
  set lastSpace to currentIndex
  outputFromTo(lastWordBeginning, currentIndex)
endif
if it's a letter and lastSpace is currentIndex-1 then 
           set lastWordBeginning to currentIndex
   endif
 next letter

Ok, now the two can be compared. First, the advantages of the OOP Approach:

Downsides:

I used this example because I think it really gets at the heart of what object-oriented code is for me. AlanKay meant for software systems to behave more like biological systems. He used that analogy because multi-cellular systems can function with billions of cells, all working together. If we are going to write bigger and bigger systems, this model might prove to work. OOP, for me, is not mainly about structuring code into self-contained modules to make the code easier to read (although this is very useful). OOP is about thinking of the problem in terms of small, autonomous entities all interacting in a complex system. --EricNormand?


See Also: OoBusinessExamples


EditText of this page (last edited May 23, 2007) or FindPage with title or text search