CS 240 – Advanced Programming Concepts

Slides:



Advertisements
Similar presentations
Chapter 1: Computer Systems
Advertisements

Software Engineering Routine design. High quality routines Routine: individual method or procedure invocable for a single purpose.
Introduction to C Programming
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
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.
Outline Java program structure Basic program elements
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
CSE1301 Computer Programming: Lecture 13 Documentation.
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.
Chapter 2: Introduction to C++.
Introduction to C Programming
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.
General Issues in Using Variables
The Pseudocode Programming Process Chapter 9. Summary of Steps in Building Classes and Routines.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Java Language and SW Dev’t
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
The Java Programming Language
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
CPS120: Introduction to Computer Science
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Software Implementation (Writing Quality Code). void HandleStuff( CORP_DATA & inputRec, int crntQtr, EMP_DATA empRec, float & estimRevenue, float ytdRevenue,
Lecture 1 Introduction Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
High-Quality Routines Chapter 5-6. Review Class Quality Checklist 2.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Working with Java.
Chapter 2 Introduction to C++ Programming
Lecture 1 Introduction Richard Gesick.
Lecture 3: Operators, Expressions and Type Conversion
Java Primer 1: Types, Classes and Operators
EGR 2261 Unit 4 Control Structures I: Selection
The Pseudocode Programming Process
University of Central Florida COP 3330 Object Oriented Programming
Introduction to C Topics Compilation Using the gcc Compiler
Stack Data Structure, Reverse Polish Notation, Homework 7
High-Quality Routines
Coding Design, Style, Documentation and Optimization
Objects First with Java
PROGRAMMING METHODOLOGY
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Chapter 1: Computer Systems
Creating your first C program
Chapter 09 – Part I Creating High-Quality Code
Introduction to C++ Programming
Focus of the Course Object-Oriented Software Development
Beginning Style 27-Feb-19.
Chapter 2: Introduction to C++.
Software Design Principles
CMSC 345 Programming.
Unit 3: Variables in Java
Chap 2. Identifiers, Keywords, and Types
Variables in C Topics Naming Variables Declaring Variables
CSCE-221 C++ Coding Standard/Guidelines
Instructor: Alexander Stoytchev
Controlling Program Flow
Presentation transcript:

CS 240 – Advanced Programming Concepts Writing Quality Code CS 240 – Advanced Programming Concepts

void handleStuff( CORP_DATA inputRec, int crntQtr, EMP_DATA empRec, float estimRevenue, float ytdRevenue, int screenX, int screenY, COLOR_TYPE newColor, COLOR_TYPE prevColor, STATUS_TYPE status, int expenseType ) { for ( int i = 1; i <= 100; ++i ) { inputRec.revenue[ i ] = 0; inputRec.expense[ i ] = corpExpense[ crntQtr, i ]; } UpdateCorpDatabase( EmpRec ); estimRevenue = ytdRevenue * 4.0 / (float)crntQtr ; newColor = prevColor; status = Success; if ( expenseType == 1 ) { for ( int i = 1; i <= 12; ++i ) profit[ i ] = revenue[ i ] - expense.type1[ i ]; else if ( expenseType == 2 ) { profit[ i ] = revenue[ i ] - expense.type2[ i ]; else if ( expenseType == 3 ) profit[ i ] = revenue[ i ] - expense.type3[ i ]; What is wrong with this method? (1) The method has a bad name. HandleStuff tells you nothing about what the method does. (2) The method isn't documented. It's not self-documenting, and it doesn't contain any comments. (3) The method has bad layout. Its physical organization on the page gives few hints about its logical structure. Different styles are used in different parts of the method. (4) The method's input variable, inputRec, is modified by the method. If it's an input variable, its value should not be modified. If its supposed to be modified, it shouldn't be named inputRec. (5) The method reads and writes global variables. It reads from corpExpense and writes to profit. It should communicate directly with other methods through parameters rather than through global variables. (6) The method doesn't have a single purpose. It initializes some variables, writes to a database, does some calculations - none of which seem to be related to each other. A method should have a single, clearly-defined purpose. (7) The method doesn't protect itself against bad data. If crntQtr is 0, we get a divide-by-zero. (8) The method uses several magic numbers. (9) The method uses only two fields of the inputRec parameter which is of type CORP_DATA. If only two fields are used, the specific fields rather than the whole structure should be passed in. (10) Some of the method's parameters are unused (screenX and screenY). (11) One of the method's parameters is mislabeled. prevColor is passed as a non-const reference even though the method doesn't change its value. It should either be passed by value or by const reference. (12) The method has too many parameters. The upper limit for an understandable number of parameters is about 7. This method has 11. (13) The method's parameters are poorly ordered and are not documented. Parameters should be ordered as follows: in, in-out, out.

Quality Code Example If you would like to see an example of generally well-written code, look at the Job Scheduler program

Strong Cohesion Just like classes, methods should be highly cohesive A cohesive method does one and only one thing, and has a name that effectively describes what it does getCustomerName, eraseFile, calculateLoanPayment Methods that do too much become obvious if we name them properly doDishesAndWashClothesAndSweepFloor

Good Method Names A method name should clearly and completely describe what the method does If a method prints a report and re-initializes the printer, it should be named printReportAndInitPrinter , not just printReport Method has no return value (i.e., void) Name should be a verb or verb phrase Method has return value (i.e., non-void) Name can be a verb or verb phrase Or, it can describe what the method returns instead of what it does isPrinterReady, currentPenColor, nextCustomerId

Good Method Names Avoid meaningless verbs handleCalculation, performServices, dealWithInput Methods that are not cohesive are often difficult to name Make method names long enough to be easily understood (don’t abbreviate too much) Establish conventions for naming methods Boolean functions - isReady, isLeapYear, … Initialization - Initialize/Finalize, Setup/Cleanup, … Getters/setters - getName, setName, … add/remove, insert/delete

Reasons for Creating Methods One of our primary tools in writing quality code is knowing when and why to create new methods Classes are abstractions that represent the “things” in a system Methods are abstractions that represent the “algorithms” in a system There are many reasons to create methods; we will focus on a few: Top-down decomposition of algorithms Avoiding code duplication Avoiding deep nesting

Algorithm Decomposition Long or complex methods can be hard to understand Long or complex methods can be simplified by factoring out meaningful sections of code into well-named sub-methods The original method becomes a "driver" that calls the sub-methods (it becomes shorter, simpler, and easier to understand) The extracted methods may be placed on different classes (i.e., put sub-methods on the class that contains the data they use) Decomposition continues until methods are sufficiently short and simple Example: Schedule’s getNextWorkDay, isWeekendDay, and isHoliday methods

Comments If you feel a need to comment a paragraph of code, consider putting that section of code in a method of its own with a descriptive name This may do away with the need for the comment, and result in highly-readable code Do whatever makes the code the most readable Factor out into separate method with a good name, or Leave code inline with a comment If a method is heavily commented, that might indicate that further decomposition is necessary

Avoid Code Duplication Avoiding code duplication is one of the most important principles of software design Duplicated code makes software maintenance difficult and error-prone If the same code is needed in multiple places, put the code in a method that can be called wherever the code is needed Inheritance can also be used to avoid code duplication (inherit shared code from a common superclass)

Deep Nesting Excessive nesting of statements is one of the chief culprits of confusing code You should avoid nesting more than three or four levels Creating additional sub-methods is the best way to remove deep nesting

Parameters Use all of the parameters The more parameters a method has, the harder it is to understand The fewer parameters the better One rule-of-thumb is that you should limit parameters to no more than 7, and that many should be rare Order parameters as follows: in, in-out, out

Guidelines for Initializing Data Improper data initialization is one of the most fertile sources of error in computer programming Initialize variables when they're declared Declare variables close to where they're used Variables don't have to be declared at the top of the method Check for the need to reinitialize a variable Counters, accumulators, etc. Compiler warnings can help find un-initialized variables Java automatically initializes instance variables and doesn’t allow you to use uninitialized local variables

Code Layout The physical layout of the code strongly affects readability Imagine a program with no newlines Imagine a program with no indentation Good layout makes the logical structure of a program clear to the reader Good layout helps avoid introducing bugs when the code is modified Pick a style that you like and consistently use it If your organization has a standard, use it (even if you prefer a different style)

Whitespace Use whitespace to enhance readability Spaces, tabs, line breaks, blank lines Organize methods into "paragraphs" Paragraph = a group of closely related statements Separate paragraphs with one or more blank lines Indentation Use indentation to show the logical structure (i.e., nesting)

Expressions Arithmetic and logic expressions can be hard to understand Over-parenthesize arithmetic expressions Enhance readability Make clear the order of operator evaluation Insert extra spaces between operands, operators, and parentheses to enhance readability while (startPath+pos<=length(pathName)&& pathName[startPath+pos]!=';') { … } while (((startPath + pos) <= length(pathName)) && pathName[startPath + pos] != ';') { … }

Expressions Put separate conditions on separate lines if (('0' <= inChar && inChar <= '9') || ('a' <= inChar && inChar <= 'z') || ('A' <= inChar && inChar <= 'Z')) { … } if (('0' <= inChar && inChar <= '9') || ('a' <= inChar && inChar <= 'z') || ('A' <= inChar && inChar <= 'Z')) { … }

Expressions Or, even better Put expressions, or pieces of them, in well-named submethods if (isDigit(inChar) || isLowerAlpha(inChar) || isUpperAlpha(inChar)) { … } Or, even better if (isAlphaNumeric(inChar)) { … } boolean isAlphaNumeric(char c) { return (isDigit(c) || isLowerAlpha(c) || isUpperAlpha(c));

Placing curly braces for (int i=0; i < MAX; ++i) { values[i] = 0; } Version 1: The commonly accepted Java standard Version 2: An alternative style preferred by many programmers Versions 3 & 4: Don’t use

Placing curly braces What about this? for (int i=0; i < MAX; ++i) values[i] = 0; Always use curly braces, even when not required because you’re only enclosing one statement

Method parameters Use spaces to make method parameters readable WebCrawler.crawl(rootURL,outputDir,stopWordsFile); WebCrawler.crawl( rootURL, outputDir, stopWordsFile ); WebCrawler.crawl(rootURL, outputDir, stopWordsFile);

One statement per line Declare each variable on a separate line More robust under modification Easier to understand int * p, q; // oops! int * p; // correct int * q; Don't put multiple statements on the same line x = 0; y = 0; x = 0; y = 0;

Wrapping long lines When should you wrap long lines? When they won't fit on the screen? Whose screen? Wrapping between 80 and 100 characters is common Lines longer than that are hard to read It discourages deep nesting Align continuation lines in a way that maximizes readability

Wrapping long lines private boolean isNthDayOfWeekInMonth(Calendar date, int n, int dayOfWeek, int month) { ... } target = addDependenciesToTarget(dependencyGraph, targetName, dependencyList); DailySchedule newDailySchedule = new DailySchedule(getNextSchedulableDay(today)); return (date.get(Calendar.DAY_OF_WEEK) == dayOfWeek && date.get(Calendar.MONTH) == month && date.get(Calendar.DAY_OF_WEEK_IN_MONTH) == n);

Pseudo-Code When writing an algorithmically complex method, write an outline of the method before starting to code Use English-like statements to describe the steps in the algorithm Avoid syntactic elements from the target programming language Design at a higher level than the code itself Write pseudo-code at the level of intent What more than how (the code will show how) Write pseudo-code at a low enough level that generating code from it is straightforward If pseudo-code is too high-level, it will gloss over important details

Example of bad pseudo-code increment resource number by 1 allocate a dlg struct using malloc if malloc() returns NULL then return 1 invoke OSrsrc_init to initialize a resource for the operating system *hRsrcPtr = resource number return 0 Intent is hard to understand Focuses on implementation rather than intent Includes too many coding details Might as well just write the code

Example of good pseudo-code Keep track of current number of resources in use If another resource is available Allocate a dialog box structure If a dialog box structure could be allocated Note that one more resource is in use Initialize the resource Store the resource number at the location provided by the caller EndIf Return TRUE if a new resource was created else return FALSE Written entirely in English Not programming language specific Written at level of intent Low-level enough to write code from

Choose Good Variable Names Too Long NumberOfPeopleOnTheUSOlympicTeam Too Short N Just Right NumTeamMembers Are short variable names always bad? NO Loop control variables: i, j, k, idx Temporary variables: temp Names that are naturally short: x, y, z

Naming Conventions Separating words in identifiers "Camel-case" WebCrawler, documentMap Separate words with underscores Web_crawler, document_map First char of class name is upper-case First char of method name is lower case First char of variable name is lower-case Constant names are usually all upper-case with words separated by underscore

Creating Readable Names Names matter more to readers of the code than to the author of the code Don't use names that are totally unrelated to the entities they represent (e.g., “Thingy”) Don't differentiate variable names solely by capitalization int temp; char Temp; Avoid variables with similar names but different meanings Mountain timp;

Creating Readable Names Avoid words that are commonly misspelled Avoid characters that are hard to distinguish (1 and l) Avoid using digits in names (e.g., File1 and File2) srcFile and destFile might be better Sometimes Dr. Seuss naming is the best you can do (Thing1 and Thing2)

Abbreviation Guidelines Only abbreviate when you have to Remove non-leading vowels (Computer -> Cmptr) Or, Use the first few letters of a word (Calculate -> Calc) Don't abbreviate by removing just one character from a word (use "name" instead of "nam") Create names that you can pronounce Abbreviate consistently