Introduction to Programming Style

Similar documents
The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

10 Strategies for Effective Marketing Campaigns

CIS220 In Class/Lab 1: Due Sunday night at midnight. Submit all files through Canvas (25 pts)

Perl Basics. Structure, Style, and Documentation

Coding Style Handout #15 February 1, CS106A Winter

Lecture 4 CSE July 1992

CSE 11 Style Guidelines

CS106A, Stanford Handout #30. Coding Style

Promoting Component Architectures in a Dysfunctional Organization

Variables and. What Really Happens When You Run hello_world.py

How to approach a computational problem

Using Text in Photoshop

11 Coding Standards CERTIFICATION OBJECTIVES. Use Sun Java Coding Standards

Programming in ROBOTC ROBOTC Rules

Code Convention and version control help us to success in Botball

Creating Word Outlines from Compendium on a Mac

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Formatting: Cleaning Up Data

Detailed instructions for adding (or changing) your Avatar (profile picture next to your

CS 1110, LAB 1: PYTHON EXPRESSIONS.

Excel Basics: Working with Spreadsheets

Programming Style. Quick Look. Features of an Effective Style. Naming Conventions

The compiler is spewing error messages.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

the NXT-G programming environment

Sets. Sets. Examples. 5 2 {2, 3, 5} 2, 3 2 {2, 3, 5} 1 /2 {2, 3, 5}

3. Simple Types, Variables, and Constants

HTML/CSS Lesson Plans

If Statements, For Loops, Functions

Rescuing Lost Files from CDs and DVDs

1.2 Adding Integers. Contents: Numbers on the Number Lines Adding Signed Numbers on the Number Line

6.170 Laboratory in Software Engineering Java Style Guide. Overview. Descriptive names. Consistent indentation and spacing. Page 1 of 5.

Taskbar: Working with Several Windows at Once

CREATING CONTENT WITH MICROSOFT POWERPOINT

9. MATHEMATICIANS ARE FOND OF COLLECTIONS

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Write for your audience

Learning to Program with Haiku

CDs & DVDs: Different Types of Disk Explained

Your . A setup guide. Last updated March 7, Kingsford Avenue, Glasgow G44 3EU

(Refer Slide Time 6:48)

A practicalintroduction to embedded programming. Brian Plancher 10/17/2018

CS 351 Design of Large Programs Coding Standards

Week - 01 Lecture - 04 Downloading and installing Python

Proofwriting Checklist

COPYRIGHTED MATERIAL. Dipping Your Toe into Python. Part I. Chapter 1: Programming Basics and Strings. Chapter 2: Numbers and Operators

SOEE1160: Computers and Programming in Geosciences Semester /08. Dr. Sebastian Rost

Typographic hierarchy: How to prioritize information

2 Sets. 2.1 Notation. last edited January 26, 2016

2. You are required to enter a password of up to 100 characters. The characters must be lower ASCII, printing characters.

Chapter 1 Introduction

Documentation Requirements Computer Science 2334 Spring 2016

QUICK EXCEL TUTORIAL. The Very Basics

Lecture 5 8/24/18. Writing larger programs. Comments. What are we going to cover today? Using Comments. Comments in Python. Writing larger programs

Assignment 2: Welcome to Java!

CS 177 Recitation. Week 1 Intro to Java

Public Meeting Agenda Formatting Best Practices

Game keystrokes or Calculates how fast and moves a cartoon Joystick movements how far to move a cartoon figure on screen figure on screen

Introduction to Programming

Student Outcomes. Lesson Notes. Classwork. Discussion (4 minutes)

3. Introduction to Algorithm and Flowchart

Racket Style Guide Fall 2017

EE 382 Style Guide. March 2, 2018

CS159 - Assignment 2b

Chapter 2.5 Writing maintainable programs

printf( Please enter another number: ); scanf( %d, &num2);

Cyber Smarts Using Social Media Wisely

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

Part II Composition of Functions

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CS Problem Solving and Object-Oriented Programming

Implementing an Algorithm for Boomerang Fraction Sequences in Python

An Introduction to Python (TEJ3M & TEJ4M)

S206E Lecture 19, 5/24/2016, Python an overview

1 SEO Synergy. Mark Bishop 2014

1 Getting used to Python


Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

It s possible to get your inbox to zero and keep it there, even if you get hundreds of s a day.

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0. L J Howell UX Software Ver. 1.0

Full file at

Reliable programming

Relationship of class to object

In this lesson: Line height, type size and line width are the three aspects of shaping a perfect paragraph. Lesson 2

Binary, Hexadecimal and Octal number system

User Interface Programming OOP/Java Primer. Step 3 - documentation

Teacher Activity: page 1/9 Mathematical Expressions in Microsoft Word

SML Style Guide. Last Revised: 31st August 2011

Identifiers. Identifiers are the words a programmer uses in a program Some identifiers are already defined. Some are made up by the programmer:

Stat 582 Writing Rubric (First six items from Kansas State Dept of Education rubric)

IT Web and Software Developer Software Development Standards

Yup, left blank on purpose. You can use it to draw whatever you want :-)

