0% found this document useful (0 votes)
15 views43 pages

08 - Ch8 Implementation - 2022 - Ny

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views43 pages

08 - Ch8 Implementation - 2022 - Ny

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

SOFTWARE

ENGINEERING
CO3001

CHAPTER 8 – SOFTWARE IMPLEMENTATION Anh Nguyen-Duc


Tho Quan-Thanh

WEEK 8
Adapted from https://iansommerville.com/software-engineering-book/slides/
TOPICS COVERED

 Implementation meaning
 Coding style & standards
 Code with correctness justification
 Integration meaning
 Integration process

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 2


IMPLEMENTATION

smallest part that will be separately maintained

 Implementation = Unit Implementation + Integration

put them all together

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 3


GOLDEN RULE (!?)

 Requirements to satisfy Customers


 Design again requirements only
 Implement again design only
 Test again design and requirements

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 4


IMPLEMENT CODE

 1. Plan the structure and residual design for your code


 2. Self-inspect your design and/or structure
 3. Type your code
 4. Self-inspect your code
 5. Compile your code
 6. Test your code

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 5


GENERAL PRINCIPLES IN PROGRAMMING PRACTICE

 1. Try to re-use first


 2. Enforce intentions
 If your code is intended to be used in particular ways only, write it so
that the code cannot be used in any other way.
 If a member is not intended to be used by other functions, enforce this
by making it private or protected etc.
 Use qualifiers such as final and abstract etc. to enforce intentions

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 6


“THINK GLOBALLY, PROGRAM LOCALLY”

 Make all members


 as local as possible
 as invisible as possible
 attributes private:
 access them through more public accessor functions if required.
 (Making attributes protected gives objects of subclasses access to members of their base classes
-- not usually what you want)

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 7


EXCEPTIONS HANDLING
“If you must choice between throwing an exception
and continuing the computation, continue if you can”
(Cay Horstmann)

 Catch only those exceptions that you know how to handle


 Be reasonable about exceptions callers must handle
 Don’t substitute the use of exceptions for issue that should be
the subject of testing

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 8


NAMING CONVENTIONS

 Use concatenated words


 e.g., cylinderLength

 Begin class names with capitals


 Variable names begin lower case
 Constants with capitals
 as in MAX_N or use static final

 Data members of classes with an underscore


 as in _timeOfDay

 Use get…, set…., and is… for accessor methods


 Additional getters and setters of collections
 And/or distinguish between instance variables, local variables and
parameters
Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 9
DOCUMENTING METHODS

 what the method does


 why it does so
 what parameters it must be passed (use @param tag)
 exceptions it throws (use @exception tag)
 reason for choice of visibility
 known bugs
 test description, describing whether the method has been tested, and the location of its test
script
 history of changes if you are not using a sub-version system
 example of how the method works
 pre- and post-conditions
 special documentation on threaded and synchronized methods

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 10


