Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Good Habits for Great Coding: Improving Programming Skills with Examples in Python
Good Habits for Great Coding: Improving Programming Skills with Examples in Python
Good Habits for Great Coding: Improving Programming Skills with Examples in Python
Ebook411 pages3 hours

Good Habits for Great Coding: Improving Programming Skills with Examples in Python

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Improve your coding skills and learn how to write readable code. Rather than teach basic programming, this book presumes that readers understand the fundamentals, and offers time-honed best practices for style, design, documenting, testing, refactoring, and more. 

Taking an informal, conversational tone, author Michael Stueben offers programming stories, anecdotes, observations, advice, tricks, examples, and challenges based on his 38 years experience writing code and teaching programming classes. Trying to teach style to beginners is notoriously difficult and can easily appear pedantic. Instead, this book offers solutions and many examples to back up his ideas.

Good Habits for Great Coding distills Stueben's three decades of analyzing his own mistakes, analyzing student mistakes, searching for problems that teach lessons, and searching for simple examples to illustrate complex ideas.  Having found that most learn by trying out challenging problems, and reflecting on them, each chapter includes quizzes and problems. The final chapter introduces dynamic programming to reduce complex problems to subcases, and illustrates many concepts discussed in the book. 

Code samples are provided in Python and designed to be understandable by readers familiar with any modern programming language. At the end of this book, you will have acquired a lifetime of good coding advice, the lessons the author wishes he had learned when he was a novice.

What You'll Learn

  • Create readable code through examples of good and bad style
  • Write difficult algorithms by comparing your code to the author's code
  • Derive and code difficult algorithms using dynamic programming
  • Understand the psychology of the coding process

Who This Book Is For

Students or novice programmers who have taken a beginning programming course and understand coding basics.Teachers will appreciate the author's road-tested ideas that they may apply to their own teaching.

LanguageEnglish
PublisherApress
Release dateMar 12, 2018
ISBN9781484234594
Good Habits for Great Coding: Improving Programming Skills with Examples in Python

Related to Good Habits for Great Coding

Related ebooks

Programming For You

View More

Related articles

