Transcript Document

Best Practices
Chapter 6 - Programming
Agenda











Introduction
Fundamental Principles and Practices
Think About the Code You Write
Duplicating Knowledge
Orthogonality
Flexibility and Adaptability
Programming Defensively
Creating Classes
Creating Routines
Using Variables, Types and Constants
Naming Program Elements
2
Agenda (cont)











Guidelines for Writing Code
Using Selection and Iteration
Commenting Your Code
Managing Resources
Refactoring Code
Improving Program Performance
Collaborative Construction
Performing Integration
Using Source Code Control
Using Good Tools
Conclusion
3
Introduction


Third phase in the SDLC (“developing the software”) 
programming
Involves several key activities:
1.
2.
3.
4.
5.
6.
7.

Defining the problem
Detailed design
Coding
Debugging and unit testing
Integration
Integration testing
Updating documentation
Activities  carried out in sequence
4
Introduction (cont)

Incremental integration approach favored over the
phased integration approach

Phased integration  Problem: when the parts are put
together for the first time, new problems inevitably
arise all at once, and the causes could be anywhere

Avoid phased integration for anything except tiny
programs
5
Introduction (cont)

A detailed look at the third phase
(construction phase)

Defining the Problem



Specify program objectives i.e. define the problem to
be solved
The program inputs, outputs and processing are
specified
Document everything that is defined or specified
6
Introduction (cont)

A detailed look at the third phase
(construction phase) (cont)

Detailed Design



Determine program structure and logic, and testing
design  walkthrough
Use pseudocode to design your code
Pseudcode is an English-like description of the
actions to be performed by code
7
Introduction (cont)

A detailed look at the third phase
(construction phase) (cont)

Coding


Design logic translated into desired high-level
programming language
Create a skeleton:





declare variables
write functions (just declaration and error handling)
create the user interface
write calls to the various functions
Then go and fill in coding details, one function at a time
8
Introduction (cont)

A detailed look at the third phase
(construction phase) (cont)

Debugging and Unit Testing



Check for errors and debug to remove errors
Use desk-checking to detect errors
Desk checking: reading through code to make sure it
is free of errors and that the logic works
9
Introduction (cont)

A detailed look at the third phase
(construction phase) (cont)

Integration


Integrate the code into the part of the system that
been completed so far
Integration Testing

Test to ensure that integrated code works properly as
part of the system
10
Introduction (cont)

A detailed look at the third phase
(construction phase) (cont)

Updating Documentation



Writing a description of the program’s purpose and
process, and also how to use it
Prepared for people who use the program in the future
Writing documentation is not an end-stage process of
programming  carried out during all programming
steps
11
Introduction (cont)

Some specific tasks involved in programming:
 Verifying that the groundwork has been laid so that construction
can proceed successfully
 Determining how code will be tested
 Designing and writing classes and routines
 Creating and naming variables and named constants
 Selecting control structures and organizing blocks of statements
 Unit testing, integration testing, and debugging code
 Reviewing other team members’ low-level designs and code and
having them review yours
 Polishing code by carefully formatting and commenting it
 Integrating software components that were created separately
 Tuning code to make it faster and use fewer resources
12
Fundamental Principles and
Practices

Read the language documentation:
 Object-oriented languages have a vast object
hierarchy that needs to be understood. NB to not
misuse classes or “re-inventing the wheel”

Understand the collection of procedures and functions
offered by the language in use  will execute faster
than “equivalent” programmer-defined procedures and
functions
13
Fundamental Principles and
Practices (cont)

Strive to produce code of high quality:
 Apply quality checks: E.G.  strive for completeness
(code satisfies all requirements) and for correctness
(code is error-free)

Don’t “leave it for later”:
 Do commenting, code formatting, and error handling
while writing code
 This makes it less tedious than “cleaning up”
thousands of lines of code later
14
Fundamental Principles and
Practices (cont)

Strive to reduce complexity:


When writing code, ask whether code could be
simplified.
Concern yourself with aesthetics:

Code should be neat and pleasing to the eye so
that it is easy to read, absorb and understand
15
Fundamental Principles and
Practices (cont)

Do the planning:

Careful planning is crucial. Remember:






Determine how much design will be done before coding begins and how much
will be done during coding
Before coding commences, decide what coding standards and conventions for
names, comments, layouts, etc … will be adhered to
Decide what specific practices will be followed with regards to error handling,
security, class interfaces, code reuse and performance. E.G.  not deciding
on an error-handling strategy from the outset can be problematic, it is difficult
to add error handling after a program has been implemented
Determine whether programmers will work in teams, individually, or both
Decide what steps must be followed to integrate code submitted by multiple
teams or individuals
Determine how quality assurance requirements will be met. E.G.  decide
whether programmers will review or inspect each other’s code, and what types
of testing will be conducted
16
Fundamental Principles and
Practices (cont)

Design carefully:
 Plan code before writing it
 Most program “bugs” can be traced back to poor planning and
poor design.
 Do not hack code together by writing a portion quickly and then
having to modify it repeatedly until it produces the desired effect

Decide how many forms are needed and the content of those forms,
what code should be in events and what should be in code modules,
the scope of variables, what methods and algorithms you will use,
etc…

Use pseudocode and drawings, to plan code. NB for large, complex
projects where a lack of planning can cause confusion and serious
errors
17
Fundamental Principles and
Practices (cont)

Make appropriate technology choices:


E.G: Determine the system architecture or part thereof, choose
programming languages, and choose a suitable database
management system
Detect and rectify faults and potential problems early:


Evaluate and critically analyze each segment of code as soon as
you complete it
Look out for warning signs:






tricky code
an error-prone code segment
a lengthy routine
low cohesion
inability to reuse code
Warning signs indicate that code should be reworked or rewritten if
possible
18
Fundamental Principles and
Practices (cont)

Ensure that specifications are met:
 Strive for correctness. Ensure code meets formal
specifications and requirements of the user

Simplify the deployment, configuration,
administration and maintenance task

Take security and data protection seriously:
 Code must meet security and data protection
requirements  protection from unauthorized access,
damage or loss of data, etc…
19
Fundamental Principles and
Practices (cont)

Design and build orthogonal systems:




Design and build flexible, adaptable systems:



Two or more things are orthogonal if changes to one does not affect any of
the others (they exhibit independence or decoupling)
E.G.  a well-designed system allows the user interface to be changed
without affecting the database
Orthogonal systems are easier to design, build, test and extend
Requirements, users and technologies change, often having an impact on
the software being developed
Decisions are never cast in stone  make it flexible enough to adapt to
changing decisions
Design and build for interoperability:

Code needs to interoperate well with the existing and future parts of a
solution
20
Fundamental Principles and
Practices (cont)