/* Class Name : EncounterCast
* Version information : Version 0.1
* Date : 6/19/1999
* Copyright Notice : see below
* Edit history:
* 11 Feb 2000/** Facade Tomclass/object
VanCourt for thesimplified
Used EncounterCharacters package. Used to
test interface.
* 8 Feb 2000 * reference
Tom all charactersMinor
VanCourt of the Encounter game.
cleanup.
* 08 Jan 2000* <p> Design: SDD 3.1 Module
Tom VanCourt Changedecomposition
to conform to coding standards
*/ * <br> SDD 5.1.2 Interface to the EncounterCharacters package
*
/* * <p>Design issues:<ul>
Copyright* <li> SDD Eric
(C) 2000 5.1.2.4 method
J. Braude engagePlayerWithForeignCharacter
and Thomas D. Van Court. was
* not implemented, since engagements are handled more directly
* from
This program theimplementation
is the Engaging stateofobject.
the case study specified in
"Software * </ul>
Engineering:
/** Gets anencounterCast,
Object-Oriented the Perspective,"
one and onlyWiley 2001,
instance of EncounterCast.
by Eric J.*Braude. * <p> Requirement: SDD 5.1.2
* @author* Dr. Eric Braude
* @version 0.1
* @return The EncounterCast singleton.
*/ */
public class EncounterCast
public static EncounterCast getEncounterCast()
{ { return encounterCastS; }
/** Name for human player */
Sep 2019 private static final String MAIN_PLAYER_NAME = "Elena"; CHAPTER 7.3. MORE ON IMPLEMENTATION 11
DOCUMENTING ATTRIBUTES

 Description -- what it's used for


 All applicable invariants
 quantitative facts about the attribute,
 such as "1 < _age < 130"
 or " 36 < _length * _width < 193".

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 12


CONSTANTS

 Before designating a final variable, be sure that it is, indeed, final.


You’re going to want to change "final" quantities in most cases.
Consider using method instead.
 Ex:
 instead of ...
 protected static final MAX_CHARS_IN_NAME;

 consider using ...


 protected final static int getMaxCharsInName()
 { return 20;
 }

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 13


INITIALIZING ATTRIBUTES

 Attributes should be always be initialized, think of


 private float _balance = 0;
 Attribute may be an object of another class, as in
 private Customer _customer;
 Traditionally done using the constructor, as in
 private Customer _customer = new Customer( "Edward", "Jones" );
 Problem is maintainability. When new attributes added to
Customer, all have to be updated. Also accessing persistent
storage unnecessarily.
Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 14
RELEVANT BOOKS

Old edition, available online at NTNU lib. New edition


BAD SMELLS IN CODE (CODE SMELLS)

 Code smells are any violation of fundamental design


principles that decrease the overall quality of the code.

 Not bugs or errors

 Can certainly add to the chance of bugs and failures


down the line.
CODE SMELLS CATEGORIES

 Duplicated Code • Switch Statements


 Long Method • Lazy Element
 Large Class • Speculative Generality
• Temporary Field
 Long Parameter List
• Message Chains
 Divergent Change • Middle Man
 Shotgun Surgery
• Data Class
 Feature Envy • Refused Bequest
 Data Clumps
 Primitive Obsession
COD REFACTORING GOALS AND PROPERTIES

 Change the internal structure without changing external


behavior

 Eliminate code smells for


 Readability
 Consistency
 Maintainability

 Properties
 Preserve correctness
 One step at a time
 Frequent testing
CODE REFACTORING STEPS

 Designing solid tests for the section to be refactored

 Reviewing the code to identify bad smells of code

 Introducing refactoring and running tests (One step at a time)


REMOVE DUPLICATED CODE – PULL UP METHOD (DON’T REPEAT YOURSELF
(DRY))
 You have methods with identical results on subclasses.
REMOVE DUPLICATED CODE - SUBSTITUTE ALGORITHM

 You want to replace an algorithm with one that is clearer.

String foundPerson(String[] people){ String foundPerson(String[] people){


List candidates = Arrays.asList(new
for (int i = 0; i < people.length; i++) { String[] {"Don", "John", "Kent"});
if (people[i].equals ("Don"))
{ return "Don"; } for (int i=0; i<people.length; i++)
if (candidates.contains(people[i]))
if (people[i].equals ("John")) return people[i];
{ return "John"; }
return "";
if (people[i].equals ("Kent"))
{ return "Kent"; } }
}
return "";
}
REDUCE SIZE – SHORTEN METHOD/CLASS

 Long Method
 E.g., Extract method

 Large Class
 E.g., Extract class, subclass, interface
EXTRACT METHOD EXAMPLE
If you have to spend effort looking at a fragment of code and figure out what it
is doing, then you should extract it into a function/method and name it after
“what.”

void printOwing() { printBanner();


void printOwing() printDetails(getOutstanding());}
{
printBanner(); //print details
void printDetails (double outstanding) {
System.out.println ("name: " +
_name); System.out.println ("name:" + _name);
System.out.println ("amount " System.out.println ("amount:" +
+ getOutstanding()); outstanding);
} }
REDUCE SIZE – SHORTEN PARAMETER LIST

 Long Parameter List


 E.g., Introduce Parameter Object
DIVERGENT CHANGE

 Code smell
 One module is often changed in different ways for different
reasons.
 Classes have more than distinct responsibilities that it has
more than one reason to change
 Violation of single responsibility design principle

 Refactoring
 You identify everything that changes for a particular cause
and put them all together
INCREASE COHESION

 Feature envy
 A function in one module spends more time communicating
with functions or data inside another module than it does
within its own module.
 Move function to give it a dream home

https://waog.wordpress.com/2014/08/25/code-smell-feature-envy/
INCREASE COHESION (CONT’)

• Data clumps
– Bunches of data often hang around together
– Consolidate the data together, e.g., Introduce
Parameter Object or Preserve Whole Object

int low = daysTempRange().getLow();


withinPlan =
int high = daysTempRange().getHigh();
plan.withinRange(daysTempRange());
withinPlan = plan.withinRange(low, high);
PRIMITIVE OBSESSION

 Primitive fields are basic built-in building blocks of a language,


e.g., int, string, or constants

 Primitive Obsession is when the code relies too much on


primitives and when uses primitive types to represent an object
in a domain
The address is defined as an array.
Every time we need the address we will
have to hard code it

https://codeburst.io/write-clean-code-and-get-rid-of-code-smells-aea271f30318
We create a new class called Address
Every time we need to add/edit an
address we hit the Address class

https://codeburst.io/write-clean-code-and-get-rid-of-code-smells-aea271f30318
INSPECTION AND CODE REVIEW

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 31


WHAT IS INSPECTION?

 Visual examination of software product

 Identify software anomalies


 Errors
 Code smells
 Deviations from specifications
 Deviations from standards
 E.g., Java code conventions
www.oracle.com/technetwork/java/codeconventions-150003.pdf
WHY DO WE NEED INSPECTION?

 Many software artifacts cannot be verified by running tests, e.g.,


 Requirement specification
 Design
 Pseudocode
 User manual

 Inspection reduces defect rates


 Inspection complements testing
 Inspection identifies code smells
 Inspection provides additional benefits
INSPECTION FINDS TYPES OF DEFECTS DIFFERENT FROM TESTING

Number of different types of defects detected by testing vs. inspection [1]

Some defect types Testing Inspection


Uninitialized variables 1 4
Illegal behavior, e.g., division by zero 49 20
Incorrectly formulated branch conditions 2 13
Missing branches, including both conditionals and 4 10
their embedded statements
INSPECTION REDUCES DEFECT RATES
TESTING VS. INSPECTION

Testing Inspection

Pros • Can, at least partly, be • Can be used on all types of


automated documents, not just code
• Can consistently repeat • Can see the complete picture, not
several actions only a spot check
• Fast and high volume • Can uses all information in the team
• Can be innovative and inductive

Cons • Is only a spot check • Is difficult to use on complex,


• Can only be used for code dynamic situations
• May need several stubs and • Unreliable (people can get tired)
drivers • Slow and low volume
CODE REVIEW AT GOOGLE [3]

 "All code that gets submitted needs to be reviewed by at least


one other person, and either the code writer or the reviewer
needs to have readability in that language. Most people use
Mondrian to do code reviews, and obviously, we spend a good
chunk of our time reviewing code."

--Amanda Camp, Software Engineer, Google


EXAMPLE OF A CODE REVIEW CHECKLIST

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 38


INSPECT CODE 1 OF 5: CLASSES OVERALL

 C1. Is its (the class’) name appropriate?


 C2. Could it be abstract (to be used only as a base)?
 C3. Does its header describe its purpose?
 C4. Does its header reference the requirements and/or design
element to which it corresponds?
 C5. Does it state the package to which it belongs?
 C6. Is it as private as it can be?
 C7. Should it be final (Java)
 C8. Have the documentation standards been applied?
Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 39
INSPECT CODE 2 OF 5 : ATTRIBUTES

 A1. Is it (the attribute) necessary?


 A2. Could it be static?
 A3. Should it be final?
 A4. Are the naming conventions properly applied?
 A5. Is it as private as possible?
 A6. Are the attributes as independent as possible?
 A7. Is there a comprehensive initialization strategy?

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 40


INSPECT CODE 3 OF 5 : CONSTRUCTORS

 CO1. Is it (the constructor) necessary?


 CO2. Does it leverage existing constructors?
 CO3. Does it initialize of all the attributes?
 CO4. Is it as private as possible?
 CO5. Does it execute the inherited constructor(s) where
necessary?

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 41


INSPECT CODE 4 OF 5: METHOD HEADERS

 MH1. Is the method appropriately named?


 MH2. Is it as private as possible?
 MH3. Could it be static?
 MH4. Should it be final?
 MH5. Does the header describe method’s purpose?
 MH6. Does the method header reference the requirements and/or design section that it
satisfies?
 MH7. Does it state all necessary invariants?
 MH8. Does it state all pre-conditions?
 MH9. Does it state all post-conditions?
 MH10.Does it apply documentation standards?
 MH11.Are the parameter types restricted?

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 42


INSPECT CODE 5 OF 5: METHOD BODIES

 MB1. Is the algorithm consistent with the detailed design pseudocode and/or flowchart?
 MB2. Does the code assume no more than the stated preconditions?
 MB3. Does the code produce every one of the postconditions?
 MB4. Does the code respect the required invariant?
 MB5. Does every loop terminate?
 MB6. Are required notational standards observed?
 MB7. Has every line been thoroughly checked?
 MB8. Are all braces balanced?
 MB9. Are illegal parameters considered?
 MB10. Does the code return the correct type?
 MB11. Is the code thoroughly commented?

Sep 2019 CHAPTER 7.3. MORE ON IMPLEMENTATION 43

You might also like