Title: Best Practices
1Best Practices
2Agenda
- 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
3Agenda (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
4Introduction
- Third phase in the SDLC (developing the
software) ? programming - Involves several key activities
- Defining the problem
- Detailed design
- Coding
- Debugging and unit testing
- Integration
- Integration testing
- Updating documentation
- Activities ? carried out in sequence
5Introduction (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
6Introduction (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
7Introduction (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
8Introduction (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
9Introduction (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
10Introduction (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
11Introduction (cont)
- A detailed look at the third phase (construction
phase) (cont) - Updating Documentation
- Writing a description of the programs 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
12Introduction (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
13Fundamental 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
14Fundamental 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) - Dont 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
15Fundamental 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
16Fundamental 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 others code, and what
types of testing will be conducted
17Fundamental 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
18Fundamental 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
19Fundamental 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
20Fundamental Principles and Practices (cont)
- Design and build orthogonal 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 - Design and build flexible, adaptable systems
- 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
21Fundamental 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)
22Fundamental 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
23Fundamental 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
24Fundamental 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
25Fundamental 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
- Dont duplicate
26Fundamental 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
- Create and name the important controls before
working on event procedures - Type constant definition statements and variable
declaration statements before typing other code - Type the remaining statements in lowercase letters
27Fundamental Principles and Practices (cont)
- Seek proven ways of doing things
- 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 - Use good tools
- 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
28Fundamental 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
29Actively 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
30Duplicating 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?
31Duplicating 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
32Duplicating 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
33Duplicating 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 modules 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)
34Duplicating Knowledge (cont)
- Ways to Reduce Inadvertent Duplication
- Mistakes in a systems 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
35Duplicating 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
36Duplicating 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 peoples
source code and documentation. This makes it
easier to reuse existing work
37Orthogonality
- 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
38Orthogonality (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
39Orthogonality (cont)
- Keep your code decoupled
- Write modules that dont reveal anything
unnecessary to other modules and that dont rely
on the implementation of other modules - If you need to change an objects state, get the
object to do it for you - Avoid global data
- Explicitly pass any required context into your
modules as parameters. - Avoid similar functions
- Dont code functions that contain similar code
40Orthogonality (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
41Flexibility 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
42Flexibility and Adaptability (cont)
- Follow the dont 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
43Flexibility 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
44Flexibility 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
objects methods - The law states (Hunt Thomas, 2000)
45Flexibility 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
46Programming 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
47Programming 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
48Programming 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
49Programming 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
50Programming 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
51Programming 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 non-exceptional 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
52Programming 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
53Programming 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
54Programming 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
55Programming 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)
56Creating 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
57Creating 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
58Creating 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 classs details and
shows that all its methods and properties belong
together - Make usage as obvious as possible
- Minimize accessibility ? strictest level of
privacy - Dont 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
59Creating Classes (cont)
- E.G. of a badly designed class
60Creating Classes (cont)
61Creating Classes (cont)
- Steps for Creating Classes
- Design the class
- What private data the class will hold
- What the classs 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 classs interface one that presents
convenient abstraction - Write the code for the class Create the data
members, properties, and routines - 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
62Creating 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
63Creating 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
64Creating 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
65Creating Routines (cont)
- E.G. of pseudocode that violates these guidelines
66Creating Routines (cont)
- A better design
- Pseudocode can become actual comments in a
program, thereby clearly describing the intent of
the code
67Creating Routines (cont)
- Steps for Creating Routines
- Design the Routine
- Check the Design
- Code the Routine
- Review and Test the Code
- Conduct a Final Quality Check
68Creating 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
69Creating 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
70Creating 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 routines declaration and add its
description - The table describes information that should
appear inside a routines header
71Creating 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
72Creating Routines (cont)
- Steps for Creating Routines (cont)
- Code example showing pseudocode statements
transformed into C comments
73Creating 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
74Creating 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
75Creating Routines (cont)
- Guidelines for Creating Routines (cont)
- Separate query operations from modification
operations - 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 - Avoid unnecessary proliferation of procedures,
functions and classes - 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
76Creating 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
functions 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.
77Creating 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
78Creating 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 routines
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 routines
parameters
79Creating 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
80Passing by Value
- By Value parameters retain their original value
after Sub procedure terminates
81Passing by Reference
- "By Reference" parameters can be changed by the
Sub procedure and retain the new value after the
Sub procedure terminates
82Creating 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
83Using 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
84Using 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
85Using 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
86Using 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
87Using 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
88Using Variables, Types and Constants (cont)
- Guidelines for using variables (cont)
- Keep references to the same variable close
together - Helps reduce the chance that the variables value
might be changed inadvertently when new code is
added - Improves readability ? users 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
89Using 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
90Using 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
91Using Variables, Types and Constants (cont)
- Guidelines for using variables (cont)
- Dont 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
92Using 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
- E.G. ? names like CustomerArray, ArrayElements,
and TelNoString should be avoided - 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. ? 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
93Using 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")
The output looks like this 10 1 0.1 0.01 0
.0009999999 The numbers are not equal
94Using 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
95Using 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.
96Using 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
97Using 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
98Using 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
99Using 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
100Using 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
101Using 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 Addre