Download presentation
Presentation is loading. Please wait.
1
Coding Guidelines Dr.Ledgard
Electrical Engineering and Computer Science Department University of Toledo Toledo, Ohio, USA
2
1. Variable and class names
The general rule is to base all names on conventional English usage. Variables: Not So Good Readable Round Wheel LoopTimes NumLoops Valid InputStatus Starting Source Ending Destination SetWaiting Listener
3
1.Variable and class names
Classes: Not So Good Readable accounting bankAccount setPoint point nodeNetworking socket_info When defining classes, make the class names descriptive, but when declaring an object, especially when the object is used frequently, make the object name short.
4
2. Method and procedure names
A procedure is a funtion that can be called as a statement. Methods and procedures generally denote actions and transformations, and hence should be verbs. Not So Good Readable NameSet SetName Modified Modify Withdrawal Withdraw Right MoveRight
5
3.Boolean names Suppose you are setting a Boolean variable to true after you complete a certain operation a certain number of times. In particular, suppose there is no more space in an array. Not So Good Readable Fill Full Terminate Terminated Real IsReal Edit IsEditable Waits Waiting License hasLicense
6
4. Conventional meaning and English syntax
Care should be taken to retain conventional meaning and English syntax. Name Comment IdVehicle Does not make sense VehicleId Better SectorNum When identifying a specific sector NumSectors When naming the total number of free sectors FormEnable(); Backwards EnableForm(); Better
7
5. Strive for shorter names
All other things equal, shorter names are always better. For example, local variables that are used only for index variables may be named i, j, k, etc. An array index used on every line of the loop need not be named any more elaborately than i. Not So Good Readable Index i, j NumberOfItems n (or N) CheckIfEntryIsCorrect Validate IsARealNumber IsReal Temporary Temp
8
5. Strive for shorter names
Major variables (objects) that are used frequently should be especially short. For major variables that are used throughout the program, a single letter may really help make the program clear. Acceptable Preferable stack CurrentStack; stack S; window Window1, Window2; window W1, W2; frame TopFrame; frame Top; counter Cntr; counter C; searchTree Tree; searchTree ST; MoveRight(); Right();
9
6. shorten names Rely on context to shorten names. A variable can often be shortened based on the context where it is being used. For instance, a variable like Store in a stack implementation is preferred over StackStore. Acceptable Preferable TreeNode Node CustomerID ID StackStore Store CarDriver Driver NameStringInfo Name_Info
10
7.Make names pronounceable
Having to sound out or decrypt names slows down the reading of a program. Poor Readable Tbl Table Genymdhms GenerateTime Cntr Counter Nbr Num
11
8. Underscores or uppercase letters
Use underscores or uppercase letters to show the separation of words in a variable name. For example: Poor Readable inputstatus InputStatus inputstatus inputStatus inputstatus input_status inputstatus Input_Status Itemcount ItemCount
12
9.Abbreviations used sparingly
Any abbreviation should reflect common convention. Long names are hard to read and can also make the code look bad and we don't want that! Name Abbreviated CustomerInformation CustomerInfo AllocationPointer AllocationPtr // Ptr is OK
13
10. Never Name with identical spelling
When you are not sure how to differentiate a class name and a variable name for the class, consider using a longer more descriptive name for the class. Poor Better int Int; int i; player Player; player P; player Player; player NewPlayer; player Player; playerInfo Player; player Player; playerProfile Player; customer Customer; customer Next; customer Customer; CustomerInfo customer; customer Customer; CustomerInfo C1, C2, FirstInLine;
14
1. Consider programs as a “table”.
Code is not English text. It is more like math and tables. For example, the following is quite readable:
15
1. Consider programs as a “table”.
This also means using vertical alignment to show symmetry. For example, instead of
16
2. Do not use a variable width font
Do not use a variable width (proportional) font for program code. Code is not text. Fixed width fonts (e.g. Courier and Data Gothic) look right and make alignment of code easier.
17
public static void main(String[] args) throws IOException
{ Scanner conIn = new Scanner(System.in); TriviaGame game; // the trivia game int questNum; // current question number TriviaQuestion tq; // current question String answer; // answer provided by user // Initialze the game game = GetTriviaGame.useTextFile("game.txt"); // Greet the user. System.out.println("Welcome to the " + game.getQuizName() + " trivia quiz."); System.out.print("You will have " + game.getNumChances() + " chances "); System.out.println("to answer " + game.getCurrNumQuestions() + " questions.\n");
18
public static void main(String[] args) throws IOException { Scanner conIn = new Scanner(System.in); TriviaGame game; // the trivia game int questNum; // current question number TriviaQuestion tq; // current question String answer; // answer provided by user // Initialze the game game = GetTriviaGame.useTextFile("game.txt"); // Greet the user. System.out.println("Welcome to the " + game.getQuizName() + " trivia quiz."); System.out.print("You will have " + game.getNumChances() + " chances "); System.out.println("to answer " + game.getCurrNumQuestions() + " questions.\n");
19
6. Layout of if-then Many programmers commonly use if-then statements. If you have one statement for use with the If-then expression, try to combine it into a single line of code. For multiple statements, use the curly brackets, { }, and indentation to set off the statements from the rest of the code. The following are the three basic types of If-then statements.
20
7. Layout of if-then-else.
21
8. Layout of while loops.
22
9. Layout of for loops
23
10. Functions Be sure to indent the entire bodies of functions. This indentation allows the reader/debugger to realize, with less effort, that the contained variables/methods are a part of the function.
24
11.blank lines between sections
Blank lines can be used to increase readability: When changing from preprocessor directives to code Around class and structure declarations. Around a function definition of some length. Around a group of logically connected statements of some length. Between declarations and the executable statements that follow.
25
11.blank lines between sections
26
12. Blank spaces to show meaning
Strategic blank spaces within a line simplify parsing by the human reader. For example, X = A + B*C; is more readable than X = A+B * C; // shows wrong precedence or X=A+B*C; // does now show clearly (A + B*C) is assigned to X When statements become more complex, showing the parts of a statement becomes even more important.
27
12. Blank spaces to show meaning
Use blank spaces: After commas in argument lists. Around the assignment operator "=" and the redirection operators ">>" and "<<". Do Not Use blank spaces: For unary operators like unary minus (-), address of (&), indirection(*), member access (.), increment (++) and decrement (--).
28
13. Short functions may not need blank lines.
If a function is a one-liner, put the whole function on one line, especially with a group of short functions. For instance, use int GetProduct(int a, int b) {return a*b;} not int GetProduct(int a, int b) { return a*b; }
29
14. If it makes sense, put 2-3 statements on one line
That would really simplify code, but only where sensible. For example, use : case FOO : oogle(zork); boogle(zork); break; case BAR : oogle(zork); boogle(zork); break; case BAZ : oogle(zork); boogle(zork); break;
30
15. Make all lines so that they can be displayed without wrapping
On an 80-character display. If wrapping is required, try to break at an operator, and start the next line with the operator vertically aligned. For example:
31
C. Comments 1. Identifying information.
2. Comments should be kept simple like a bullet list. 3. Cluster your comments at the beginning of each unit (function, class, or program). 4. Reduce comments to their most simple form.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.