Design and build scalable solutions when
necessary:


A scalable application: able to cope with an increased load
without requiring extensive modification (just add additional
resources)
Design and build systems that are changeable
and long living:



Organize the internal details of an application so future
changes can be made easily and quickly
Give adequate thought to which features may change and
write code so changes can be made with little effort
Saves time and money (and make users happier)
21
Fundamental Principles and
Practices (cont)

Design and build robust systems and
reliable systems that work correctly

Design and build systems with suitable
performance and response times:

Performance benefits might seem insignificant,
but a constant focus on performance can lead to
significant performance enhancements
22
Fundamental Principles and
Practices (cont)

Build well-written and understandable systems:

Standard tools, techniques and best practices should be used:










informative naming,
modularity,
indenting,
testing and documenting assumptions,
using white space,
strong cohesion,
weak coupling,
proper commenting.
Saves time, money and effort ITO system maintenance
Strive to create self-documenting code:


Well-written code should not need many comments
Techniques for producing self-documenting code: using good program
structure, using good names for program elements, laying out code well, and
minimizing complexity
23
Fundamental Principles and
Practices (cont)

Code for ease of readability:
 Code layout should visually and consistently
communicate the structure of the code to the reader
 Readability has a positive effect on other aspects of a
program:






Reviewability
Error rate
Debugging
Modifiability
Development time – a consequence of all of the above
External quality – a consequence of all of the above
24
Fundamental Principles and
Practices (cont)

Write code that is easy to use:
 Think carefully about how code will be used by other
code and how its use can be made as simple as
possible

Create uncomplicated interfaces:
 E.G.  functions, components and services

Don’t duplicate
25
Fundamental Principles and
Practices (cont)

Code for reuse

Avoid rework by reusing code

Take advantage of features that help to reduce
errors:

E.G.  in Visual Basic it is useful to:
1. Create and name the important controls before working
on event procedures
2. Type constant definition statements and variable
declaration statements before typing other code
3. Type the remaining statements in lowercase letters
26
Fundamental Principles and
Practices (cont)

Seek proven ways of doing things:



Use good tools:


Guidelines, best practices, design patterns etc … saves time and effort
E.G  design patterns can simplify software development and help to create
efficient, maintainable and extensible systems easily
The better your tools, and the better you know how to use them, the more
productive you can be
Use automation:


Automate manual, repetitive and mundane tasks to ensure consistency and
repeatability
E.G.  schedule backups to run automatically at night, schedule nightly
compiles, carry out automatic regression testing, create shell scripts to
automatically perform administrative tasks, automatically generate
documentation and publish it on a Web site, etc …
27
Fundamental Principles and
Practices (cont)

Have a backup plan:


Take steps to safeguard work against disk failure,
accidental deletion, sabotage, theft, natural disasters etc…
Devise a backup plan  make backup copies of work
periodically and transferring them off site. Also:
 Test backup plans by doing a “restore” to make sure that
everything you need is correctly restored
 When you finish a project, make a project archive 
includes everything needed to re-create or modify the
product later
28
Actively Think About the Code
You Write

Hunt & Thomas (2000) offer suggestions:

Always be aware of what you are doing

Don’ t code blindfolded. Understand the code you are writing and the technologies you
are using

Proceed from a plan, whether it is in your head or on a printout stuck on the wall

Rely only on reliable things. Don’ t depend on accidents or assumptions

Document your assumptions and test them

Prioritize your effort by spending time on the important aspects such as the
fundamentals and infrastructure, rather than the bells and whistles

Be ready to refactor if you find existing code constrains your efforts
29
Duplicating Knowledge

Duplication of knowledge can be categorized into
various categories:





Imposed duplication
Inadvertent duplication
Impatient duplication
Interdeveloper duplication
Question: How can such problems of duplication be
addressed?
30
Duplicating Knowledge (cont)

Ways to reduce imposed duplication

Multiple representations of information in code:
 A client-server application may require a shared structure to
be represented on both the client and the server, or might
need a class whose attributes mirror the schema of a
database table
 E.G.  structures in multiple languages can be built from a
common metadata representation using a simple code
generator each time the software is built
 Class definitions can be generated automatically from the
online database schema, or from the metadata used to
build the schema
 The process must be active – it cannot be a one-time
conversion, otherwise you are still duplicating information
31
Duplicating Knowledge (cont)

Ways to reduce imposed duplication (cont)

Documentation in code:
 Always provide comments in your code, but don’ t repeat
the information represented by the code otherwise every
change will necessitate a change to both code and
comments
 Keep the low-level knowledge in the code, and use
comments for high-level explanations

Documentation and code:
 Documentation and code contain representations of the
same knowledge
 Any change to the code should be reflected in the
documentation too, without delay
32
Duplicating Knowledge (cont)

Ways to reduce imposed duplication (cont)

Language issues:



Some languages impose duplication in their source
code
E.G.  duplicating interface information between a
module’s interface and its implementation. There is no
easy way to overcome such duplication
Many development environments are able to detect
and report most language based mismatches (E.G. 
a header file that disagrees with its implementation)
33
Duplicating Knowledge (cont)

Ways to Reduce Inadvertent Duplication

Mistakes in a system’s design can lead to duplication.
Imagine a class that represents a line, and that has certain
properties that need to be set by the developer:





Start coordinate
End coordinate
Length
A line will always have a start, end, and length (even if the
length is zero).
Is this a good representation?  NO! because length
should be calculated automatically from the start and end
coordinates, and hence should be a read-only property
34
Duplicating Knowledge (cont)

Ways to Reduce Impatient Duplication


Time pressures can cause us to take shortcuts
(E.G.  quickly copying some old code and
tweaking it slightly)
E.G.  the Y2K problem - Many of the issues
involved were caused by the laziness of
developers not allowing for the full year to be
stored or acquired
35
Duplicating Knowledge (cont)

Ways to Reduce Interdeveloper Duplication

Several techniques can address such problems:

At the high level: Have a clear design, a strong technical project
leader, and a well-understood division of responsibilities within the
design

At the module level: Engage in active and frequent communication
with other developers. Participate in forums to discuss common
problems

Store source and documentation in a central place: A team
member appointed as the project librarian can control this. Read
other people’s source code and documentation. This makes it easier
to reuse existing work
36
Orthogonality

An orthogonal system is one where its
components are highly independent

When components are highly interdependent,
one change can have many repercussions.

There are several techniques that can be
used to maintain orthogonality when coding:
37
Orthogonality (cont)

Use libraries and toolkits that preserve
orthogonality:

Ask  Will the toolkit or library impose changes
that should not be there? E.G.  if it requires you
to create or access objects in a special way then
orthogonality will suffer

