Chapter5 - Program Design and Efficiency - Tobeupdated
Chapter5 - Program Design and Efficiency - Tobeupdated
© HĐC 2024.1
Program design and efficiency
“Designing object-oriented software is hard, and designing
reusable object-oriented software is even harder...It takes a
long time for novices to learn what object-oriented design is
all about. Experienced designers evidently know something
inexperienced ones don't...
One thing expert designers know not to do is solve every
problem from first principles. Rather, they reuse solutions
that have worked for them in the past. When they find a
good solution, they use it again and again. Such experience
is part of what makes them experts. Consequently, you'll
find recurring patterns of classes and communicating
objects in many object-oriented systems. These patterns
solve specific design problems and make object-oriented
design more flexible, elegant, and ultimately reusable...”
Erich Gamma et. al.: Design Patterns: Elements of Reusable
Object-Oriented Software, Addison-Wesley, 1995.
Requirements:
what are the main objectives of the program
requirements must be clear but do not need to be detailed
Technical specifications: describe specifications of the
program in details
E.g.: format, response of the program, memory constraint
Technical specifications can be extended subsequently as
the program is developed
START
statements
statements
conditional
FALSE
TRUE
statements
END
Requirements:
Enable user to play tic-tac-toe game with computer (placing X
and O)
Allow user to choose if they want to play first or computer
starts first
Ask if user wants to play again once the game finishes
Welcome message:
Welcome to TIC-TAC-TOE.
-----------------------
1|2|3
-----
4|5|6
-----
7|8|9
Efficient Programs
Selecting the algorithm
Developer should use the best applicable algorithm
Then considering the efficiency of the code
E.g.: Calculating the summation of n continuous integer
starting at m
void main() { void main()
long n,m,i , sum ; {
cout << ‘ Enter n ‘ ; cin << n; long n,m , sum ;
cout << ‘ Enter m ‘ ; cin << m; cout << ‘ Enter n ‘ ; cin << n;
sum =0; cout << ‘ Enter m ‘ ; cin << m;
for(i = m ; i < = m+n; i++) sum =(m + m+ n) * n / 2;
sum += i; cout << ‘ Sum = ‘ <<sum;
cout << ‘ Sum = ‘ <<sum; }
}
Before
float f()
{ double value = sin(0.25);
//
…..
}
After
double defaultValue = sin(0.25);
float f()
{ double value =
defaultValue;
//
…..
}
for (i = 1; i<=10;i++)
x += strlen(str);
Y = 15 + strlen(str);
len = strlen(str);
for (i = 1;i<=10;i++)
x += len;
Y = 15 + len;
M = sin(d);
for (i =0; i<100;i++)
plot(i, i*M);
x99 sigmoid(x99)
X0 is known
Compute Delta = X1-X0
Comput Xmax = X0 + N * Delta;
With a given X
Compute i = (X – X0)/Delta;
o Which needs a substation of two real numbers and a division of real
numbers
Compute sigmoid(x)
o Which needs a multiplication of floats and a addition of floats
Code Simplification
Most of the programs which can run fast are simple. Thus,
developer should simplify the source code to make it run fast.
Problem Simplification
To improve the program efficiency, the developer should
simplify the problem to solve
Relentless Suspicion
One should question the necessary of each code block and each
field/property in data structure
Early Binding
Carry out the task immediately to avoid redoing multiple times
later
found = FALSE;
for(i=0;i<10000;i++) {
if( list[i] == -99 ) {
found = TRUE;
}
}
if( found ) printf("Yes, there is a -
99. !\n");
int main(void)
/* Read a circle's radius from stdin, and compute and write its
diameter and circumference to stdout. Return 0 if successful. */
{
const double PI = 3.14159;
int radius;
int diam;
double circum;
Name
Letters, digits and underscore (_)
Cannot start with a digit
Cannot be C/C++ keywords such as double, return
Differentiate UPPERCASE and lowercase text
VAR, Var, var, vAr are treated differently
It is valid to use all uppercase letters
However, all uppercase text are used in #define statement (will
be discussed) conventionally
Precious material
Microsoft Excel has more than 65.000 variables
How long should the name be?
m
mph
miles_per_hour
average_miles_per_hour_that_the_car_went
Yes: y = x;
x = x + 1;
Attention!
yes UPPER CASE
yes ( )
/*************************************************
Explanation at
* Program: Mi_To_Km
the beginning
* Purpose: Miles to kilometers conversion
of the code
* Author: A. Hacker, 1/18/00 Section AF (Turing)
*************************************************/
A program is a document:
Computer read it partially
Human read it completely
Donald Knuth: “literate programming”
Programming style is a term useful to developers and
related to:
Comments, spaces, indentation, name
Understandable, straightforward, elegant code
Code quality
#include <stdio.h>
/* conversion constants. */
#define FEET_PER_MILE 5280.0
#define SECONDS_PER_HOUR (60.0 * 60.0)
int main(void)
{
double miles_per_hour; /* input mph */
double feet_per_second; /* corresponding feet/sec */
double feet_per_hour; /* corresponding feet/hr */
return(0);
}
#include<stdio.h>
int main(void){double v1,v2,v3,v4,v5;pr\
intf(“Enter a number of miles per hour:\
”);scanf(“%lf”,&v1);v5=v1*14.6666667;pr\
intf(“%f miles per hour is equal to %f \
feet per second.\n”,v1,v5);return(0);}
Prototype:
int fprintf ( FILE * stream,
const char * format, ... );
Return Value:
On success, the total number of characters written is returned.
If a writing error occurs, the error indicator (ferror) is set
and a negative number is returned.
If a multibyte character encoding error occurs while writing
wide characters, errno is set to EILSEQ and a negative
number is returned.
errno is a macro of type int indicating “Last error
number”
int main () {
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL) {
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
} else {
fclose (pf);
}
return 0;
}
// first implementation
#include <iostream>
int Receive(int input, std::string& output) {
if (input < 0) {
return -1;
}
output = "Hello";
return 0;
}
// second implementation
#include <iostream>
std::string Receive(int input, int& error) {
if (input < 0) {
error = -1;
return "";
}
error = 0;
return "Hello";
}
int main() {
std::cout << "Input: -1" <<
std::endl;
Test(-1);
std::cout << "Input: 1" << std::endl;
Test(1);
return 0;
}
try {
// Block of code to try
throw exception; // Throw an
exception when a problem arise
}
catch () {
// Block of code to handle errors
}
try {
int age = 15;
if (age > 18) {
cout << "Access granted - you are old enough.";
} else {
throw 505;
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Error number: " << myNum;
}
class Device
{
int fd;
public:
Device(const std::string &deviceName) {
fd = open(deviceName.c_str(), O_RDWR);
if (fd < 0) {
throw std::system_error(errno, std::system_category(),
"Failed to open device file");
}
}
~Device() {
close(fd);
}
// continue in next slide …