23-Oct-15 Style. Why style matters Good style isn’t just to make your code “look pretty” The most critical factor in style is readability If a program.

Slides:



Advertisements
Similar presentations
1-May-15 Style. 2 About the book This book is a team effort by many good programmers, not just one person’s opinions The rules have been widely distributed.
Advertisements

2-May-15 GUI Design. 2 HMI design There are entire college courses taught on HMI (Human-Machine Interface) design This is just a very brief presentation.
Internal Documentation Conventions. Kinds of comments javadoc (“doc”) comments describe the user interface: –What the classes, interfaces, fields and.
Introduction to C Programming
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
15-Jun-15 Style Consolidated Lectures. 2 About the book This book is a team effort by many good programmers, not just one person’s opinions The rules.
15-Jun-15 Beginning Style. 2 Be consistent! Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t.
16-Jun-15 Recognizers. 2 Parsers and recognizers Given a grammar (say, in BNF) and a string, A recognizer will tell whether the string belongs to the.
Style Rules II: Names and Naming. Overview Today we will discuss: –Reasons for naming conventions –Rules for naming variables, classes, and methods.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
18-Jun-15 Arrays. 2 A problem with simple variables One variable holds one value The value may change over time, but at any given time, a variable holds.
22-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Style Rules I. Style is important Everyone agrees that good style is important –Everyone agrees on most of the essentials –But some people have “religious.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements If a method is in the same class, you execute those declarations.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements You execute those declarations and statements by calling the.
26-Jun-15 Beginning Style. 2 Be consistent! Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t.
28-Jun-15 Recognizers. 2 Parsers and recognizers Given a grammar (say, in BNF) and a string, A recognizer will tell whether the string belongs to the.
29-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Introduction to C Programming
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.3 The Class String.
Algorithm Programming Coding Advices Bar-Ilan University תשס " ו by Moshe Fresko.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Lecture 10 Instructor: Craig Duckett. Assignment 2 Revision TONIGHT DUE TONIGHT Wednesday, August 5 th Assignment 3 NEXT DUE NEXT Monday, August 10 th.
Java Language and SW Dev’t
A First Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Credits: a significant part of.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
© 2006 Pearson Education 1 Obj: cont 1.3 and 1.4, to become familiar with identifiers and to understand how programming languages work HW: p.51 #1.8 –
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
The Java Programming Language
CSC204 – Programming I Lecture 4 August 28, 2002.
Introduction Algorithms and Conventions The design and analysis of algorithms is the core subject matter of Computer Science. Given a problem, we want.
Just as there are many human languages, there are many computer programming languages that can be used to develop software. Some are named after people,
CIT 590 Intro to Programming First lecture on Java.
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
23-Oct-15 Abstract Data Types. 2 Data types A data type is characterized by: a set of values a data representation, which is common to all these values,
Introduction to programming in the Java programming language.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Code Conventions Tonga Institute of Higher Education.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
Working With Objects Tonga Institute of Higher Education.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Programming for Interactivity Professor Bill Tomlinson Tuesday & Wednesday 6:00-7:50pm Fall 2005.
Today… Style, Cont. – Naming Things! Methods and Functions Aside - Python Help System Punctuation Winter 2016CISC101 - Prof. McLeod1.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Software Development Languages and Environments. Computer Languages Just as there are many human languages, there are many computer programming languages.
CSC 108H: Introduction to Computer Programming
Working with Java.
Some Eclipse shortcuts
Recursion 12-Nov-18.
Chapter 4 void Functions
Recursion 2-Dec-18.
Recursion 2-Dec-18.
Style 5-Dec-18.
Style 5-Dec-18.
Recursion 29-Dec-18.
Style 22-Feb-19.
Beginning Style 27-Feb-19.
Style 4-Apr-19.
Style 9-Apr-19.
Introduction to Primitives
Introduction to Primitives
Recursion 23-Apr-19.
Style 26-Apr-19.
Unit 3: Variables in Java
Presentation transcript:

23-Oct-15 Style

