Style 24 Nov20 Why style matters n n

  • Slides: 27
Download presentation
Style 24 -Nov-20

Style 24 -Nov-20

Why style matters n n n Good style isn’t just to make your code

Why style matters n n n Good style isn’t just to make your code “look pretty” The most critical factor in style is readability If a program is readable, n n 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 n “Syntactic” style n n n Mostly pretty mechanical: Spacing,

Two kinds of style n “Syntactic” style n n n 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 n n n Largely or completely non-mechanical Rules are “slippery, ” harder to describe and to apply Learned largely through experience n n But only if you are willing to experiment and try new approaches Ultimately much more important than syntactic style 3

Syntactic style

Syntactic style

Be consistent! n Most times, you will enter an ongoing project, with established style

Be consistent! n Most times, you will enter an ongoing project, with established style rules n n 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 5

Do it right the first time n You only write code once, but you

Do it right the first time n You only write code once, but you read it many times while you’re trying to get it to work n n Good style makes it more readable and helps you get it right! You’re working on a large project, so you use good style. . . n n . . . 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? 6

Indent nested code n Always indent statements that are nested inside (under the control

Indent nested code n Always indent statements that are nested inside (under the control of) another statement n n n if (item. Cost <= bank. Balance) { write. Check(item. Cost) bank. Balance = bank. Balance - item. Cost } 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 n 2 spaces is the standard for Scala (4 spaces for Java) 7

Break up long lines n n n Keep your lines short enough to be

Break up long lines n n n 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: n It’s illegal to break a line within a quoted string n n Break after, not before, operators n n Unless you use “triple quotes” A line ending with a binary operator is obviously incomplete 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 You can often make a line shorter by giving names to subexpressions n This has the additional advantage of explaining those subexpressions 8

Don’t use “hard” tabs n A hard tab is an actual tab character in

Don’t use “hard” tabs n A hard tab is an actual tab character in your text n n 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) n n When you hit the tab key, the editor puts spaces into your file, not tab characters With soft tabs, your indentation is always safe 9

Using spaces n n n Use spaces around all binary operators except “dot”: if

Using spaces n n n 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: def add(x: Int, y: Int) {. . . } a = add(3, k) General rule: Space as you would in English (treating operators as words) 10

Correct (syntactic) style made easy n n Select some or all of your code,

Correct (syntactic) style made easy n n Select some or all of your code, right click, and choose Source Format Don’t use Source Correct Indentation -- that’s set up to use Java indentation (4 spaces) 11

Semantic Style

Semantic Style

Use meaningful names n Names should be chosen very carefully, to indicate the purpose

Use meaningful names n Names should be chosen very carefully, to indicate the purpose of a variable or method n n n 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 n n 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 n n Don’t change the name, separate the purposes Don’t abbreviate names n But very common abbreviations, such as max for “maximum”, are OK 13

Meaningful names: exceptions I n n n It is common practice to use i

Meaningful names: exceptions I n n n It is common practice to use i as the index of a forloop, j as the index of an inner loop, and k as the index of a third-level loop This is often better than trying to come up with a meaningful name Example: n for (i <- 1 to 10) { for (j <- 1 to 10) { println(" " + (i * j)) } } 14

Meaningful names: exceptions II n Local variables in methods may be given short, simple

Meaningful names: exceptions II n Local variables in methods may be given short, simple names, if: n n n 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 15

Meaningful names: exceptions III n If a variable has no special meaning, you can

Meaningful names: exceptions III n If a variable has no special meaning, you can use a name that reflects its type n n For example, if you are writing a general method to work with any strings, you might name them string 1, string 2, etc. Alternatively, you can use very short names n n n s, t, u, or s 1, s 2, etc. are often used for Strings p, q, r, s are often used for Booleans w, x, y, z are often used for Doubles 16

Naming classes and interfaces n n Capitalize the first letter of each word, including

Naming classes and interfaces n n Capitalize the first letter of each word, including the first word: Print. Stream, Person, Exempt. Employee Use nouns to name classes: Exempt. Employee, Customer. Account n n Classes are supposed to represent things Use adjectives to name traits: Comparable, Printable n Traits are supposed to represent capabilities 17

Naming variables n n Capitalize the first letter of each word except the first:

Naming variables n n Capitalize the first letter of each word except the first: total, max. Value Use nouns to name variables: balance, output. Line n Variables are supposed to represent values 18

Naming methods n Capitalize the first letter of each word except the first: display,

Naming methods n Capitalize the first letter of each word except the first: display, display. Image n n Methods are capitalized the same as variables Use verbs when naming methods: display. Image, compute. Balance n Methods are supposed to do something 19

Think small n According to world-famous computer scientist Edgser Dijkstra, “We have small heads.

Think small n According to world-famous computer scientist Edgser Dijkstra, “We have small heads. ” n n Small, single purpose methods are much easier to read, write, and debug n n n Translation: We can only keep track of a few things at a time 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. 20

Design before you program n n Good design, especially good choice of data structures,

Design before you program n n 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 n n n 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 21

Test first n n You have to test anyway, so why not write the

Test first n n You have to test anyway, so why not write the tests first? TDD (Test Driven Design) leads to: n n n 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 22

Keep it DRY (Don’t Repeat Yourself) n Don’t copy and paste code n n

Keep it DRY (Don’t Repeat Yourself) n Don’t copy and paste code n n n 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 n n 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 23

Refactor, early and often n Whenever you see a better way of doing things

Refactor, early and often n Whenever you see a better way of doing things than you are currently doing them, refactor n n n Here are the most common refactorings: n n 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 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 24

Comment n Write documentation comments for the person who is going to use your

Comment n Write documentation comments for the person who is going to use your classes and methods n n n 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 n n Don’t repeat the obvious—assume they know some Java Explain tricky or obscure code n n 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 25

Do user testing n Sure, you think your user interface is simple and obvious—you

Do user testing n Sure, you think your user interface is simple and obvious—you wrote it! n n n 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 26

The End “Where a calculator on the ENIAC is equipped with 18 000 vacuum

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