EXAMINING THE CODE. 1. Examining the Design and Code 2. Formal Review: 3. Coding Standards and Guidelines: 4. Generic Code Review Checklist:

Real Wireframes Get Real Results

Topic C. Communicating the Precision of Measured Numbers

The MailNinja 7-Step Success Formula For Sending Lead Generating Campaigns

Graphing on Excel. Open Excel (2013). The first screen you will see looks like this (it varies slightly, depending on the version):

Heuristic Evaluation of [ Quest ]

CSCI 2101 Java Style Guide

Mr G s Java Jive. #11: Formatting Numbers

Transcription:

Introduction to Programming Style Thaddeus Aid The IT Learning Programme The University of Oxford, UK 30 July, 2013 Abstract Programming style is the part of the program that the human reads and the compiler ignores, however that doesn t make it unimportant. Poorly written and confusing code can lead to errors and obfuscate bugs in the code. By implementing an easy to read and understand set of style standards at the beginning of your time learning how to program you can cut out many of the headaches that are normally associated with the programming learning curve. 1 Programming Style [Computer programs are] the most advanced things that humans make. - Douglas Crockford When I first started programming I was told to follow the K.I.S.S. (Keep It Simple Stupid) method and to write readable, understandable, and sharable code. I promptly disregarded that advice and produced a very clever program that didn t do anything and I couldn t figure out what I had done wrong. The first exercise I am going to recommend for style is to forget everything you know about style and write the cleverest code you can, using all the trickiest tricks you can think of and don t comment your code. Give it to a programming friend and see if they can understand it, then leave it for a week and see if you can still understand it. I hope that this will help to explain why good style is important, both so that anyone else that looks at your code can understand it, but also so that in the future you can understand it as well. Programming can be one of the most creative things that you can do, your imagination can allow to you do things that would have seemed impossible 50 years ago, but how you express that imagination is very important. Consider a novelist; a novelist creates imaginary worlds full of detail and adventure and then communicates that world of imagination to the reader. If the novelist cannot clearly communicate their ideas then that novelist isn t going to be 1