Why style matters Good style isn’t just to make your code “look pretty” The most critical factor in style is readability If a program is readable, It is easier to debug It is easier to maintain It is easier to upgrade For “real” programs (those that actually get used), the time spent reading them far exceeds the time spent writing them 2

Two kinds of style “Syntactic” style Mostly pretty mechanical: Spacing, indentation, capitalization, etc. Eclipse can do a lot of this for you Some more conceptual, for example, the names of methods should be verbs Syntactic style is easier to define “Semantic” style Largely or completely non-mechanical Rules are “slippery,” harder to describe and to apply Learned largely through experience But only if you are willing to experiment and try new approaches Ultimately much more important than syntactic style 3

Syntactic style

5 Be consistent! Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t like them As they are what your team is used to, they will be more readable to other members of your team

6 Do it right the first time You only write code once, but you read it many times while you’re trying to get it to work Good style makes it more readable and helps you get it right! You’re working on a large project, so you use good style......but you need a tool to help you do one little job, so you slap it together quickly Guess which program will be around longer and used by more people?

7 Indent nested code Always indent statements that are nested inside (under the control of) another statement if (itemCost <= bankBalance) { writeCheck(itemCost); bankBalance = bankBalance - itemCost; } The open brace always goes at the end of a line The matching close brace lines up with the statement being closed Don’t use C-style braces unless that is the already established standard for the project you are on Indentation should be consistent throughout the program 4 spaces is the standard for Java (other languages may differ)

8 Break up long lines Keep your lines short enough to be viewed and printed Many people use 72 or 80 character limits Suggestions on where to break a long line: It’s illegal to break a line within a quoted string Break after, not before, operators Line up parameters to a method Don’t indent the second line of a control statement with a long test so that it lines up with the statements being controlled

9 Don’t use “hard” tabs A hard tab is an actual tab character in your text It tells the program to go to the next tab stop (wherever that is) Not every program puts tab stops in the same place If you use hard tabs to indent, sooner or later your nice indentation will be ruined Good editors can be set to use soft tabs (your tab characters are replaced with spaces) When you hit the tab key, the editor puts spaces into your file, not tab characters With soft tabs, your indentation is always safe

10 Using spaces Use spaces around all binary operators except “dot”: if (n > 1 && n % 2 == 1) n = 3 * n + 1; Do not use spaces just within parentheses: if ( x < 0 ) x = -x; // don’t do this Use a space before and after the parenthesized test in a control statement: if (x < 0) {...} while (x < 0) {...} Do not use a space between a method name and its parameters; do put a space after each comma: int add(int x, int y) {...} a = add(3, k);

11 Use meaningful names Names should be chosen very carefully, to indicate the purpose of a variable or method If the purpose changes, the name should be changed Spend a little time to choose the best name for each of your variables and methods! Long, multiword names are common in Java Eclipse will complete long names for you (control-space) However, if a name is too long, maybe you’re trying to use it for too many purposes Don’t change the name, separate the purposes Don’t abbreviate names But very common abbreviations, such as max for “maximum”, are OK

12 Meaningful names: exceptions I It is common practice to use i as the index of a for- loop, j as the index of an inner loop, and k as the index of a third-level loop This is almost always better than trying to come up with a meaningful name Example: for (int i = 1; i <= 10; i++) { for (int j = 1, j <= 10; j++) { System.out.println(" " + (i * j)); } }

13 Meaningful names: exceptions II Local variables in methods may be given short, simple names, if: The purpose of the variable is obvious from context, and The variable is used only briefly, in a small part of the program But never use meaningless names for fields (class or instance variables) or classes or methods

14 Meaningful names: exceptions III If variables have no special meaning, you can use names that reflect their types For example, if you are writing a general method to work with any strings, you might name them string1, string2, etc. Alternatively, you can use very short names s, t, u, or s1, s2, etc. are often used for Strings p, q, r, s are often used for booleans w, x, y, z are often used for real numbers

