Friday, April 19, 2013

Small Code

Here's a snippet from a post I took offline.

Small Code
"Functions should do one thing. They should do it well. They should do it only."

I feel like this is an overused term. It doesn't help that I also feel cursed by what my professor has taught me, "Try to keep your methods down to three to five lines." No matter how many times a fellow developer will compliment how nice my code is, they will argue to the death that you can't possibly have those kind of restrictions.
If the rule is a bit strict then yes, there are times where it will be bent; otherwise, there's no reason I have to constantly look at 150 line methods. You won't know what I mean until you honestly try it for yourself.

The easiest way to pick up on this ability is to practice designing programs. You would be surprised how even the smallest programs can test you. I've done designs for elevators and soda machines. Here's an overall image for my elevator design when I was in college. This was all accomplished using the technique I'm about to share with you.

Elevator Design


I suppose it's called "Top-down design." Here's what you do.  Capture the overall algorithm of the application in five to ten lines of pseudocode. You must restrict yourself to one level of indentation. Now that you have your first level of abstraction, you're going to delve deeper, explaining how each sentence is accomplished in three to five lines of pseudocode. You will repeat this process until you encounter existing data structures or API provided by your language of choice.

Here's an example design process of the checkers board game:

First Step, outline main process
start game
prompt for game type
play game
tally score
ask to play again

Second Step, break down your first level of abstraction into greater detail. As you can see you're simply breaking the next level down into greater detail.

start game
    load up settings 
        if game was saved
     load saved game

prompt for game type
    promt user
 if single player
     get single board
 else
     get two player board

play game
    while the game is still going
 if user turn
     prompt for move
 else
     make move with AI

tally score
    if main player won
 add score to main player board
    else
 add to opponent score

ask to play again
    if user still wants to play
 start game over
    else
 go back to main screen


Hopefully this will get you familiar with the "Top Down" design approach; otherwise I recommend you dig up Steve Halladay & Michael Wibel's book "Object-Oriented Software Engineering" for more details. I'm pretty sure there are still copies out there for sell.

No comments:

Post a Comment