Keeping such details isolated from your code also
allows you to change vendors easily. This could
be achieved by requiring additional information to
be expressed as metadata, outside the code
38
Orthogonality (cont)

Keep your code decoupled:



Avoid global data:


Write modules that don’t reveal anything unnecessary to
other modules and that don’t rely on the implementation of
other modules
If you need to change an object’s state, get the object to do
it for you
Explicitly pass any required context into your modules as
parameters.
Avoid similar functions:

Don’t code functions that contain similar code
39
Orthogonality (cont)

Be cautious of relying on language defaults in your code.

E.G.  an object in a library might apply certain defaults for
properties if the programmer does not explicitly set values for
them  creates an implicit assumption in your code

This reduces clarity and increases coupling. If the authors of the
object decide to change the default property values in the new
version of the library, your code might fail.

Failure might occur suddenly or it might occur gradually over time
in the form of data corruption
40
Flexibility and Adaptability


Changes in requirements, users, technologies, etc…
can have an impact on software being developed
Suggestions to help build flexible systems:


Write code to handle small or large changes by using
abstraction to hide implementation details
This hides third-party products behind a well-defined,
abstract interface, and can be changed with minimal
impact to the rest of the system
41
Flexibility and Adaptability
(cont)

Follow the “don’t duplicate” principle

Make sure systems are orthogonal. Organize code into
modules and limit the interaction between  easy change
or replacement
 Minimize coupling
 When we ask an object to perform a service it should not
give us a secondary object that we have to deal with to get
the required service
42
Flexibility and Adaptability
(cont)

Ask how difficult it will be to support other versions of the
operating system that is to support the system

Make applications highly configurable.
 Building systems to support different architectures (E.G. 
stand-alone or client-server), database products, business rules,
user interface styles, etc … simply by changing a configuration
file.
 Create dynamic and adaptable programs  program the general
case and put specifics outside the compiled application.
 Configuration data (metadata), can be stored in an XML file or
the system registry
43
Flexibility and Adaptability
(cont)


The Law of Demeter for functions helps minimize coupling between
modules by preventing you from reaching into an object to access a
third object’s methods
The law states (Hunt & Thomas, 2000):
44
Flexibility and Adaptability
(cont)

Following this law, objects must delegate and
manage any and all secondary objects directly

Consider the cost for flexibility and adaptability
 weigh the pros and cons

There might be room for deviation from the law
for a good reason E.G.  for performance
issues
45
Programming Defensively

Is about producing robust code able to deal with error conditions,
bad data, etc … without crashing

Check for Invalid Input


Check all data received from external sources, such as a file or a
user, to ensure its validity
Examples of invalid data:




Data that is out of range (E.G.  test score of 120 where min = 0 and
max = 100)
Data that is not valid for its purpose (E.G.  a blank ID number)
Data containing a check digit that does not match the check digit
calculated to validate the data
Data that causes a breach of security E.G.  data that causes
overflows or contains hidden commands or code that could become a
security risk when processed
46
Programming Defensively
(cont)

Check arguments passed to routines to ensure the
values they contain are valid
Checking input data = overhead  increases coding
time, code length, processing time and complexity
but necessary in the long term

Check All Assumptions


E.G.  is a file extension three characters long at a
maximum? Or, can there only be one period in a filename?
 True for FAT but not for NTFS
47
Programming Defensively
(cont)

Handle Error Conditions and Bad Data

How to handle error conditions and bad data:

Return a neutral value: E.G.  zero or an empty string.

Substitute the next piece of valid data: E.G.  an invalid data
record, could be skipped.

Return the same answer as the previous time: The previously
read data could be used instead of the invalid data

Substitute the closest legal value

Log a warning message to a file

Return an error code: or exception error could be thrown
48
Programming Defensively
(cont)

Handle Error Conditions and Bad Data


Call an error-processing routine/object

Display an error message wherever the error is
encountered

Handle the error in whatever way works best locally

Shut down
Decide the approach before coding and be consistent
49
Programming Defensively
(cont)

Throwing and Handling Exceptions
 Used to notify other parts of a program about unexpected
conditions
 Are thrown only for exceptional conditions
 All other error conditions should be handled locally by normal
coding practices (returning an error code, logging the error, or
shutting down)
 Exceptions crash programs unless an exception handler exists
 Handlers allow a program to crash gracefully  allowing for
unsaved data to be saved, open files to be closed, etc…
50
Programming Defensively
(cont)

Throwing and Handling Exceptions (cont)
 Hunt & Thomas (2000) recommend that exception handling be
reserved for unexpected events

Ask “Will this code still run if I remove all the exception
handlers?” If “no” then exceptions are being used in nonexceptional circumstances

E.G.  Opening a file for reading and the file does not exist


If the file should exist  an exception error is warranted
If uncertain whether the file exists  not exceptional
51
Programming Defensively
(cont)

Throwing and Handling Exceptions (cont)

The Visual Basic code example below uses Try and Catch
blocks to catch division by zero as an exception:
52
Programming Defensively
(cont)

Throwing and Handling Exceptions (cont)

The Try/Catch block surrounds the code that can
potentially generate an exception

Or use an If statement instead to check whether Bottom is
not zero:
53
Programming Defensively
(cont)

Throwing and Handling Exceptions (cont)


Sometimes useful to raise (or throw) an exception manually and handle
it by exception-handling code
In Visual Basic, the Throw statement is used to throw an exception:
54
Programming Defensively
(cont)

Throwing and Handling Exceptions (cont)


Creating a centralized exception reporter procedure that can be
called from Catch blocks. The procedure (e.g. ReportException),
displays a message box detailing the exception error
Bear the following in mind when using exceptions:
 Always order exceptions in Catch blocks from the most specific
to the least specific

Include a localized description string  message the user sees.
Must clarify the cause and location of the exception and must
indicate how the user should respond (E.G.  call or email the
developer or support personnel)
55
Creating Classes

Reasons for creating classes:



To model real-world objects
To model abstract objects E.G.  Shape object
To reduce complexity  by hiding internal workings.
This also improves maintainability
56
Creating Classes (cont)

To isolate complexity

To hide implementation details

To limit effects of changes  by isolating areas that are likely to change

To hide global data

To streamline parameter passing

To make central points of control

To facilitate reusable code

To package related operations  trig functions, string-manipulation routines
and graphics routines
57
Creating Classes (cont)

Guidelines for designing and creating classes:
 Ensure that each class has a central purpose
 Create good class interfaces  must exhibit good abstraction
that hides the class’s details and shows that all its methods and
properties belong together
 Make usage as obvious as possible




Minimize accessibility  strictest level of privacy
Don’t expose member data in the public interface:
Member data should be private
Hide implementation details
Avoid tight coupling  should be as independent as possible
and should collaborate with other classes only when necessary
58
Creating Classes (cont)