considered a good novelist. Novelists slavishly use the proper elements of style for the language they are using and the genre they are writing in as it make comprehension easier. Imagine if the next book you read has the period at the beginning of the sentence and replaced all commas with hash signs; that would make the book harder to understand. I feel it is the same for the programmer that uses non-standard notation. A programmer must be able to communicate their ideas clearly in their code. I feel that this clarity should be applied at all times; you never know when that code you have written quickly to solve a problem will be given to someone else to maintain. Think of it as a novelist s notebook being published after they have passed away. Your personal code should reflect what a good programmer you are, not that you were lazy and didn t want to take the time to complete your ideas. There is no one gold standard of programming style, just as there is no one way to write a good novel. Many methods have been used and different programming languages sometimes require different styles. So that is the first piece of advice I have: learn the conventions of your language. A quick Google search should provide multiple articles on the specifics of your language but I will cover some of the genetic considerations in this document. Second, don t get set in writing in just one style. When you work with different groups or different languages you will need to adapt your writing style to match the environment that you are working in, you don t want to try and match your working environment to your writing style. A novelist will use a slightly different writing style depending on what they are trying to convey and there is a stylistic difference between a romance and a thriller. Both can be written well but what works in one genre may not work in another; it is the same with programming. A novelist who writes jointly with a partner will make sure that the style used works for both of them so that the reader doesn t have to change mental space when shifting between authors. Coding style should be about avoiding errors and nothing else. At the end of the day how pretty your code looks doesn t matter to your compiler or interpreter; it will ignore all the work that you have put into your style, but that doesn t make style a waste of time. Style is what you put into your code to help you debug your code. That being said, I think that code that is well written and readable does have its own beauty and elegance. 2 White Space White space is your friend; it turns compact, inaccessible code into readable, maintainable code. A little extra time spent making the code look better can save you and your teammates time when looking for errors. Consider the following code: f u n c t i o n ( ) { i n t a ; i n t b ; a=5;b=6; return ( a+b ) ; 2

// p e r f e c t l y l e g a l code in some languages l i k e C While the previous code is functional and in this small sample you can understand it quickly, imagine having line after line of this compact confusing code in your program. It is much better to take that code and add some white space to make it more approachable. f u n c t i o n ( ) { i n t a ; i n t b ; a = 5 ; b = 6 ; r eturn ( a + b ) ; // much e a s i e r f o r people to read Adding indentation and empty lines allows for the program to be segmented into logical spaces which make it easy for the eye to look at different parts of the program. This can help to bring your attention to errors. My experience is that I spend more time debugging my code than writing it and all of the programmers I know do the same. So it makes sense to try and cut down as much time debugging as you can and if it costs a few extra keystrokes when you are writing your code you should think of that as an investment into saving on your total time spent debugging. 3 Curly Braces There have been many holy wars fought over where to put your curly braces in your code. I have never quite understood why it is such a major cause of discord in programming circles but it is and you should be prepared to work in several styles instead of wasting time trying to make everyone else conform to your preferred style of curly brace. The first style is: i f ( a==b ) { e l s e { d i f f e r e n t 3

This is the style I first learned when I started learning C, but when I started programming in Java I learned the second major style: i f ( a == b ) { e l s e { d i f f e r e n t It doesn t really matter which way you choose to implement your curly braces, just make sure that you are consistent in your usage through your program or it will get confusing and you may miss a bug and have to spend more time correcting the program. This is one of the areas that I feel you should be willing to change how you write your code to match your language or the group that you are programming with. I change which method I use depending on the language that I am using and the people that I am working with. I mildly prefer the second type, but not enough to make an issue over it. 4 Naming Identifiers You may have noticed that the variable names I have been using don t mean anything. You can t look at a and understand what I am using it for. This is confusing and should be avoided. It becomes obvious what the program is doing if you change your variable names such as: f u n c t i o n ( ) { i n t t e s t S c o r e 1 ; i n t t e s t S c o r e 2 ; t e s t S c o r e 1 = 5 ; t e s t S c o r e 2 = 6 ; r eturn t e s t S c o r e 1 + t e s t S c o r e 2 ; // i t i s obvious that I am summing a p a i r o f t e s t s c o r e s There are several trains of thought about naming variables. The name should be descriptive at the very least and you can add variable type and scope to the name as well to reduce confusion. Consider: i n t a ; i n t t e s t S c o r e ; i n t i n t t e s t S c o r e ; i n t g r a d e s i n t t e s t S c o r e ; 4

The longer names are more descriptive than the shorter names and will help to limit errors made while programming. Using an Integrated Development Environment (such as Eclipse) can really help in this regard; with IDEs you only need to type part of the name of your variable and then you can use the auto-complete feature to complete the name of your variable (or function). By tradition uppercase is limited in its use in programming. Words in all capitals are usually macros or constants and are replaced just before compilation by the compiler. In C it looks something like: #d e f i n e PI 3.141592 Variables use a lowercase first letter and can contain capitol letters to signify additional words as I have been using on my longer names. It is also possible to use an underscore to separate parts of the name of a variable: g r a d e s i n t A r r a y t e s t S c o r e s Class definitions in many languages have an initial capitol letter to differentiate them from the instantiated objects. Class TestScores (... ) {... // d e c l a r i n g a c l a s s TestScores t e s t S c o r e s ; // d e c l a r i n g an o b j e c t By limiting the use of capital letters you will know immediately what sort of identifier you are dealing with, from a macro to a Class to a variable or object. 5 Alignment Additional clarity can be achieved through the use of vertical alignment. It takes a bit more time but this allows you to simply look down a list to see if anything looks wrong. Compare: t e s t = 1 ; anothertest = 3 ; theclassaverage = 2 ; versus: t e s t = 1 ; anothertest = 3 ; theclassaverage = 2 ; 5

This style is very easy to break. If I copy and replace the name of theclassaverage to classmean then the alignment will be broken and would require fixing. So while this style can help to detect errors it can also add to your workload fixing the style itself. This style can also cause issues when different members of the team prefer different tab spacing. 6 Comments I want to end this introduction with a word on comments. You should use them as often as possible. If there is any chance that what you are doing isn t painfully obvious to someone else reading your code you should add a set of comments. I tend to use a self documenting style where I use identifiers that describe what the function is doing, but often this isn t enough to explain the details of the operation. Consider this program I wrote to harvest information from a data file: #!/ usr / bin / p e r l use s t r i c t ; use warnings ; open ( INFILE, <, chr2trees. txt ) or d i e cannot open < input. txt : $! ; open (OUTFILE, >, p o s i t i o n s. csv ) or d i e cannot open < output. txt : $! ; my $ l i n e ; while ( $ l i n e = <INFILE>){ my @parts = s p l i t (/ /, $ l i n e ) ; p r i n t OUTFILE $parts [ 0 ]. \n ; c l o s e ( INFILE ) ; c l o s e (OUTFILE ) ; p r i n t e n t e r a c h a r a c t e r to continue : ; my $junk = <STDIN>; For someone that understands Perl most of this program should make sense. Line by line read from the file chr2trees.txt and put the first word into positions.txt. However what is $junk and why is it there? This is a case where I failed to follow code styles and I have added a bit of confusion to the code. I had intended this just to be a pause at the end of the program so that I just have to hit enter and the program finishes. But coming back to it this can also 6

look like I wanted to do something else with the program. If I have just added a comment like: # pause program b e f o r e e x i t p r i n t e n t e r a c h a r a c t e r to continue : ; my $junk = <STDIN>; That would have removed the ambiguity from the program. 7 Conclusion I hope this introduction to programming style has helped to clarify some of the finer points of writing a good program and that you will continue to learn about programming style. I recommend you Google for a video called Programming Style and your Brain for an interesting look at why style matters. A good book to start with is a library copy of Code Complete by Steve McConnel. Good luck and I wish you a minimum of bugs. 8 Creative Commons licence This work is released under a Creative Commons licence: Attribution-NonCommercial- ShareAlike 2.0 UK: England Wales. 7