15 Naming classes and interfaces Capitalize the first letter of each word, including the first word: PrintStream, Person, ExemptEmployee Use nouns to name classes: ExemptEmployee, CustomerAccount Classes are supposed to represent things Use adjectives to name interfaces: Comparable, Printable Interfaces are supposed to represent features

16 Naming variables Capitalize the first letter of each word except the first: total, maxValue Use nouns to name variables: balance, outputLine Variables are supposed to represent values

17 Naming methods Capitalize the first letter of each word except the first: display, displayImage Methods are capitalized the same as variables Use verbs when naming methods: displayImage, computeBalance Methods are supposed to do something

18 Naming constants A constant is an identifier whose value, once given, cannot be changed Constants are written with the keyword final, for example: final int FIVE = 5; final float AVOGADROS_NUMBER = 6.022E23; Constants are written in ALL_CAPITALS, with underscores between words

19 Correct (syntactic) style made easy In Eclipse, go to Window  Preferences  Java  Code Style  Formatter, and under Select a profile: choose Java conventions [built-in] Select some or all of your code and choose Source  Format To simply indent correctly, without reformatting, select some lines and choose Source  Correct Indentation or just type ctrl-I.

Semantic Style

Think small According to world-famous computer scientist Edgser Dijkstra, “We have small heads.” Translation: We can only keep track of a few things at a time Small, single purpose methods are much easier to read, write, and debug Difficulty goes up with the square of the length of the method Think of each method as a “verb” in a language you are inventing for this particular problem Remember the acronym KISS: Keep It Simple, Stupid. 21

Design before you program Good design, especially good choice of data structures, makes a huge difference in how difficult it is to write a program For any given assignment, it is typical to see some submissions ten times as long as other submissions This probably means the student put in ten times as much work The longer the program, the less likely it is to be correct Good programmers usually consider at least two or three ways of doing the assignment before they start coding 22

Test first You have to test anyway, so why not write the tests first? TDD (Test Driven Design) leads to: Shorter, single purpose methods Methods that are testable Methods with a clearly defined function Methods that are more independent (i.e. you don’t have to set up a lot of context before the method can be used) Better separation of concerns (for example, computation vs. input/output) A good test suite greatly simplifies future maintenance 23

Keep it DRY (Don’t Repeat Yourself) Don’t copy and paste code If you repeat a block of code, and the code needs to be debugged or modified, you have to find every place that the code occurs If different parts of a program all use the same code, errors in that code will be exposed and caught much earlier The DRY principle also applies to data If you have two representations of the same information, they must be kept consistent—this is extra work and error-prone Every bit of data should have a single “master” representation; use methods to derive other views of that data 24

Refactor, early and often Whenever you see a better way of doing things than you are currently doing them, refactor Refactoring is modifying code without changing what it does, in order to make it simpler, cleaner, better Refactoring is often necessary in order to add new functionality to a program Here are the most common refactorings: Changing the name of a variable or method when you change what it does (or just think of a better name) Extracting a chunk of code and making it a method (instead of copying and pasting the code) Eclipse makes many refactorings easy and (relatively) fairly safe Refactoring is a lot easier and safer if you have a good test suite 25

Comment Write Javadoc comments for the person who is going to use your classes and methods Tell them everything they need to know in order to use your code Don’t tell them how the code works (unless it’s absolutely required in order to use the code—but this indicates a bad code design) Write internal comments for the person who is going to maintain your code Don’t repeat the obvious—assume they know some Java Explain tricky or obscure code Better yet, replace tricky or obscure code with cleaner code Your goal should always be for short, simple, self-explanatory code that doesn’t need comments 26

Do user testing Sure, you think your user interface is simple and obvious—you wrote it! Sorry, but this is one area where your intuition simply cannot be trusted Even user-interface experts get surprised Getting even one person to try out your user interface will likely find 90% of the problems with it 27

28 The End “Where a calculator on the ENIAC is equipped with vacuum tubes and weighs 30 tons, computers of the future may have only vacuum tubes and perhaps weigh 1½ tons.” —Popular Mechanics, March 1949