E.G. of a badly designed class:
Why?
59
Creating Classes (cont)

A better solution:
60
Creating Classes (cont)

Steps for Creating Classes
1.
Design the class:






What private data the class will hold
What the class’s responsibilities will be
What methods and properties the class will have
Structural issues, whether the class will contain other classes and whether it will be
derived from another class
The class’s interface – one that presents convenient abstraction
2.
Write the code for the class: Create the data members, properties, and routines
3.
Review and test the class: Make sure it has been designed and built satisfactorily
These steps should be carried out iteratively until you are happy with the
outcome
61
Creating Routines

Reasons for creating routines:











To reduce complexity  use it repeatedly without having to think about its
details
To offer abstraction
To avoid duplicate code
To isolate non-portable code: Non-portable capabilities can be placed in
separate routines thereby identifying and isolating non-portable code
To facilitate performance improvements: Having code in one place
makes it practical to refactor the routine to improve its performance
To isolate complexity
To hide implementation details
To limit effects of changes
To hide global data
To make central points of control
To facilitate reusable code
62
Creating Routines (cont)

Writing Pseudocode



Carefully design the routine according to the requirements
Use pseudocode to concentrate on the logic
E.G.  pseudocode for performing a linear search of an array:
63
Creating Routines (cont)

Guidelines for using pseudocode:

Use clear English-like statements

Avoid syntactic elements from the programming language

Show what the code should do, not how it will do it

Write pseudocode at a low enough level that generating
code from it will be nearly automatic
64
Creating Routines (cont)

E.G. of pseudocode that violates these
guidelines:
65
Creating Routines (cont)

A better design:

Pseudocode can become actual comments in a program, thereby clearly
describing the intent of the code
66
Creating Routines (cont)
Steps for Creating Routines

1.
2.
3.
4.
5.
Design the Routine
Check the Design
Code the Routine
Review and Test the Code
Conduct a Final Quality Check
67
Creating Routines (cont)
Steps for Creating Routines (cont)

Design the Routine

Describe the routine: Short, concise description of the
purpose of the routine and define:





Inputs to the routine.
Outputs from the routine.
Preconditions guaranteed true before the routine executes (input
values within certain ranges, files open or closed, etc…)
Postconditions guaranteed true after the routine executes (output
values within certain ranges, files open or closed, etc…)

Give it a name

Write the pseudocode
68
Creating Routines (cont)

Steps for Creating Routines (cont)

Iterate through multiple designs until you find the best one.
Always try to reuse code (and design for reuse).

Check whether the desired functionality is already available in a
library that could be used instead of or as part of the routine

When designing routines remember:

How you will test the routine

What error handling will be necessary

Whether the routine will meet the required performance goals
69
Creating Routines (cont)

Steps for Creating Routines (cont)

Check the Design


Check your design, i.e. pseudocode, or get someone else to check it
Code the Routine

Write the routine’s declaration and add its description

The table describes information that should appear inside a routine’s header:

.
70
Creating Routines (cont)

Steps for Creating Routines (cont)

Code the Routine (cont)

Add the pseudocode as comments

Add code for each comment

Refactor the code, if necessary
71
Creating Routines (cont)

Steps for Creating Routines (cont)

Code example showing pseudocode statements transformed into C++
comments:
72
Creating Routines (cont)

Steps for Creating Routines (cont)
 Review and Test the Code
 Check the routine for errors: Desk checking, peer reviews,
walkthroughs or one or more other techniques


Compile the routine

Test the routine: Use the debugger to make sure the code
executes as expected. Then use test cases, testing code, or other
testing techniques

Remove all errors
Conduct a Final Quality Check
73
Creating Routines (cont)

Guidelines for Creating Routines

Aim for strong cohesion: A routine in which all its operations are
strongly related is said to be strongly cohesive

Aim for loose coupling: Routines should be independent to other
routines

Use procedures and functions appropriately:

Define a function when the end result of the processing task is a single value,
use a procedure in other cases

Functions should not do any input or output processing

For functions, make sure a return value is actually returned for all possible
paths through the function. Initialize the return value to a default value. For
procedures ensure that return values are returned for all output parameters
74
Creating Routines (cont)

Guidelines for Creating Routines (cont)

Separate query operations from modification operations:



Avoid unnecessary proliferation of procedures, functions and classes:



Query operations should normally not modify state
If an operation GetBalance() changes the state of a program or an object,
separate the query functionality from the modification functionality by providing
two separate routines
Having too few of these elements might be an indication that they have too
much functionality
Maintain a good balance by not creating too few or too many of these
elements, at the same time being careful not to violate good guidelines and
practices
Combine similar routines:


Consider combining similar routines that offer the same functionality but differ
only by a constant value used inside the routine
The constant value could then be passed to the new routine as a parameter
75
Creating Routines (cont)

Guidelines for Creating Routines (cont)
 Use meaningful names:

Name describes precisely what the routine does. E.G. 
CalculateAmtOwing and NOT HandleInput and PerformTask

Keep names shorter than 20 characters

For a function, the name should describe the function’s return value

For procedures, the name should use a verb followed by an object,
E.G.  PrintDocument. For methods of an object, the name of the
object should be excluded as it will be included in the method call,
E.G.  Document.Print.
76
Creating Routines (cont)

Guidelines for Creating Routines (cont)

Use consistent names:


E.G.  do not use CalcAmtOwing for one procedure
and CalculateTax for another
Use opposite pairs precisely and use them
consistently, such as Add and Remove, Show and
Hide and Next and Previous
77
Creating Routines (cont)

Guidelines for Creating Routines (cont)

Simplify routine interfaces:









List parameters in input, modify, and output order. Place status or error variables last
Use consistent ordering for similar parameters. E.G. if two similar routines use the
same or similar parameters, keep the order of the parameters as similar as possible.
Use meaningful names for parameters and use comments to clarify parameters where
meaning, input requirements, or resultant values are not obvious.
Don’ t use routine parameters as working variables. Instead, assign the parameters to
new local working variables and modify them as necessary.
Remove parameters that serve no purpose or are not used.
Pass only data that makes sense to the routine’s purpose and the abstraction it presents.
When you need to pass several values from the same object into a routine, consider
passing the whole object instead.
Avoid passing an entire object as a parameter if only a few values from the object will be
used in the routine. Instead, define parameters for the specific fields required in the
routine.
Ensure that the data types of the arguments passed to a routine match up with the
corresponding data types of the routine’s parameters
78
Creating Routines (cont)

Guidelines for Creating Routines (cont)
 Do not use reference parameters unnecessarily:

When changes to a parameter value within a procedure do not
have to change the value stored in the variable passed to it,
the argument should be passed to the parameter by value.

For functions, all parameters should be passed by value

