<<

PROGRAM READABILITY

A convention is a group of agreed to or generally accepted rules. A programming convention is one that a seasoned programmer follows when writing his or her code. There’s no quicker way to reveal that you’re a “newbie” than by ignoring conventions. Some of these conventions are specific to Java; others are used by computer programmers in all languages.

This topic covers programming conventions that pertain to program A program's readability readability, which is a measure of how corresponds to how easily it easily a computer program can be read and can be read and understood understood by a human being. The reader needs to comprehend the purpose of the computer statements, the machine operations they describe and the interaction between different segments of readability program's The How easily the program can be read and understood code. Many factors affect program readability, but in this topic we’ll focus on the written presentation of the program.

Camel-Case Java’s spelling convention is a style called camel-case, where the first letter of each successive word in an identifier is capitalized. Camel-case is further divided into upper camel-case, in which you capitalize the first letter of the identifier; and lower camel-case, in which you don’t.

Use upper camel-case for Java class identifiers.

Examples CamelCase MyApplication String

Scanner System GregorianCalendar

Use lower camel-case for Java variable and method identifiers.

Examples main( . . . ) radius area salesForFirstQuarter dayOfYear outsideDegreesF

nextDouble( ) print( . . . ) println( . . . )

Program Readability Page 1 Meaningful Identifiers Java programmers should select “meaningful” identifiers (i.e. identifiers that are self explanatory) whenever possible; but try to avoid overly long ones.

Example Pretend you need a variable to hold a temperature reading in degrees Fahrenheit. reading No – too vague. degrees No – too imprecise. t Too short; also can be confused with time. temp OK but can be confused with temporary. temperature OK. fahrenheit Better. degreesFahrenheit Good, although it’s rather long. degreesF Perhaps a suitable short version of the one above.

Constant Identifiers A constant identifier has an immutable value and is created by preceding the declaration and initialization with the modifier final.

Example final double PI = 3.14159;

A constant identifier can be used in the same manner as a variable except that its value cannot be changed during the program run.

Example area = PI * radius * radius OK. Value of PI is used.

Wrong! PI is immutable – cannot be changed PI = in.nextDouble( ); during the program run.

Program Readability Page 2 In Java, a constant value is any value that can be determined by the compiler before the program is actually executed.1 It is most usually a literal, a previously declared constant identifier or an expression involving previously declared constant identifiers.

Example final double HI = 100; final double LO = 0; final double RANGE = HI - LO; final double MID = RANGE / 2 + LO;

Seasoned programmers use constant identifiers for two reasons. First, to help a human reader better understand the program. Code whose purpose is self-evident without further explanation is said to be self documenting.

Example

Self-Documenting Code Not So Much

miles = MILES_PER_KM * kilometers; m = .621 * k;

Second, a constant identifier keeps you from having to repeatedly type (and possibly mistype) complicated values such as π (3.1459) or e (2.71828183) or values that change periodically such as the number of students in a class.

Example final double E = 2.71828183; final int CLASS_SIZE = 25;

Finally, do not use a named constant for a value that (a) is easy to type, (b) is widely understood and () never changes.

Example Never do this. final double TWO = 2.0;

1 Hardware, Software and Computer Languages → Compile Time and Runtime, p. 1.

Program Readability Page 3 Java’s spelling convention for constant identifiers is to use all capital letters and separate the embedded words with the underscore (_) character.

Examples PI APR POINTS_POSSIBLE

CLASS_SIZE MILES_PER_KM SALES_TAX_RATE

Commenting Completely self-documenting code is the programming ideal; but it is very difficult to achieve. Program comments must be used to explain whatever is not self-evident from the code.

Computer programs written by professional programmers for commercial purposes are used for years; sometimes decades. As the years pass, the needs of the users change. Thus, programs are likely to be altered through the years by someone other than whoever originally wrote them. Any explanation of what is going on in your mind when you write your code will be greatly appreciated by this unknown future colleague.

A program preface can explain the program’s overall purpose. It may be appropriate to include the algorithm used for the program.

Example /* Input an integer n > 2 and print the prime numbers from 2 through n.

The program uses "the sieve of Eratosthenes":

(1) Place all integers 2...n into the sieve. (2) Remove the nonprime integers from the sieve: Remove the multiples of k = 2, 3, 5, etc. until k > sqrt(n) (3) Only primes remain in the sieve => print them */

