Fundamental Data Types CSC3004 Introduction to Software Development
































- Slides: 32
Fundamental Data Types CSC-3004 Introduction to Software Development Spring 2013 Dr. James Skon
Numbers in General Avoid "magic numbers" – Magic numbers are literal numbers, such as 100 or 47524, that appear in the middle of a program without explanation – If you program in a language that supports named constants, use them instead. – If you can't use named constants, use global variables when it's feasible to do so.
Numbers in General Avoiding magic numbers yields three advantages: – Changes can be made more reliably. • Must change all “ 100”s to “ 200”s that deal with some aspect. But which? – Changes can be made more easily. • Change once! – Your code is more readable. • for i = 0 to 99 do. . . • for i = 0 to MAX_ENTRIES-1 do. . .
Numbers in General Use hard-coded 0 s and 1 s if you need to. – The values 0 and 1 are used to increment, decrement, and start loops at the first element of an array. • for i = 0 to CONSTANT do. . . • total = total + 1
Anticipate divide-by-zero errors Each time you use the division symbol (/ in most languages), think about whether it's possible for the denominator of the expression to be 0. – If the possibility exists, write code to prevent a divide-by-zero error.
Make type conversions obvious. Make sure that someone reading your code will be aware of it when a conversion between different data types occurs. In C++ you could say: y = x + (float) i
Avoid mixed-type comparisons If x is a floating-point number and i is an integer, the test if ( i = x ) then … is almost guaranteed not to work. By the time the compiler figures out which type it wants to use for the comparison, converts one of the types to the other, does a bunch of rounding, and determines the answer, you'll be lucky if your program runs at all.
Integers Check for integer division – – – When you're using integers, 7/10 does not equal 0. 7. It usually equals 0, or minus infinity, or the nearest integer … What it equals varies from language to language Consider: 10 * (7/10) = (10*7) / 10 = 7
Check for integer overflow Integer Type Range Signed 8 -bit − 128 through 127 Unsigned 8 -bit 0 through 255 Signed 16 -bit − 32, 768 through 32, 767 Unsigned 16 -bit 0 through 65, 535 Signed 32 -bit − 2, 147, 483, 648 through 2, 147, 483, 647 Unsigned 32 -bit 0 through 4, 294, 967, 295 Signed 64 -bit through Ranges− 9, 223, 372, 036, 854, 775, 808 for Different Types of Integers 9, 223, 372, 036, 854, 775, 807
Check for integer overflow The easiest way to prevent integer overflow is to think through each of the terms in your arithmetic expression and try to imagine the largest value each can assume
Check for overflow in intermediate results The number at the end of the equation isn't the only number you have to worry about Consider: int term. A = 1000000; int term. B = 1000000; int product = term. A * term. B / 1000000; System. out. println( "( " + term. A + " * " + term. B + " ) / 1000000 = " + product ); Output: ( 1000000 * 1000000 ) / 1000000 = -727 WHY?
Floating-Point Numbers floating-point numbers can't represent many fractional decimal numbers accurately a 32 -bit floating-point representation of 1/3 equals 0. 33333330
Floating-Point Numbers Avoid additions and subtractions on numbers that have greatly different magnitudes – – With a 32 -bit floating-point variable, 1, 000. 00 + 0. 1 = 1, 000. 00 Why? because 32 bits don't give you enough significant digits to encompass the range between 1, 000 and 0. 1. Likewise, 5, 000. 02 - 5, 000. 01 = 0. 0.
Floating-Point Numbers 1 is equal to 2 for sufficiently large values of 1. —Anonymous
Floating-Point Numbers Avoid equality comparisons Floating-point numbers that should be equal are not always equal. – – The main problem is that two different paths to the same number don't always lead to the same number. For example, 0. 1 added 10 times rarely equals 1. 0
Values of I: Floating-Point Numbers 0. 1 double nominal = 1. 0; double sum = 0. 0; for ( int i = 0; i < 10; i++ ) { sum += 0. 1; } if ( nominal == sum ) { 0. 2 0. 3000000004 The variable nominal is a 0. 4 64 -bit real 0. 5 0. 6 sum is 10*0. 1. 0. 7 It should be 1. 0. l 0. 799999999 0. 899999999 Here's the bad 0. 99999999 comparison System. out. println( "Numbers are the same. " ); } else { System. out. println( "Numbers are different. " ); }
Floating-Point Numbers final double ACCEPTABLE_DELTA = 0. 00001; boolean Equals( double Term 1, double Term 2 ) { if ( Math. abs( Term 1 - Term 2 ) < ACCEPTABLE_DELTA ) { return true; } else { return false;
Characters and Strings Avoid magic characters and strings Fo r commonly occurring strings use a constant, or Place in string resources file. – – – This allows for translation to other languages Takes up less memory Good names make more sense
Boolean Variables Use boolean variables to document your program – Instead of merely testing a boolean expression, you can assign the expression to a variable that makes the implication of the test unmistakable if ( ( element. Index < 0 ) || ( MAX_ELEMENTS < element. Index ) || ( element. Index == last. Element. Index ) ){. . .
Boolean Variables Improved Test: finished = ( ( element. Index < 0 ) || ( MAX_ELEMENTS < element. Index ) ); repeated. Entry = ( element. Index == last. Element. Index ); if ( finished || repeated. Entry ) {. . . }
Boolean Variables Consider If ( ( document. At. End. Of. Stream() ) And ( Not input. Error ) ) And _ ( ( MIN_LINES <= line. Count ) And ( line. Count <= MAX_LINES ) ) And _ ( Not Error. Processing() ) Then ' do something or other. . . End If}
Boolean Variables Or consider all. Data. Read = ( document. At. End. Of. Stream() ) And ( Not input. Error ) legal. Line. Count = ( MIN_LINES <= line. Count ) And ( line. Count <= MAX_LINES ) If ( all. Data. Read ) And ( legal. Line. Count ) And ( Not Error. Processing() ) Then // do something or other. . . End If
Enumerated Types Public Enum Color_Red Color_Green Color_Blue End Enum Public Enum Output_Screen Output_Printer Output_File End Enum Public Enum Country_China Country_England Country_France Country_Germany Country_India Country_Japan Country_Usa End Enum
Use enumerated types for readability Instead of: if chosen. Color = 1 you can write more readable expressions like if chosen. Color = Color_Red
Enumerated Types Anytime you see a numeric literal, ask whether it makes sense to replace it with an enumerated type: int result = Retrieve. Payroll. Data( data, true, false, true ); int result = Retrieve. Payroll. Data( data, Employment. Status_Current. Employee, Payroll. Type_Salaried, Savings. Plan_No. Deduction, Medical. Coverage_Include. Dependents );
Enumerated Types Use enumerated types for modifiability Easier to change, makes more sense Use enumerated types as an alternative to boolean variables – – Often, a boolean variable isn't rich enough to express the meanings it needs to. an enumerated type with the values Status_Success, Status_Warning, and Status_Fatal. Error would be more useful than a boolean with the values true and false.
Enumerated Types Check for invalid values: Select Case screen. Color Case Color_Red. . . Case Color_Blue. . . Case Color_Green. . . Case Else Display. Internal. Error( False, "Internal Error 752: Invalid color. " ) End Select
Enumerated Types Define the first and last entries of an enumeration for use as loop limits Public Enum Country_First = 0 Country_China = 0 Country_England = 1 Country_France = 2 Country_Germany = 3 Country_India = 4 Country_Japan = 5 Country_Usa = 6 Country_Last = 6 End Enum
Named Constants Using a named constant is a way of "parameterizing" your program When an array size changes, you change only the definition of the constant you used to declare the array. This "single-point control" goes a long way toward making software truly "soft": easy to work with and change.
Named Constants For (int i ; i <=12 ; i++) { profit( i ) = revenue( i ) - expense( i ); } For (int month ; month <=NUM_MONTHS_IN_YEAR ; month++) { profit( month ) = revenue( month ) -- expense( month ); }
Arrays Make sure that all array indexes are within the bounds of the array Consider using containers instead of arrays, or think of arrays as sequential structures – – Consider using container classes that you can access sequentially—sets, stacks, queues, and so on—as alternatives Random access is like GOTO's – very unstructured