In cases where a large amount of data needs to be passed
there might be good reason to pass by reference
79
Passing by Value

“By Value” parameters retain their original
value after Sub procedure terminates
80
Passing by Reference

"By Reference" parameters can be changed
by the Sub procedure and retain the new
value after the Sub procedure terminates
81
Creating Routines (cont)

Guidelines for Creating Routines (cont)
 Check routine parameter values

Avoid long routines: Avoid writing routines longer than 200
lines of code to keep them understandable

Avoid forcing a routine to exit: Routines should have one entry
point and one exit point. Avoid forcing a routine to exit partway
through unless you have a good reason to and that it will improve
readability
82
Using Variables, Types and
Constants (cont)

Variables

Store data
 Has a data type and name
Guidelines for using variables


Explicitly declare all variables:
 Not always necessary but its easy to misspell  introduces
hard-to-find bugs
 In Visual Basic, use Option Explicit to enforce variable
declaration
83
Using Variables, Types and
Constants (cont)

Guidelines for using variables (cont)

Minimize the scope of variables:
 No larger than necessary  make code more manageable
 Favour local variables over global variables
 Global variables can make application logic difficult to
understand and make code reuse and maintenance more
difficult

Minimize the lifetime of variables:
 E.G.  a database connection
84
Using Variables, Types and
Constants (cont)

Guidelines for using variables (cont)

Use each variable for one purpose only:
 A “temp” variable used in multiple places in code for varied
purposes reduces readability
 Storing values that have different meanings in a variable
also violates this guideline E.G.  a positive employee
number for a permanent employee and a negative
employee number for a temporary employee
85
Using Variables, Types and
Constants (cont)

Guidelines for using variables (cont)

Choose the correct data type for a variable:

Never choose a data type that wastes memory E.G. , declaring a
variable that stores an integer value up to 32,767 when it will never
hold a value larger than 203

Avoid overflow errors  occur when the result of an expression is too
large to be stored in a variable.

The speed of arithmetic calculations differs for different numeric
data types

When a variable will be used to store money values, avoid round-off
errors by choosing an appropriate data type. E.G.  in Visual Basic,
the Decimal data type stores money values
86
Using Variables, Types and
Constants (cont)

Guidelines for using variables (cont)
 Group variable declarations together:


Above program code, but after the constant definition statements
Separate groups of related declarations:

Place a blank line before and after each group of related declarations

Remove variables that are not used

Initialize variables and array elements:


E.G.  an accumulator should be initialised immediately before the
loop that performs the accumulation
Re-initialize counters and accumulators if they are used more than
once
87
Using Variables, Types and
Constants (cont)

Guidelines for using variables (cont)

Keep references to the same variable close together:
 Helps reduce the chance that the variable’s value might be
changed inadvertently when new code is added
 Improves readability  user’s focus restricted to a smaller
segment of the program at a time
 Minimize the number of statements between the first
reference and the last reference of a variable
88
Using Variables, Types and
Constants (cont)

Guidelines for using variables (cont)


Keep references to the same variable close together (cont):
Simple code segment:
a = 10
b=4
a=a+1
c = 2 * 12
d = 15
e=a*c
f=b*2

The statements do not adhere to this guideline. Reorder as follows:
b=4
f=b*2
a = 10
a=a+1
c = 2 * 12
e=a*c
d = 15
89
Using Variables, Types and
Constants (cont)

Guidelines for using variables (cont)
 Check the validity of variable values:


E.G.  within the correct range
Do not perform arithmetic operations on string values:


Avoid using control properties in arithmetic expressions. E.G. 
Label controls used to display values, not to hold values used in
calculations. Numbers should be stored in numeric variables and be
used in arithmetic calculations as needed
Convert strings to numbers before performing arithmetic operations
on them
90
Using Variables, Types and
Constants (cont)

Guidelines for using variables (cont)

Don’t waste space in arrays:
 Avoid using fixed-size arrays if they will result in unused
array elements.
 Use dynamic arrays to minimize wasted memory, but
remember that resizing dynamic arrays consumes
processor time and can slow execution
 Consider other forms of data structures E.G.  linked lists
91
Using Variables, Types and
Constants (cont)

Types


Signify what type of data is stored in a variable, and the structure of that
data
General Type Guidelines

Provide descriptive real-world type names:


Watch for overflows:


E.G.  integer calculations that result in a result that is too large for the integer data type
Watch for rounding errors:


E.G.  names like CustomerArray, ArrayElements, and TelNoString should be avoided
E.G.  Visual Basic provides the Decimal data type for calculations that cannot tolerate
rounding errors
Watch for divide-by-zero errors:


Ensure that the denominator can never be zero.
Include code to check for a zero denominator to prevent divide-by-zero errors
92
Using Variables, Types and
Constants (cont)

General Type Guidelines (cont)

Be careful of using mixed-type comparisons:


Can cause unexpected results  equality comparisons involving floating-point numbers that should be equal are not.
Illustrated below:
Dim CompareVal As Single = 0.001
Dim CalcVal As Single
Dim Count As Byte
CalcVal = 100
For Count = 1 To 5
CalcVal *= 0.1
Out.WriteLine(CalcVal)
Next
If CalcVal = CompareVal Then
Out.WriteLine("The numbers are equal")
Else
Out.WriteLine("The numbers are not equal")
End If

The output looks like this:
10
1
0.1
0.01
0.0009999999
The numbers are not equal
Consider using a class:

If a primitive data type requires additional behaviour or additional data, consider using a class instead to provide that
behaviour
93
Using Variables, Types and
Constants (cont)

Enumerated Types

Use enumerated types:



Improve program readability and modifiability
A program using constants and enumerated types in
place of literals has an advantage over one scattered
with literals  easier to understand
Allows changes to be made to constant and
enumerated type values easily because changes need
only be made in one place, preserving integrity
94
Using Variables, Types and
Constants (cont)

Enumerated Types (cont)

Consider the following code:
Dim RainfallTotal As Single
Dim Rainfall(12) As Single
Dim Month As Byte
‘Initialize array here.
RainfallTotal = 0
For Month = 1 To 12
RainfallTotal += Rainfall(Month)
Next

It is not entirely clear that the code above is looping through the twelve
months of the year, January through to December.
95
Using Variables, Types and
Constants (cont)

Enumerated Types (cont)

Notice that the purpose of the loop is made clearer in the following improved version of the same code:
Enum Months
Invalid = 0
January = 1
February = 2
March = 3
April = 4
May = 5
June = 6
July = 7
August = 8
September = 9
October = 10
November = 11
December = 12
End Enum
Const MONTHS_IN_YEAR = 12
Dim RainfallTotal As Single
Dim Rainfall(MONTHS_IN_YEAR) As Single
Dim Month As Months
‘Initialize array here.
RainfallTotal = 0
For Month = Months.January To Months.December
RainfallTotal += Rainfall(Month)
Next
96
Using Variables, Types and
Constants (cont)