Program Readability Page 4 Always comment the declaration of any program datum whose purpose is not self evident from its identifier.

Example final double FT_PER_M = 3.281; // 1 m = 3.281 ft. double t; // travel time in seconds double dist; // distance traveled

Salt your code with comments that identify its major sections.

Example // input data . . . // calculate area . . .

Use statements from your pseudo-code algorithm to explain the purpose of your code.

Example // start the game by tossing two dice die1 = (int)(Math.random( ) * 6 + 1); die2 = (int)(Math.random( ) * 6 + 1);

Explain code whose mechanics are not self evident.

Example // is the number even? if ( number % 2 == 0 ) . . .

Program Readability Page 5 Spacing and Indention Java ignores any white space within a program that is not needed to separate two lexemes, allowing you to use extra white space to visually enhance your program by spreading your code out horizontally and vertically. If not done too drastically, this greatly improves a program’s readability.

Example The familiar nursery rhyme, written below without spaces, demonstrates how improper spacing reduces readability.

MaryhadalittlelambhisfleecewaswhiteassnowandeverywherethatMarywentthelambwassuretogo. Hefollowedhertoschoolonedaywhichwasagainsttheruleitmadethechildrenlaughandplaytoseealamb atschool.

Example The Java application below from a previous topic2 has had its comments and unneeded spaces removed. It is correct and perfectly clear to the Java compiler – i.e. it compiles and runs file – but it is not very readable to a human. import java.util.Scanner; public class Circle{public static void main(String[]args){ double radius,diameter; Scanner in=new Scanner(System.in); System.out.print("Enter circle's radius: "); radius=in.nextDouble( );diameter=2*radius; System.out.print("A circle with radius "+radius); System.out.println(" has diameter "+diameter);}}

2 Hardware, Software and Computer Languages → Java IPO Programs, p. 1.

Program Readability Page 6 In Java programming, indention is used to visually emphasize statements inside brace ({}) delimited code. There are two predominant styles. One style has the matching braces in the same column, making it easier to match the closing brace (}) with its opening brace ({).

Example 1 public class HelloWorld 2 { 3 public static void main( String [] args ) 4 { 5 System.out.println( "Welcome to Java Programming!" ); 6 } 7 }

The other style places the opening brace ({) at the end of the first line of the construct and the closing brace (}) in the same column as the construct’s initial keyword. In addition to using fewer lines, this style better emphasizes the ending of the construct.

Example 1 public class HelloWorld { 2 public static void main( String [] args ) { 3 System.out.println( "Welcome to Java Programming!" ); 4 } 5 }

The style is not as important as consistency – pick a style and stick with it throughout the same program.

Program Readability Page 7 Exercises

1. Pretend you need a variable to hold a distance in feet. Rank the following identifiers in order, 1 = the best and 7 = the worst. Write a brief reason for your ranking. d distance f ft distanceInFeet feet dist

2. Circle the identifiers that use camel-case. myapplication MyApplication MYAPPLICATION

firstQuarterSales firstquartersales FirstQuarterSales

FIRST_QUARTER_SALES

3. Each of these class identifiers uses correct Java syntax. Circle the identifiers that are spelled according to Java’s naming convention. MyApplication myApplication MY_APPLICATION

scanner Scanner SCANNER

System system SYSTEM

4. Each of these variable or method identifiers uses correct Java syntax. Circle the identifiers that are spelled according to Java’s naming convention. AverageScore averageScore AVERAGE_SCORE

nextdouble( ) NextDouble( )

PRINT Print print

Program Readability Page 8 5. Each of these constant identifiers uses correct Java syntax. Circle the identifiers that are spelled according to Java’s naming convention. FEET_PER_METER FeetPerMeter feetPerMeter

PI Pi EUROSYMBOL

6. Write the statement to declare the constant identifier TAX_RATE to have the value 0.08.

7. Comment on the suitability of each named constant. final double PI = 3.14159; final double TWO = 2.0;

8. Comment on the suitability of each named constant. final double APR = 18; // annual percentage interest rate final double ONE_HUNDRED = 100.0; final double MONTHS_PER_YEAR = 12.0;

Program Readability Page 9