Reading Code

"When you do this exercise, think of yourself as an anthropologist, trucking through a new land with just barely enough of the local language to get around and survive. Except, of course, that you will actually get out alive because the internet isn’t a jungle." - Zed Shaw in "Learn Python the Hard Way".

1. Why to Read Code?

  1. Debugging a Program
  2. Modifying a Program
  3. Using a Program (Code as Documentation)
  4. Learning (e.g., Worked Example, Stack Overflow, Tutorial)

2. First Level - Tracing / Executing

3. Second Level - Reverse Engineering

How to Read Code?

  • Program's Code = A Solution to a Programming Problem
  • The goal is to extract the design and its implementation details, in some sense, preforming reverse engineering to the code
  • The process of reading code resonates the "Programming Problem Solving Model"

The Two (plus one) Questions to Answer

  1. What is the problem that the program solves?

  2. How does the problem solve the problem? What is the design of the code?

    1. "Design Tweet" (max 280 characters)
    2. Design Products
  3. Why the problem is solved that way? Why the solver choose that design?

Reading Code Steps

(adapted version from Find the Bug by Adam Barr)

  1. Apply the Reinterpret the Problem Phase

  2. Split the Code into Sections with Goals

    1. Identify sections in the code
      1. Spaces
      2. Control Flow (loops, conditions)
      3. Functions
    2. Identify goals for each section
    3. Use the Comments
      1. Look for longs or multi-line comments
      2. May indicate that
        1. This code is tricky, unclear or less obvious one
        2. Preceding a code section and explains its goal
      3. However, comments may be misleading, therefore read with care
  3. Identify the Meaning of Each Variable

    1. Variable Names
    2. Look at the Usage of Each Variable
      1. Where the variable is used?
      2. Is the variable modified? Where is the variable modified (also defined)?
      3. How the variable is used?
      4. What is the state of the variable along the code?
  4. Generate Test Cases by the Test Phase (from simplest to the most complex)

  5. Walk Through each Section

    1. Follow Execution
    2. Track Variables
      1. Think-aloud
      2. Written
    3. Note to Indentation
    4. Pay Attention in Conditions and Loops
    5. If Classes, Follow the MRO

Two Useful Strategies

  • Make changes to a program to understand it (e.g. adding diagnostic print commands)
  • Make prediction before running a code snippet

Decoding a Function - What is the problam that it solve?

  1. Name
  2. Parameters - meaning and type
  3. Return value - meaning and type



Copyright © 2020 Shlomi Hod.
All rights reserved.

results matching ""

    No results matching ""