Enumerated Types (cont)

Use the first entry for an invalid value:
 Reserve the first entry for an invalid value
 Setting this entry to zero and declaring it as invalid will help
to reveal variables that have not been properly initialized
 See the example below:
Enum EmpStatus
Invalid = 0
FullTime = 1
PartTime = 2
End Enum
97
Using Variables, Types and
Constants (cont)

Enumerated Types (cont)

Check for invalid values: Check that variables of enumerated types have valid values:
Enum EmpStatus
Invalid = 0
FullTime = 1
PartTime = 2
End Enum
Private Function GrossSalary(ByVal Status As EmpStatus) As Decimal
Select Case Status
Case EmpStatus.FullTime
’Calculate full-time salary.
Case EmpStatus.PartTime
’Calculate part-time salary.
Case Else
’Deal with invalid status.
End Select
End Function
98
Using Variables, Types and
Constants (cont)

User-Defined Types

Use user-defined data type definitions to improve readability and modifiability:
Consider the following Visual Basic code:
Structure Dimension
Dim Meters As Single
End Structure
Dim Length As Dimension
Dim Breadth As Dimension
Dim Height As Dimension
Length.Meters = 2.05
Breadth.Meters = 4.12
Height.Meters = 3.72


If the dimensions require precision greater than that offered by a single data type,
simply change “Single” to “Double”
The change is restricted to only one place
99
Using Variables, Types and
Constants (cont)

User-Defined Types (cont)

Make type definitions easy to find and use:
 If you have type definitions that may be useful in multiple
applications, consider placing them in a separate module so
that they can be easy to find and add to other projects

Distinguish between user-defined types and
predefined types:
 Do not define user-defined types that could be mistaken for
predefined types  cause confusion when the code is read
 Use names that are clearly different to the ones used by
predefined types
100
Using Variables, Types and
Constants (cont)

User-Defined Types (cont)

Use user-defined data type definitions to group related data items:
Structure TStudent
Dim StudNo As Long
Dim Name As String
Dim Address As String
Dim TelNo As String
End Structure
Dim Student as TStudent
With Student
.StudNo = ...
.Name = ...
.Address = ...
.TelNo = ...
End With


Allows all the student data to be passed to a routine via only one parameter, instead of four (one each for student
number, name, address and telephone number)
Improves modifiability  elements in the structure can be changed without affecting the routines that receive the
student data as a parameter
101
Using Variables, Types and
Constants (cont)

User-Defined Types (cont)

Use user-defined data type definitions to group related data items (cont):

Such groupings can also simplify operations on the group of data, as shown in the example below:
Const MAX_STUDENTS = 2 ’Must be >= 2.
Dim Students(MAX_STUDENTS) As TStudent
Dim TempStudent As TStudent
‘Initialize array here.
TempStudent = Students(1)
Students(1) = Students(2)
Students(2) = TempStudent


The elements in the type can be changed (E.G.  additional elements added) with no change to the
code
Consider using a class instead:

Where additional flexibility is required
102
Using Variables, Types and
Constants (cont)

Symbolic Constants


Symbolic constants are descriptive names used
in place of literal constants, such as numeric or
string values
They offer similar advantages to enumerated data
types  improve program readability and
modifiability
103
Using Variables, Types and
Constants (cont)

Symbolic Constants (cont)

Guidelines for using symbolic constants:




Make code more meaningful.
E.G.  instead of using the literal constant 0.14 within code, define a symbolic
constant for the value 0.14 (E.G.  “TAX_RATE”)
Symbolic constants make programs easier to understand and reduce the
chance of inconsistencies  changes can be made more reliably and easily
(in one place)
Consider the following when using them:





Use uppercase names, separate each word with an underscore
Use names that describe the abstract entity represented by the constant, rather than
the value it refers to (E.G.  “VAT_RATE” instead of “FOURTEEN_PERC”)
Avoid digits in symbolic constant names
Avoid using any literal constants in a program, except a zero length string (“ ”) and the
numbers 0 and 1. This will ease maintenance and aid understanding
Use True and False rather than 0 and non-zero when representing boolean values
104
Using Variables, Types and
Constants (cont)

Symbolic Constants (cont)

Guidelines for using symbolic constants (cont):
 Constants not only be reserved for literals used more than
once in a program, but also used whenever they make code
more readable and maintainable
 Whenever including a literal value in code, ask whether a
named constant should be defined instead
 E.G.  instead of hard coding an array size into an array
declaration, declare a constant for the array size
 Use constants for lower and upper limits of loops
105
Using Variables, Types and
Constants (cont)

Symbolic Constants (cont)

Don’t use a variable if a constant will suffice:



Make consistent use of constants:



E.G.  do not declare constant MAX_HOURS to be 40 and then use MAX_HOURS in
some places in your code and 40 in others to refer to the same quantity.
Later changing the constant’s value to 35 is likely to cause logic errors if you forget to
change the 40’s to 35’s
Group constant definitions together:


A variable represents a data item whose values changes at run-time
If a variable’s value will never change at run-time, declare a constant instead
Place them above program code  easy to find E.G.  place them just after a routine’s
header or at the top of a program
Make use of the program language’s symbolic constants:

Programming languages provide a set of predefined symbolic constants  vbRed instead
of &hFF for the colour red
106
Naming Program Elements




Use of good names in a program is NB for
creating readable and clearer code
Different languages may have slightly
different conventions
Determine the conventions for the language
you are using and follow them
The naming convention chosen must be
adopted by all members of the project team
107
Naming Program Elements
(cont)

General guidelines for naming program
elements:

Use prefixes for interface objects:




Three-letter lowercase prefix for each user interface
control to indicate the control’s type
Makes code easier to read  type of control is evident
Standardize on a unique prefix for each type of object
for consistency
A longer prefix can be used if necessary for clarity
108
Naming Program Elements
(cont)

General guidelines for naming program
elements (cont):

Use prefixes for interface objects (cont):

A list of prefixes for common interface objects:
109
Naming Program Elements
(cont)

General guidelines for naming program elements
(cont):

Use prefixes for interface objects (cont):
 Menu control prefixes can be extended beyond “mnu” by
adding an additional prefix for each level of nesting, with the
final menu caption at the end of the name string
 E.G.  the File menu  “mnuFile” and the Open menu
item  “mnuFileOpen”.
 Menu control names will clearly document the menu items
to which they are attached
110
Naming Program Elements
(cont)

General guidelines for naming program
elements (cont):

Use prefixes for variables:


Prefix non-local variables to indicate their scope and
type.
E.G:
111
Naming Program Elements
(cont)

General guidelines for naming program
elements (cont):

An additional single-character prefix can be used
to specify scope. E.G:
112
Naming Program Elements
(cont)

General guidelines for naming program elements (cont):
 Use prefixes for type definitions:


Use a prefix for classes:


Identify type definition names and enumerated types using a prefix 
“T” , or suffix  “_Type” (E.G.  “TEmployee” , “T_Employee” or
“Employee_Type”)
Prefix the name of each class with an uppercase letter “C”
Use plural form for enumerated types:

Names for enumerated types should be plural E.G.  “Colours” and
“Months”
113
Naming Program Elements
(cont)

General guidelines for naming program elements (cont):

Use meaningful names:






Choose specific and descriptive names for all appropriate elements
i.e. variables, procedures, functions, and controls
The reader should be able to tell what a variable means or
represents, what a procedure or function does, what the purpose of a
control is, etc… by looking at its name
Helps make code self-documenting  reliance on manuals and
excessive comments can be reduced
Abstract names i.e. “routine2”, “Text10”, “v”, “x1”, “current”, “en”,
“Flag”, “Temp”, etc… make it difficult for new programmers to
understand logic flow
The name “Date” for a variable that stores the current date is not
ideal because the name is not specific enough  rather
“CurrentDate”
The name ”dataRead” is not specific enough for employee data read
 rather “employeeData”
114
Naming Program Elements
(cont)

General guidelines for naming program elements (cont):

Use meaningful names (cont):

Do not use names that have quirky or private meaning

Names should state “what” not “how”, thereby hiding underlying implementation and
preserving abstraction. This simplifies program complexity. E.G.  not
GetNextArrayElement  rather GetNextEmployee

Give boolean variables names that imply true or false. E.G.  not “status”  rather
“success”. Avoid terms like “flag” and negative names like “notSuccessful” and
“notFound”. Useful boolean names: ”Done”, “Error”, “Found”, “Success” and “OK”

Place computation qualifiers i.e. “Avg”, “Sum”, “Index”, and “Total”, at the end of names,
where appropriate E.G.  not “AvgSales”  rather “SalesAvg”

Do not include class names in the name of class properties. E.G.  not
Employee.EmployeeName  rather Employee.Name

Do not include table names in field names. E.G.  do not have a field named
EmployeePostalAddress in a table called Employee
115
Naming Program Elements
(cont)

General guidelines for naming program elements (cont):

Elements that should be named descriptively include:

User interface elements:


User-defined types:


Must convey the real-world meanings of values they store. Use only letters and
capitalize the first letter of each word E.G.  “EmpNum”
Constants:


Helps make code self-documenting
Variables:


E.G. command button performs an action, its name should describe the action 
cmdPrintInvoice
Describe the value represented by the constant
Classes:

Should convey each class’s real world meaning
116
Naming Program Elements
(cont)

General guidelines for naming program elements (cont):
 Elements that should be named descriptively include (cont):

Objects: Use names that are more specific than the class name E.G.
 “Employee101” for an instance of class “Employee”

Procedures and functions: Should express what the procedure or
function does. Include a verb indicating the action performed by the
procedure and a direct object indicating the entity on which the action
is performed

Parameters: Should have meaningful names that clearly express
their purpose

Database tables: Provide a descriptive name in singular form 
Employee instead of Employees
117
Naming Program Elements
(cont)

General guidelines for naming program elements (cont):

Keep names short:




But not too short and without sacrificing meaning
Avoid names that are longer than 16 to 20 characters E.G.  not “NumberOfEmployee”
 rather “EmployeeNumber”, “EmpNo” or “EmpNum”
Ask whether the name chosen will be understood by the reader
The following tips can help you abbreviate names (McConnell, 2004):










Use standard dictionary abbreviations  “fig” in place of “figure”
Remove all nonleading vowels E.G.  “screen” becomes “scrn” and “power” becomes
“pwr”
Remove articles: “and”, “or”, “the”, etc…
Use the first letter or first few letters of each word E.G.  “record” becomes “rec”
Truncate consistently after the first, second, or third letter of each word
Use every significant word in the name, up to a max of three words
Remove useless suffixes: “ing”, “ed” , etc…
Keep the most noticeable sound in each syllable
Don’t change the meaning of the variable
Iterate through these techniques until you abbreviate each name to between 8 to 20
characters or the number of characters to which your language limits names
118
Naming Program Elements
(cont)

General guidelines for naming program elements (cont):

Keep names short (cont):









Avoid using phonetic abbreviations E.G.  “sk8” in place of “skate”, “hilite” in place of
“highlight”, and “trmn8” in place of “terminate”
Not worth creating an abbreviation that removes only one character from a word
Create names that can be pronounced E.G.  “pos” instead of “pstn”
Do not use names containing misspelled words E.G.  boolean variable “loosing” instead
of “losing”
Avoid using commonly misspelled words
Where multiple natural languages are used in a project or where variations of a natural
language are used, decide which language or variation will be used for names. E.G. 
decide whether “check” or “cheque” will be used
Avoid names that sound similar E.G.  “wrap” and “rap”
Avoid abbreviations that can be misinterpreted E.G.  “FTEmp” for full-time employee
instead of “Femp”, although “FEmp” and “F_Emp” might also be acceptable
Avoid names with similar meanings E.G.  “Input” and “ InputValue”. Avoid names with
different meanings but with similar names E.G.  “ClientRecs” and “ClientReps”
119
Naming Program Elements
(cont)

General guidelines for naming program elements
(cont):
 Keep names short (cont):

General suggestions for naming program elements
(cont):




Be careful of naming collisions  same abbreviation used for two
or more different words E.G.  “frd” could be used for both “fired”
and “full revenue disbursal”
When using a case-sensitive language, such as C++, don’t
differentiate names solely by capitalization. E.G.  “frd” for “fired”
and “FRD” for “full revenue disbursal” = confusing
Avoid using numbers in names E.G.  “total1” and “total2”
Create a “Standard Abbreviations” document to record all coding
abbreviations used on a project, sorted by original word not
abbreviation. This will avoid the creation of redundant
abbreviations.
120
Naming Program Elements
(cont)

General guidelines for naming program elements (cont):

Maintain consistency: E.G.  do not use the name “TotalSales” for one
variable and “ExpenseTotal” for another. Instead, use “SalesTotal” and
“ExpenseTotal”. Also use consistent abbreviations i.e. do not use “Num” in
some places and “Number” in others

Use opposite pairs precisely: E.G. Min and Max, First and Last and
Source and Target

Avoid ambiguous names:



Avoid reusing names for different elements. E.G. do not use the name of an
existing control in a variable declaration statement. Similarly, do not use the
same name for a routine and a variable
Do not begin a variable name with one of the conventional three letter prefixes
for control names
Avoid using duplicate variable names in an application
121
Guidelines for Writing Code





















Code for ease of understanding
Code for ease of readability
Code for efficiency and performance
Look for ways to avoid duplication
Use structured programming
Write code to flow from top to bottom
Share data correctly
Minimize the scope of code elements
Explicitly declare the scope of variables and methods in classes
Simplify complicated logic
Simplify complicated data access
Never hard-code values in your code
Terminate the program gracefully and in only one place
Close open files when access is no longer needed
Destroy objects that are no longer needed
Don’t use error handling as a means of program control
Trim spaces from string values
Avoid forcibly exiting from a decision structure, loop, function or procedure
Avoid using recursion in performance situations
Adhere to the key object-oriented principles
Take advantage of the features of object orientation
122
Using Selection and Iteration

Leave out …
123
Commenting Your Code










Use comments where appropriate
Don’t use too many or too few comments
Don’t simply translate code
Do not document bad code
Format comments for ease of readability
Format comments for ease of modification
Remove unnecessary comments
Add comments while writing code
Keep comments up to date
Consider using a code documentation utility
124
Managing Resources

Leave out …
125
Refactoring Code






Building construction is not a really a good metaphor for software
development
With building construction, blueprints are drawn up, the building
is constructed, and any problems that might arise later are fixed
Software development rarely involves simply taking a design,
writing code and delivering the result
In contrast, it is common for adjustments to be made during the
process
E.G.  requirements might change, or a procedure might
become too complex and have to be divided
Rewriting, reworking and re-architecting code is known as
refactoring. It is about changing working code where the
changes do not affect the program behaviour
126
Refactoring Code (cont)

Reasons for refactoring code (Hunt & Thomas, 2000; McConnell, 2004):


















Code is duplicated
Design or code is not orthogonal
Knowledge is outdated
Performance is poor
A class has poor cohesion
A class does not do very much
A class interface does not provide a consistent level of abstraction
Data members are public
Changes within a class tend to be compartmentalized
Changes require parallel modifications to multiple classes
Related data items that are used together are not organized into classes
A middleman object isn’t doing anything
One class is overly intimate with another
A routine uses more features of another class than of its own class
A routine has a poor name
A routine is too long
A chain of routines passes tramp data
A routine uses setup code before a routine call or takedown code after a routine call
127
Refactoring Code (cont)

Guidelines for Refactoring Code






Save or backup the original code
Don’t add functionality
Make small changes, one at a time
Review each change
Test each change
Don’t hack
128
Improving Program
Performance


Program performance is only one aspect of overall software
quality and should not be seen as the sole contributor of high
quality software
When optimizing performance is important there are various
techniques that can be used. McConnell (2004):
 Change the program’s requirements
 Modify the program’s design
 Modify the class design
 Avoid operating system interactions
 Avoiding input/output
 Use a compiled language instead of an interpreted language
 Use compiler optimizations
 Use different hardware
 Use code tuning
129
Collaborative Construction

Leave out …
130
Performing Integration

Leave out …
131
Using Source Code Control


A source code control system is like a
project-wide undo function that can take you
back to an earlier version of a project - a
version that compiled and ran
Keeps track of every change made in source
code and documentation allowing you to go
back to an earlier version of your software
132
Using Source Code Control
(cont)

A good source code control system allows
you to track changes, answering questions
such as (Hunt & Thomas, 2000):




Who made changes to this line of code?
What’s the difference between the current version
and last week’s version?
How many lines of code did we change in this
release?
Which files get changed most often?
133
Using Source Code Control
(cont)






These questions are useful for bug-tracking, auditing, and
performance and quality purposes
Allow multiple users to work concurrently on the same set of files
Changes made by multiple users are then merged when the files
are returned to the repository
Such change control is necessary otherwise a user might change
a routine that someone else is changing at the same time or he
or she might unknowingly test an old version of a routine
Always use source code control for large or small projects,
whether a single person team or multiple-person team
Hunt & Thomas (2000) advise using it for everything –
documentation, phone number lists, memos to vendors, build
and release procedures, utility shell scripts, etc…
134
Using Source Code Control
(cont)

Using source code control software offers several benefits (McConnell,
2004):







It prevents you from changing a file that is being worked on by someone else
You can easily update your copies of all a project’s files to the current versions,
by issuing a single command
You can backtrack to any version of any file that was ever checked into the
repository
You can get a list of the changes made to any version of any file
You do not have to worry about personal backups because the version control
copy is a safety net
Be sure that your source code control software (and your software
configuration management plan in general) does not become a burden to
the project
It should be a valuable asset to a project; it should assist developers and do
so with minimum overhead
135
Using Good Tools



Tools such as source code control systems
make the lives of developers a lot easier
E.G.  a tool might be able to reduce tedious
work by partially or completely automating
such work
Actively search for and make use of good
tools to increase productivity and save time
136
Using Good Tools (cont)

Types of tools that developers find valuable (McConnell, 2004):














Design tools (E.G.  tools for drawing design diagrams)
Integrated Development Environments (IDEs) that offer useful timesaving features (E.G. 
error detection, ease of navigation and automatic formatting)
Search and replace tools that support search-and-replace across multiple files
File comparators to compare two files and list the differences
Merge tools that merge changes made to multiple files
Source-code beautifiers to neaten up source code
Documentation tools to extract documentation from source code to produce well-formatted
documentation (E.G.  Javadoc)
Templates to reduce typing and encourage consistent coding and documentation styles
Cross-reference tools to list variables and routines and where they have been used
Class hierarchy generators to produce information about inheritance trees
Syntax and semantics checkers to check code for errors
Metrics reporters to analyze code and report on its quality (E.G.  to locate complexity)
Refactoring tools to help make code changes quicker and less errorprone
Restructurers to assist in restructuring code (E.G.  to convert spaghetti code into betterstructured code)
137
Using Good Tools (cont)

Types of tools that developers may find very valuable (cont):











Code translators to translate code from one language to another
Version-control tools for requirements, source code, project documentation, and other
project artifacts
Data dictionaries to describe all significant data in a project
Compilers, linkers and build tools
Code libraries that can be used instead of writing your own code (E.G>  a data
compression library)
Code-generation tools to generate code for you
Setup and installation tools for installing your application
Tools that help you debug code (E.G.  execution profilers)
Tools that help you conduct effective testing
Tools that help you fine-tune your code (E.G.  execution profilers and disassemblers)
You can also build your own tools when you need them. One example is a script
that automates a repetitive, possibly tedious, task
138
Conclusion

Solid coding techniques and good
programming practices help to create high
quality code and play an important role in
software quality and performance
139