|
Programming LanguagesThis page examines the differences among programming languages. Take the Brainbench certification test on OO Concepts There are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies; the other is to make it so complicated that there are no obvious deficiencies. —C.A.R. Hoare
|
|
|
Language Features Compared
Inheritance "is a" relationshipAn object that is inherited from another object automatically receives all of the variables and methods defined by the parent. The extends keyword is used to indicate class inheritance.Unlike C, a new class written in Java can extend only one class. Java supports single inheritance. However, a Java program can use many interfaces. Interfaces can be used as data types. Interfaces specify the methods the class must have. The outcome from an Object Oriented (OO) approach to Analysis and Design is an Object Model. During the design of an application, functions are identified and grouped based on common objectives and their relationship to each other:
|
Preprocessor Compiler Directive $IncludePreprocessors handle compiler directives that are written as comments in code. An example:
In C, implementation-specific values are defined in the C header file limits.h. Constants are also defined in a header file. Define an include (.inc) file that defines constants for return values. Include this file in the source code for both the module which calls a function and the module which services the function. This way, if the value changes, the changes will be automatically reflected in all using and consuming functions. The RobotSQA uses In pure Java, implementation-specific values are defined in .ini files. Constants are defined with the final modifier.
| OO and Java Development: Guidelines and Resources by Mark.Fussell at ChiMu.com.
|
Reserved Words
| VB.NET keywords:AddHandler AddressOf Alias And AndAlso Ansi As Assembly Auto ByRef ByVal Call Case CBool CByte CChar CDate CDec CInt CLng CObj CShort CSng CStr CType Date * Decimal * Declare Delegate Dim DirectCast Each Elseif End Enum Erase Error Event Exit Friend Get GetType Handles In Inherits Integer Is Lib Like Loop Me Mod Module MustInherit MustOverride MyBase MyClass Namespace Next Not Nothing NotInheritable NotOverridable Object On Option Optional Or OrElse Overloads Overrides ParamArray Preserve Property RaiseEvent ReadOnly ReDim Rem RemoveHandler Resume Select Set Shadows Shared Single Step Stop String Structure Sub SyncLock Then To Unicode Until When With WithEvents WriteOnly Xor With C#, a keyword can be used as a variable name by appending the "at" symbol @ in front of the name, such as @Xor. |
Programming Control Logic
Sequence structures, Selection structures: Repetition structures: | ComplexityMcCabe suggests that developers should keep each module's cyclomatic complexity number below 10. This numer defines the minimum number of tests to exercise a complete basis set of paths through the control flow graph of a single module. v(G) is calculated by adding up every decision in the module — 1 for each if and while statement, one for each edge and node. called predicates.August 1996 NIST Special Publication 500-235 by Arthur H. Watson and Thomas J. McCabe Javaprepare.com by Naveen Gabrani Data Structures & Algorithms in Java by Robert Lafore (Sams, 1998), 617 pages. Typically, 50% of the run time within a program is concentrated within only 4% of the code. —Knuth, D., "An Empirical Study of FORTRAN Programs," Software Practice and Experience, April-June 1971. |
Nested If-Else Statements
CIn C and Java there are several formats:
if studentGrade >= 60 {
"Passed" } else { "Failed" } Tertiary operator:
studentGrade >= 60 ? "Passed" : "Failed" A if-else-if ladder can be more efficient and easier to read than a case statement:
if(month == 12 || month == 1 || month == 2)
This is useful for logic based on strings and other objects, because Java case statements only handle numbers. Where ELSE IF is employed in C, PL/SQL uses ELSIF but standard PSM (Persistent Stored Modules) expects ELSEIF. If you need to add an item upon not finding it in a Hashtable, avoid two operations and use the get method to get the value within the if statement instead of a containskey method followed by a put.
if ( (md = (MyData)htable.get (keyCode) != null ){
Unix Shell ScriptsIn UNIX shells, if commands are ended with if spelled backward. Multiple branching is specified using "elif".echo "read word 1 \c" read word1 echo "read word 2 \c" read word2 if [[ test !-r file1 ]] echo "cannot open file1" else elif test "$word1" = "$word2" then echo "The words are the same" else echo "The words are not the same" fi A space is mandatory before and after each pair of double brackets used to access extended tests.
SAP ABAP IF/ELSE Conditional ProgramingRemember the periods (not commas):if expression1. ABAP statements. [elseif expression2. ABAP statements.] [else. ABAP statements.] endif.
|
|
Case/Switch Decision StatementsA common mistake is leaving out the break; statement. switch (inputChar) { case 'A': case 'a': System.out.println("\"" + args[0] + "\" for \"Apple\""); break; case 'B': case 'b': System.out.println("\"" + args[0] + "\" for \"Boy\""); break; case 'C': case 'c': System.out.println("\"" + args[0] + "\" for \"Cat\""); break; case 'D': case 'd': System.out.println("\"" + args[0] + "\" for \"Dog\""); break; default: System.out.println("\"" + args[0] + "\" - Whatever!"); break; } C and Java compilers are silent when it sees a “drop-through”, but the C# compiler issues an error. Use a consistent design throughout your application for handling the situation when the case value is not anticipated.
C#Unlike in Java, C, or C++, C# switch statements can have a string as its governing type, with a value of null is permitted as a case label constant.Case statements in UNIX shells use *) to signal the default and case spelled backwards. echo "Enter a, b, or c: \c" read sletter case $sletter in a|A) echo "You entered an a" ;; b|B) echo "You entered a b" ;; c|C) echo "You entered a c" ;; *) echo "You did not enter an a, b, or c" ;; esac
RubyRuby's range construct:answer = case age when 0..17 then puts "not adult" else puts "adult" end
SAP ABAP CASE Conditional ProgramingRemember the periods (not commas):case counter. when value1. ABAP statements. when value2. ABAP statements. endcase.
|
For Counter-Controlled RepetitionThis routine (a set of Java statements) steps through a series of values and performs some action based on whether each value meets some predefined criteria. This loop is performed 19 times because it starts from 1: int loopLimit = Interger.parseInt (args[0]); outer_loop: for (int i = 1 ; i <= loopLimit ; i++ ) { for(int j = 0; j < 20; j++) { // some code if( boolean_expression ) { continue outer_loop; } } } To leave a loop conditionally, PL/SQL uses EXIT, or EXIT WHEN(...). PSM uses LEAVE, and puts the leave-statement in an if-statement to exit conditionally. The generic syntax of a for loop using teritiary operators:
statements } The four basic elements involved in counter-controlled repetition:
The for loop exits when the condition in the middle (such as x <= loopLimit) is evaluated as false. One of the most common errors is the one-off error, typically caused by replacing <= with < in the condition portion of the for loop. C# provides the foreach statement to iterate through a collection without using multiple statements. This avoids the need to explicitly extracting each element from a collection. Best of all, foreach syntax is specific to the particular collection. foreach (int number in numbers) { Console.WriteLine(number); } An example using the ASP Fields Collection: For Each ofield in oRS.Fields Response.Write ofield.name Response.Write ofield.type NextIn UNIX shells, the index variable following the "for" is used to iterate from 0 through the list after keyword "in". for animal in dog cat rabbit iguana cow do echo "I see a "$animal done A space is mandatory before and after each pair of double brackets used to access extended tests. SAP ABAP Do Loop ProgramingRemember the periods (not commas):do n times. counter = counter + 1. if counter = 2. continue. "another loop pass. if counter = 3. exit. "terminate loop. if counter = 4. stop. "jump out to end-of-selection section. else. ABAP statements. enddo.
|
While LoopsA while loop in C may never be processed since it checks for exit condition before the code is executed. This is also why you should initialize when counters to 1 rather than zero. i = 1, j = 1; while (i <=loopLimit) { j = 1; while (j <= i) { System.out.print ("*"); j++; } System.out.println (" "); i++; }Use do loops for code that should be processed at least once, because checking is done after the embedded code is executed. class WhileTest { public static void main (String args[]) { int loopLimit = Integer.parseInt (args[0]); int i = 1; do { System.out.println ("The loop count is: " + i); i++; } while (i <=loopLimit); } } Did I mention that while loops check for its exit condition before the embedded code is executed? ;) A VBScript/ASP example of looping through a file until End Of File: Response.Write "<table>" Do while NOT oRS.EOF Response.Write "<tr><td>&" & oRS("LastName").Value & "nbsp;</td></tr>" oRS.MoveNext Loop Response.Write "</table>" oRS.Close Set oRS=Nothing In UNIX shells: num=0 while test $num -le 10 do echo $num let num=num+2 done echo "The value is " $num until false do commands done SAP ABAP While Loop ProgramingRemember the periods (not commas):Processing is terminated when the logical expression is false.
while counter < 10 ABAP statements. counter = counter + 1. endwhile.
|
Loops of Logic: Recursion: Factorials
For example, 5! (5 factorial) is the product of 5 * 4 * 3 * 2 * 1 “If the number is less than zero, reject it. If it isn't an integer, round it down to the next integer. If the number is zero or one, its factorial is one. If the number is larger than one, multiply it by the factorial of the next smaller number.” To calculate the factorial of any number that is larger than 1, you need to calculate the factorial of at least one other number. The function you use to do that is the function you're in the middle of already; the function must call itself for the next smaller number, before it can execute on the current number. function factorial(aNumber) { // If the number is not an integer, round it down: aNumber = Math.floor(aNumber); // If the number is less than zero, reject it: if (aNumber < 0) { return "not a defined quantity"; } // If the number is 0 or 1, its factorial is 1: if ((anumber == 0) || (anumber == 1)) { return 1; } // Otherwise, recurse until done: else return (anumber * factorial(anumber - 1)); } Recursion was used to create this artwork |
Stop It!
The destroy() method is invoked by the browser or applet viewer to notify the applet to release any resources it has used. The applet viewer or browser decides when this is necessary.
If you are running a Java program from a Console Window and
the cursor does not provide a system prompt after the program is done,
terminate the program by pressing
| . |
Precedence of Operators
Java operators behave slightly differently than in traditional programming languages. For example: d + (1/2) * d and d + d / 2 are not the same. When Java encounters “(1/2)” or an operation involving integer data types, it performs integer division and throws away (truncates) the remainder. To avoid this, specify “(1.0/2.0)” to force floating point division.
|
Assignment Operators
With y = x++; the value assigned to y is the original value of x.
|
Typecasting
An explicit cast is needed to convert a narrowing conversion to a datatype with less digits results in a loss of precision: This statements results in an explicit convertion before the arithmetic is performed:
Narrowing occurs with the transformation of a data type with a larger range and precision into a smaller data type, resulting in a loss of data.
Compile-time casting rules when transforming between a NewType and OldType:
|
Arithmetic Operators
One use for Modulus is to determine whether aNumber is odd or even: calculate aNumber modulus 2. A result of zero means aNumber is even.
|
Shift Operators
This is commonly done in control systems to align bits that are read from, or to be written to, I/O ports. Tricky programmers use it to efficiently perform integer multiplication or division by powers of two (doubling values). Shifting can be used with confidence in Java because the bit-level representation of all types is defined and platform-independent.
|
Comparative Operators
To compare the values referenced by two objects rather than the existance of the objects,
use the Boolean.equals() method
or the Where contains text operator is used by CGIFor server-side CGI scripts, the value of CONTENT_TYPE has changed from HTTP 1.0 value of
to the HTTP 1.1 value of:
So defensive programmers should avoid using an equal operator which expects a precise match to check for “application/x-www-form-urlencoded”. Programmers should instead check whether the value is included in the CONTENT_TYPE string. In Perl, the code is:
print " Here's your page back.\n"; } This script would work for Internet Explorer 5.0, Navigator 4.x, and Navigator 5.0 because it allows for the inclusion of a charset specification in the CONTENT_TYPE string. Bit-wise operator usage
With SQL 7, the IF statement below following is a bit-wise comparison:
CREATE TRIGGER trigMine
ON tableX
FOR UPDATE
AS
IF COLUMNS_UPDATED() & 14 <> 0 A bit mask value of 14 tests whether the 2nd or 3rd or 4th columns of tableX have been updated. (values 2 + 4 + 8 = 14). The bitmask to verify if columns 6, 8, or 11 was modified can be determined by the following: power(2,(6-1)) + power(2,(8-1)) + power(2,(11-1)) = 1184. To detect if any rows have been updated:
If (COLUMNS_UPDATED() & 1184) > 0
To verify that all the rows in question have been updated:
If (COLUMNS_UPDATED() & 1184) = 1184
Question: What bitwise operation was calculated if 5=0101 and 4=0100, return a result of 5? Answer: AND, XOR, or OR |
Logical Operators
For example: The b increment operation may not be performed if a is less than or equal to 0. if((a > 0) && (b++ < 1)) { // do something }
0 OR 0 produces 0. Any 1 produces 1.
|
Arithmetic Assignment Operators
|
Classification of Anomalies
Beizer (in his "Software Testing Techniques") and Copeland (in his "A Practitioners Guide to Software Test Design") in the "Technical Testing" field reference those in the "Software Engineering" field who use these annotations:
u = Used for something (=c and p)
p = Used in a predicate (or as control variable of loop) k = kill (deallocate) - = nothing These annotations are combined in time-sequence pairs to define anomalies (an illogical or useless sequence of data object state change) usually caught by compilers:
dk = Data defined and then killed without being used. kk = Killed twice. ku = Killed and then used. -k = variable not defined but killed -u = used before defined d- = defined but never used In compiler design dataflow analysis: |
Related:
| Your first name: Your family name: Your location (city, country): Your Email address: |
Top of Page
Thank you! |