Reviews for Good Habits for Great Coding

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Good Habits for Great Coding - Michael Stueben

    Part INot Learned in School

    © Michael Stueben 2018

    Michael StuebenGood Habits for Great Codinghttps://doi.org/10.1007/978-1-4842-3459-4_1

    1. A Coding Fantasy

    Michael Stueben¹ 

    (1)

    Falls Church, Virginia, USA

    Once upon a time, a talented young programmer was in a situation where he did not have the resources to seek more education. He had a dead-end job that would never allow any promotion. Further, his family could not help him, and he lived in a decaying and unsafe part of town. Our programmer had four friends who had developed similar programming skills and who also felt limited by their opportunities. They were all slightly depressed and worried about their futures.

    Suddenly, the five programmers discovered an amazing opportunity. If they could team up and write a particular computer application, then the attention they would receive would immediately open doors for better jobs.

    Of course, anyone in this situation would want to attempt to write the application. But it was not so simple. Previously, the most challenging program each of them had written took three weeks of time at 1-2 hours a day. Most of the time was spent in debugging. Some of those bugs were so difficult to track down that they had twice given up on their programs, only to come back to them out of curiosity. In fact, those three weeks of time were actually spread over six weeks. They all had the same experience.

    Upon reviewing the work for this new project, it appeared that the job naturally could be divided into five equal parts. The problem was that each part was five times longer than anything any one of them had worked on before. They had 40 weeks to finish the project. In theory, if all could stay focused, that was more than enough time to finish. But in practice, the complexity was beyond what anyone thought he or she could do. The tantalizing prize was also an invitation to failure. Briefly each thought that the quiet go-nowhere life they were currently living might be preferable to 40 weeks of misery that almost certainly would lead to failure. Who needed that? Maybe something else would come along. Eventually in conversation, the five friends realized that this defeatist thinking is a common reason why people do not climb out of their poor situations in life. Yet, as each one currently understood the project, it was too difficult for them to complete. If they could increase the likelihood of success, then it might be worth a try. So, what to do?

    First, the five programmers had to accept the fact that they would have to turn themselves into programming robots. Many of the pleasures that were part of their everyday lives would have to be replaced with hours of coding. This would require a change of both habits and perspective on life. Could they do this? The prize dangling in front of them just might be enough.

    The real problem was debugging. Although all parts of the code seemed reasonable enough, there were so many parts that debugging problems would arise en masse. They didn’t see how any one of them could be successful. Then someone suggested a solution: For almost every key function written, a companion function could be written to test that function. After each session of coding, the testing functions would be run. Another program would import most of the important functions and run several sets of data through each function. The data would test, for example, almost every if statement in a function.

    This meant that if a redesign occurred, the functions adversely affected would be flagged immediately. Writing two functions for every one function needed in the application would be extra work, but the testing functions would be simple to write, and mostly similar to each other. This scheme, called unit testing , seemed to offer hope.

    Another member suggested that the group get together every week to read each other’s code, to discuss problems, and to suggest solutions coming from fresh eyes. In these code reviews they would share both problems and hard-learned solutions. Another suggestion was to document almost every key function with an English description (docstrings), so that any of the other members could more easily follow the code. Another suggestion was that they should occasionally try to work in pairs ( pair programming ): one typing and the other thinking about what is being typed.

    The group felt that their only chance at success was to adopt these conventions. One of the members later described working with these conventions as writing code in a straightjacket.

    Soon after the coding began, the members noticed that progress was slow but steady. The inevitable redesigns, usually based on overlooked special cases and poorly chosen data structures, almost always caused a domino effect of other changes. These changes were all quickly noticed and located by unit testing .

    The members also began discussing small differences in coding styles—e.g., should one write

    if (x and y) == True: print(x)

    or

    if x and y: print(x)?

    Because of differing opinions, they decided to vote on a group style and stick to the group’s decision. Eventually, their conventions, which were often arbitrary, began to look correct and any different convention looked wrong. Because the same style was used by everyone, they all became efficient at reading code written in their shop style.

    To make a long story short, their combination of sacrifices , commitment , and good decisions about writing code enabled them to complete the project and win a better life. Eventually, they were hired by employers seeking expert programmers.

    Their new employers appreciated the members of this group for several reasons. First, the programmers had put so much of their lives into writing code that their skills were excellent. They wrote code quickly and with few bugs. They understood their language, and used its constructs efficiently. Second, and just as important, their code was easily readable by anyone else. Third, they were flexible. They adopted the current house style in coding, even when they personally preferred to write code differently.

    In some of the companies where these coders worked, there were layoffs. Our five original coders were never let go. As one employer said, They always give more than is expected. Who would let an employee like that go?

    Years passed and they all retired from the business of writing code. One of the younger programmers was a little bored. He missed the coding experience, but was too old to return to full-time work. His spouse noticed that the neighboring high school needed a part-time teacher for a single one-semester class of advanced programming. He took the job.

    The previous teacher expected the students to understand different algorithms and build their programming skills by correctly implementing the algorithms in computer code. The old programmer-turned-replacement teacher agreed, and realized that many of the conventions that were necessary for success in business would not apply to students writing small programs. Still, he thought, writing code that was readable was something that should be taught along with algorithms , language instructions , and data structures . Halfway through the course, he had lectured on and had posted the following guidelines.

    Advice for Developing Programmers (pain management)

    1.

    Limit functions to a single task, or to simple and highly related tasks (cohesion vs. coupling ).

    2.

    Label and align your output.

    3.

    Document your programs at the top: name, date, class period (maybe course and instructor), title, and program description. Watch your spelling, grammar, and punctuation.

    4.

    Code with line numbers and never indent less than three spaces.

    5.

    Use vertical alignment in your code if it will emphasize significant relationships.

    6.

    Do not use Python language names (reserved words and built-in names) for identifiers or file names—e.g., random, max, print, factorial, etc.

    7.

    Refactor (= redesign) your programs after they work to be more readable. This is when and how program design is learned.

    8.

    Use step-wise refinement : function calls that outline your program’s work. Limit the main() function to calls to other functions. In short programs you may add initialization and maybe some output lines to the main function.

    9.

    Write self-documenting code (descriptive identifiers, usually verb-object function names) and thereby minimize comments. Avoid over-abbreviating identifiers to save typing a few letters.

    10.

    Always print the runtime, and perhaps some other statistics, for every program.

    11.

    Avoid magic numbers, unless they make the code significantly simpler to work with.

    12.

    Avoid global variables, but global constants are acceptable.

    13.

    Do not write clever code (code that doesn’t immediately look like what it does), when simpler code will do.

    14.

    Choose readability over both optimization for speed and optimization for memory use.

    15.

    Anticipate bugs by using defensive measures (asserts , error traps , try/except blocks , and intermediate prints ). Just don’t overdo it.

    16.

    Test every key function upon completion . Consider untested code to be broken code.

    17.

    For a complicated algorithm, consider writing some simple tests before you write the code, not after you write the code.

    * * *

    18.

    Do not start on the next assignment or function until you have finished the previous one.

    19.

    When coding, you need total focus. Avoid the chatty classmate. (The purpose of sometimes isolating yourself is to force you to solve problems on your own. Do not become dependent upon your classmates.)

    20.

    Save every assignment on at least two different physical devices.

    * * *

    21.

    Write some code every week. Do not regress. You may have to push yourself.

    22.

    Spend time with smart people and try to get them to talk shop.

    23.

    Read the code of other programmers.

    24.

    Learn programming tools on your own: a sophisticated editor , language idioms and tricks , built-in functions , and data structures .

    25.

    Come to your problems with a history of attempting challenging problems.

    26.

    Try hard to avoid cheating.

    27.

    Do not let grades and outside activities sabotage your education. You, not the school, are responsible for your learning.

    Unfortunately, the list was not only ignored, it was disputed by the students. He overheard many disparaging comments:

    I don’t see why my code must be readable to others when is it readable to me and nobody else will ever read it. Getting the program to work was hard enough. I need time for other classes.

    I can’t believe he asked us not to write clever code. Is he trying to stifle us?

    I think my code is descriptive enough. He is being too picky asking for better descriptors.

    The other C.S. teacher is not so picky. I wish I were in her class.

    My code is exactly like Paul’s because we worked together. He is always saying we need to help each other. He better not say I cheated.

    He tells us to help each other, but not to get help. That makes no sense.

    There are no errors in my program, so why did he want me to have error traps in my code?

    My code works for my input. It doesn’t work for his input, because he tests with weird data, like the empty set.

    I still don’t understand how focusing on grades could adversely affect my education.

    "Why should we learn the tools on our own time? Shouldn’t he teach them to

    Enjoying the preview?
    Page 1 of 1