SlideShare a Scribd company logo
1 of 199
Download to read offline
Software Defect Prevention Techniques
         - Example Project -



               Zarko Acimovic
             Copyright © 2012 Zarko Acimovic

                    All rights reserved.

                  ISBN-10: 1481113305
                ISBN-13: 978-1481113304
DEDICATION

I dedicate this book to my parents, Ivana and Goran
CONTENTS

1   Introduction

2   Theoretical Foundations for Defect Prevention              1

3   Automatic Tools for Defect Prevention                      24

4   Tools for Defect Prevention in Java Software Development   25

5   Sample Project Software Requirements                       25

6   Source Code with Violations                                26

7   Design Defects Detected by ArgoUML                         192

8   Examples of Design Defects in Sample Project               196

    About the Author
Zarko Acimovic




                                             1 INTRODUCTION

I present 5000 lines of Java source code from prototype project. The code is operational and fulfills its software
requirements. I wrote the code in 2004 and ever since had several business offers to commercialize it, which I resisted
due to complexity of the code. I tested the code with static analysis tools PMD, FindBugs, StateOfFlow and
ArgoUML in order to comprehend its architectural quality. Source code is presented as written in 2004. These tools
uncovered 1123 code violations (almost 1 violation per 5 lines of code) and 121 software design violations. All these
violations are presented in book with references to the source code. I recommend to readers to use these tools during
development and correct all the violations reported.




             2 THEORETICAL FOUNDATIONS FOR DEFECT PREVENTION

Below are the details of E-learning course “Software Engineering” from IIT Bombay India >> NPTEL >> Courses
>> Computer Science and Engineering >> Software Engineering (Video).
My opinion is that this course provides solid theoretical foundation for applying software defect prevention
techniques. The course can be found on following location


http://nptel.iitm.ac.in/video.php?subjectId=106101061

Here are the details of the course:


1 - Introduction to Software Engineering (52:21)
2 - Introduction to Software Engineering (52:55)
3 - Overview of Phases (57:22)
4 - Overview of Phases (57:03)
5 - Requirements Engineering / Specification (56:39)
6 - Formal Specification (51:44)
7 - Algebraic Specification Methods (57:34)
8 - Systems Modeling Overview (59:38)
9 - Process Modeling - DFD , Function Decomp (56:28)
10 - Process Modeling - DFD, Function Decomp (53:23)
11 - Data Modeling - ER Diagrams, Mapping (1:00:55)
12 - Data Modeling - ER Diagrams, Mapping (58:08)
13 - Production Quality Software - Introduction (53:04)
14 - Software Design - Primary Consideration (1:04:43)
15 - Design Patterns (56:13)
16 - Class and Component Level Design (54:34)
17 - Architectural Design (59:28)
18 - Software Testing - I (55:39)
19 - Software Testing - II (51:18)
20 - Structural Programming and Some implementation (45:05)
21 - Software Metrics and Quality (54:51)
22 - Verification and Validation (52:43)


                                                          iv
Software Defects Prevention Techniques – Example Project


23 - Case Study (54:55)
24 - Case Study (58:39)
25 - Software Evolution (55:41)
26 - Agile Development (55:33)
27 - Software Reuse (53:43)
28 - Reuse Continued (57:07)
29 - Introduction to Project Management (52:36)
30 - Project Scope Management (1:08:45)
31 - Project Time Management (56:51)
32 - Estimation - I (51:42)
33 - Estimation - II (50:38)
34 - Project Quality Management (58:32)
35 - Quality Management Systems - I (54:43)
36 - Quality Management Systems (54:53)
37 - Project Configuration Management (53:00)
38 - Project Risk Management (56:04)
39 - Other PM Processes (55:41)

Here are the details of the videos:


    1. Introduction to Software Engineering (52:21)
       http://nptel.iitm.ac.in/video.php?subjectId=106101061


    2. Introduction to Software Engineering (52:55)
       http://nptel.iitm.ac.in/video.php?subjectId=106101061

        •    Waterfall Model for Development
        •    Deliverables in Waterfall Model
        •    Cost/Effort Distribution
        •    Shortcomings of Waterfall Model
        •    Prototyping Model
        •    Prototyping
        •    Limitations of Prototyping
        •    Iterative Development
        •    Spiral Model
        •    Project Management Process
        •    Project Planning
        •    Project Monitoring and Control




                                                                 v
Zarko Acimovic


3. Overview of Phases in Software Development (57:22)
   http://nptel.iitm.ac.in/video.php?subjectId=106101061


4. Overview of Phases in Software Development (57:03)
   http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Structured Analysis
   •   Structured Methodology
   •   Requirement Specification Format
   •   System Design
   •   Alternatives
   •   Design goals
   •   System Architecture
   •   Structure Chart
   •   Structure Chart Notation
   •   OO Approach
   •   Design Document Format
   •   Detailed Design
   •   Implementation Phase
   •   Operations & Maintenance
   •   Summary



5. Requirements Engineering / Specification (56:39)
   http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Objectives
   •   Requirements engineering
   •   What is a requirement?
   •   Requirements abstraction (Davis)
   •   Types of requirement
   •   Requirements Audience
   •   Functional and non-functional requirements
   •   Functional requirements
   •   The LIBSYS system
   •   Examples of functional requirements
   •   Requirements imprecision
   •   Requirements completeness and consistency
   •   Non-functional requirements
   •   Non-functional classifications
   •   Non-functional requirement types
   •   Non-functional requirements examples
   •   Goals and requirements
   •   Examples
   •   User requirements
   •   Problems with natural language
   •   LIBSYS requirement
   •   Editor grid requirement


                                                    vi
Software Defects Prevention Techniques – Example Project


   •   Requirement problems
   •   Structured presentation
   •   Guidelines for writing requirements
   •   System requirements
   •   Requirements and design
   •   Alternatives to NL specification
   •   Structured language specifications
   •   Form-based specifications
   •   Tabular specification
   •   Graphical models
   •   PDL interface description
   •   The requirements document
   •   IEEE requirements standard


6. Formal Specification (51:44)
   http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Natural Language Requirement Specification
   •   Problem Statement
   •   The Need for Formal Specification
   •   Formal methods
   •   Acceptance of formal methods
   •   Use of formal methods
   •   Specification in the software process
   •   Specification techniques
   •   Formal specification languages
   •   Use formal specification
   •   Development costs with formal specification
   •   Properties of Formal Specifications
   •   Library Example-Informal Statement
   •   Library Example -- Formalization
   •   Library Example -- Formalization - 2
   •   Library Example -- Prove Correctness
   •   Specification Types
   •   Interface specification
   •   Sub-system interfaces
   •   Behavioral specification
   •   Key points



7. Algebraic Specification Methods (57:34)
   http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Disadvantages of NL specifications
   •   Another Perspective - Dangers of Physical Representations in Analysis
   •   Towards Abstraction
   •   What does a Abstract Data Type (ADT) consist of?7:29
   •   What about Post Conditions?

                                                     vii
Zarko Acimovic


   •   Algebraic Manipulation using Axioms
   •   Abstract Math to Concrete realizations
   •   ADTs and Information Hiding
   •   Completeness of Specification
   •   Definition: sufficient completeness
   •   ADT Consistency


8. Systems Modeling Overview (59:38)
   http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Model types
   •   Context models
   •   The context of an ATM system
   •   Process models
   •   Behavioral models
   •   Order processing DFD
   •   Microwave oven model
   •   Microwave oven state description
   •   Microwave oven stimuli
   •   Microwave oven state description
   •   Microwave oven stimuli
   •   Microwave oven operation
   •   Semantic data models
   •   Library semantic model
   •   Data Dictionary Entries
   •   Object models
   •   Inheritance models
   •   Multiple inheritance
   •   Object aggregation
   •   Object behavior modeling
   •   Structured methods


9. Process Modeling - DFD , Function Decomposition (56:28)
   http://nptel.iitm.ac.in/video.php?subjectId=106101061

       •   ER MODEL
       •   ENTITY
       •   ENTITY SET
       •   ATTRIBUTE
       •   DOMAIN
       •   PRIMARY KEYS
       •   EXAMPLE : A COLLEGE
       •   RELATIONSHIP
       •   RELATIONSHIP SET
       •   DEPICTING A RELATIONSHIP
       •   PRIMARY KEY FOR REPATIONSHIPS
       •   RELATIONSHIP CARDINALITY



                                                     viii
Software Defects Prevention Techniques – Example Project



10. Process Modeling - DFD, Function Decomposition (53:23)
 http://nptel.iitm.ac.in/video.php?subjectId=106101061

    •   RELATIONSHIP CARDINALITY
    •   EXISTENCE DEPENDENCE
    •   TERNARY RELATIONSHIPS
    •   WEAK ENTITY
    •   EXTENDED E-R MODEL
    •   Generalization




11. Data Modeling - ER Diagrams, Mapping (1:00:55)

    •   Generalization
    •   Specialization
    •   Inheritance
    •   Aggregation
    •   Process Model
    •   Function Decomposition
    •   FD Diagrams: Examples


12. Data Modeling - ER Diagrams, Mapping (58:08)
 http://nptel.iitm.ac.in/video.php?subjectId=106101061

        •   Data Flow Diagram (DFD)
        •   DFD Notation
        •   Context Diagram
        •   Process Refinement
        •   Physical DFD
        •   Showing Boundaries
        •   DFD Example 1: Payroll
        •   DFD Example 2: Old Car Mart
        •   DFD Example Old Car Mart
        •   Example 3: Book Supplier
        •   Book Supplier: Exploding Process 2
        •   Book Supplier : homework


13. Production Quality Software - Introduction (53:04)
 http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Software construction then and now
•   Software Crisis (Late 1980s)
•   More perspective on the Software Crisis
•   Brian Russell's Laws of Software Relativity
•   Properties of Failing software
•   Common Error in Managing the Process

                                                        ix
Zarko Acimovic


•   Software Maintenance
•   Quality Factors for Software
•   Quality Factors
•   Quality Factors - contd.
•   Quality Factors
•   Keys to achieving Structural Quality
•   What ls Abstraction?
•   Abstraction
•   Abstraction Techniques
•   Encapsulation
•   Modules
•   Desirable Characteristics - Weak Coupling
•   Information Hiding
•   Protocol Vs Behavior
•   IH and Abstraction
•   Factorization and Specialization
•   Inclusion
•   Benefits of Inheritance
•   Uses for inheritance



14. Software Design - Primary Consideration (1:04:43)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

    •   What's Design?
    •   Example Designs in Real Life
    •   Programs
    •   Example Designs in Real Life
    •   Design in Software Engineering
    •   Examples of Process Design
    •   What is covered in Product Design?
    •   From Analysis to Design
    •   Factors To be considered in Design
    •   Factors to be considered in Design
    •   Process of Complex System Design
    •   Top-down Vs. Bottom-up Approach
    •   Decomposition
    •   Composition/Interconnection
    •   Basic Principles To be applied during design
    •   Abstraction
    •   Example Abstractions
    •   Describing Abstractions
    •   Encapsulation
    •   Refinement
    •   Refinement and Change Process
    •   Communication
    •   Other Kinds of Communication



                                                       x
Software Defects Prevention Techniques – Example Project


15. Design Patterns (56:13)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Reuse in Software Engineering
   •   Patterns in Software Engineering
   •   Design Patterns
   •   Describing a Design Pattern
   •   Pattern Description Template provided by
   •   Classification of Patterns
   •   Examples of Creational Patterns
   •   Behavioral Patterns
   •   A Problem
   •   The Solution
   •   The Design Pattern: Prototype
   •   Singleton Pattern
   •   Implementing Singleton
   •   Adapter Pattern
   •   Composite Pattern
   •   The Solution
   •   Instance Structure for an Instance of a Composite Class
   •   The Composite Pattern
   •   The Facade Pattern
   •   How to interact with components with a subsystem?
   •   The Facade Pattern
   •   Proxy Pattern: A Mechanic for Communication
   •   Real object and Proxy object are different
   •   The Proxy Pattern
   •   The Decorator Pattern: Object Diagram
   •   Visual Component
   •   The Template Method Pattern
   •   Strategy Pattern


16. Class and Component Level Design (54:34)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Class
   •   Example Classes
   •   Kinds of Classes
   •   Levels of Abstraction
   •   Beck and Cunningham's CRC Method
   •   CRC: our recommendation
   •   A system decomposed in CRCs
   •   Contributions of CRC
   •   Bertrand Meyer' Design-by-Contract
   •   Design by Contact Method
   •   Contracts
   •   An Example Contact for class Book




                                                      xi
Zarko Acimovic


    •   A Contact Specification
    •   Class Design
    •   Part-Whole Design
    •   Odell's Classification Criteria
    •   Component-Integral Object
    •   Material-Object (made of)
    •   Portion-Object
    •   Place-Area
    •   Member-Bunch
    •   Member-Partnership
    •   Non-aggregation relations
    •   Transitivity in Part-Whole
    •   Two Kinds of Part-whole Relations in UML
    •   Designing New Subclasses From Old: Inheritance
    •   Use of Inheritance in a Subclass
    •   Components
    •   Use of Inheritance in a Subclass
    •   Components
    •   Design of Components
    •   Decisions about component's non-functional properties
    •   Reuse in Component Technologies



17. Architectural Design (59:28)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Software Architecture
•   Why Do We need Architecture?
•   Basic Principles applied by Architects
•   Several Approaches to Architecture
•   The Zachman Framework
•   Open Distributed Processing Reference Model (ODP-RM)
•   ODP: Enterprise viewpoint
•   ODP: Information viewpoint
•   ODP: Computational viewpoint
•   ODP: Computation viewpoint
•   ODP: Engineering viewpoint
•   ODP: Transparencies
•   ODP: Transparencies Defined
•   4+1 View Model
•   Unified Process Model of Architecture
•   Commonly occurring Architectural Patterns
•   Layers
•   Peers
•   Client-server
•   Pipelines
•   Transactional Flows



                                                  xii
Software Defects Prevention Techniques – Example Project


•   Filters
•   Blankboards
•   Facade
•   Broker
•   MVC
•   Microkernel
•   Framework Architectures
•   A Framework
•   References/Readings



18. Software Testing - I (55:39)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Why Testing?
•   A Test Case
•   What criteria to use?
•   Black Box Testing
•   White Box Testing
•   Levels of Testing
•   Stub Modules
•   Test Drivers
•   Test Drivers during Partial Integration
•   Testing Modules with Top Down Integration
•   Testing Modules with Bottom Up Integration
•   Regression Testing
•   Monitoring Behavior of Programs
•   Documentation Probes
•   Standard Error Probes and Exceptions (user defined)
•   Assertions for defensive programming
•   Different Types of Assertions
•   IS the output of a test correct?
•   Test Objectives
•   Alpha testing and Beta testing
•   Debugging
•   Testing In Software Development



19. Software Testing - II (51:18)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Black box vs. white box testing
•   Black Box Testing (External)
•   White Box Testing (Internal)
•   Statement Coverage
•   An Example for Statement Coverage
•   Observations



                                                      xiii
Zarko Acimovic


•   An Example for Statement Coverage
•   Observations
•   Implicit statements
•   Basic Path Testing
•   A Sequential Composition
•   A Branching Statement
•   A While Statement
•   A Repeat Statement
•   A Switch Case Statement
•   A Compound Condition
•   Cyclomatic Complexity
•   Cyclomatic Complexity Example
•   Condition Testing
•   Condition Testing Strategies
•   Data Flow Testing Strategies
•   Exercise: Try different strategies on the below program




20. Structural Programming and Some implementation (45:05)
http://nptel.iitm.ac.in/video.php?subjectId=106101061


21. Software Metrics and Quality (54:51)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Why Measurement?
•   Use of Software Measurement
•   The attributes that can be captured
•   Which one is a good measure?
•   What to measure in software?
•   Measurement Scales
•   Ordinal Scale
•   Interval Scale
•   Ratio Scale
•   Absolute Scale
•   Size Metrics
•   Length
•   Functionality
•   Complexity
•   Measuring Structure
•   Coupling and cohesion
•   Object Oriented Metrics: CK and MOOD
•   Quality Guidelines for Coding and Development
•   Defensive Programming for Modules, Functions, Procedures, Classes
•   Preconditions
•   Invariants



                                                     xiv
Software Defects Prevention Techniques – Example Project


•   Use of Software Measurement
•   Separate Compilation
•   Makefile
•   Separate Compilation
•   Makefile
•   A Sample Makefile
•   Code organization
•   Development
•   Some good practices


22. Verification and Validation (52:43)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Verification vs validation
•   The V & V process
•   V & V goals
•   V & V confidence
•   Static and dynamic verification
•   Program testing
•   Types of testing
•   Testing and debugging
•   The debugging process
•   V & V planning
•   V-model of development
•   The Structure of a software test plan
•   Software inspections
•   Inspection success
•   Inspections testing
•   Program inspections
•   Inspection pre-conditions
•   Inspection procedure
•   Inspection Roles
•   Inspection Checklists (2)
•   Inspection Checklists (3)
•   Inspection rate
•   Automated static analysis
•   Static Analysis Checks
•   Stages of static analysis
•   LINT static analysis
•   Verification and formal methods
•   Arguments for formal methods


23. Case Study (54:55)
 http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Case study: library book circulation system
•   BOOK CIRCULATION



                                                       xv
Zarko Acimovic


•   STATEMENT OF PROJECT SCOPE AND OBJECTIVES
•   THE FEASIBILITY STUDY: CIRCULATION
•   Financial analysis for alternatives 1 :
•   Alternatives 2
•   Plan for alternatives 1
•   Feasibility ...
•   Requirements Analysis
•   Circulation System
•   Draw first level DFD
•   Requirements Analysis



24. Case Study (58:39)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Requirements Analysis...
•   Refinement of issue process
•   Requirements Analysis...
•   Requirements Specification...
•   SRS ...
•   System Design: CIRCULATION
•   System Design ...
•   System Design
•   E-R DIAGRAM
•   System Design ...
•   Table Design
•   Physical DB Design
•   Physical DB Design...
•   Physical DB Design...
•   System Design ...
•   Software Architecture
•   Software Architecture...
•   Implementation Schedule
•   Implementation Schedule...
•   Design documentation
•   Detailed Design
•   Data and Module Specification
•   Module ...
•   Implementation


25. Software Evolution (55:41)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

    •   Software Change
    •   Software change control
    •   Software change strategies
    •   Program evolution dynamics



                                                   xvi
Software Defects Prevention Techniques – Example Project


    •   Laws of Program Evolution
    •   Applicability of Lehman's laws
    •   Software maintenance
    •   Maintenance is inevitable
    •   Causes of maintenance
    •   Distribution of maintenance effort
    •   Types of Maintenance
    •   Breakup of costs
    •   Spiral maintenance model
    •   Maintenance costs
    •   Maintenance costs factors
    •   Problems facing Maintainers
    •   Approaches to Maintenance
    •   The Change process
    •   Change requests
    •   Change implementation
    •   Maintenance prediction
    •   Change prediction
    •   Complexity metrics
    •   Process metrics


26. Agile Development (55:33)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Objectives
•   Requirements
•   Characteristics of Agile Processes
•   An iterative development process
•   Advantages of incremental development
•   Problems with incremental development
•   Prototyping
•   Software prototyping
•   Benefits of prototyping
•   Throw -away prototypes
•   Incremental Development & Prototyping
•   Conflicting objectives
•   Agile methods
•   Principles of Agile Methods
•   Problems with agile methods
•   Extreme programming
•   The Four Core Values of XP
•   Communication
•   Feedback
•   Courage
•   The XP release cycle
•   XP Practices
•   XP Practices - 2



                                                      xvii
Zarko Acimovic


•   XP and agile principles
•   Requirements scenarios
•   Story Card for document downloading
•   XP Design Guidelines
•   XP and change
•   Testing in XP
•   Task cards for document downloading
•   Test Case Description
•   Test- first development
•   Pair programming
•   XP Summary




27. Software Reuse (53:43)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Design with Reuse
•   Objectives
•   Software reuse
•   Benefits of reuse
•   Requirements for design with reuse
•   Reuse problems
•   Generator-based reuse
•   Types of program generator
•   Reuse through program generation
•   Component-based development
•   Components
•   Component abstractions
•   CBSE processes
•   An opportunistic reuse process
•   Development with reuse
•   CBSE problems
•   Application frameworks
•   Framework classes
•   Extending frameworks



28. Reuse Continued (57:07)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Application frameworks
•   Framework classes
•   Extending frameworks
•   Evaluating Frameworks
•   Framework evaluation criteria



                                                  xviii
Software Defects Prevention Techniques – Example Project


•   Evaluating Frameworks
•   COTS product reuse
•   Integration Approaches
•   Examples of COTS muse
•   COTS system integration problems
•   Component development for reuse
•   Reusable components
•   Re-usability enhancement
•   Generalization Techniques
•   Generating good mental Models
•   Application families
•   Application family specialization
•   Inventory management systems
•   Application family architectures
•   A library system
•   Library system
•   Family member development
•   Design patterns
•   The Observer pattern


29. Introduction to Project Management (52:36)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   What is Project Management ?
•   Who Executes a Project?
•   An Effective PM Needs to Do the Following:
•   Productivity Gains With Standards and Procedures
•   Software Process is a Part of Organizational Process
•   Software Project Phases and Activities
•   Software Development Strategies at a Glance
•   Project Management Process Groups: Schematic
•   Illustration: Interaction Within and Across Project
•   Software Development Methodology: Schematic
•   PMBOK (2000)
•   Framework for Project Management
•   PMI Developed Code Of Ethics (1/2)
•   Impact of Good Project Management
•   Software Project Management
•   Suggested Readings




                                                       xix
Zarko Acimovic


30. Project Scope Management (1:08:45)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Scope Management Subprocesses
•   Illustrative Comparison of Projects
•   Another Way of Comparing Projects:
•   PM Must Question ALL Aspects of a Project
•   Illustration: Stakeholder Analysis
•   Illustration: Objectives of a Hospital IS
•   Illustration: Project Charter (1/3)
•   Illustration: Project Charter (2/3)
•   Illustration: Project Charter (3/3)
•   Illustration: WBS Organized by phases
•   Summary: Scope management Subprocesses


31. Project Time Management (56:51)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Project Time Management Subprocesses
•   WBS to Precedence Relationship
•   Precedence Diagramming Method (PDM): Types of Dependencies
•   Illustration: PDM Network
•   Illustration: Arrow Diagramming Method (ADM) Network
•   Precedence Relationship to Schedule
•   Schedule Development Preferences
•   Illustration of a Schedule
•   Software Support for Project Management
•   Summary: Time Management Process



32. Estimation - I (51:42)
http://nptel.iitm.ac.in/video.php?subjectId=106101061

•   Estimation is an Ongoing Activity
•   Stages in Project Estimation
•   Estimation Approaches
•   PERT Sizing Approach to Estimation
•   Estimation: Levels of Application
•   Function Point Counting Procedure
•   Components of FP Count
•   FP for Average Complexity Functions




                                                  xx
Software Defects Prevention Techniques – Example Project


33. Estimation - II (50:38)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Marketing MIS: data flow diagram
   •   General Systems Characteristics (GSCs)
   •   Value Adjustment Factor (VAF)
   •   GSC and FPC: Marketing MIS
   •   Marketing MIS: Cost and Price
   •   COnstructive COst MOdel (COCOMO): Intd.
   •   Marketing MIS Modules
   •   Marketing MIS: Pert sizing
   •   COCOMO Equations
   •   COCOMO Cost Drivers (1/2)
   •   COCOMO Cost Drivers (2/2)
   •   Cost Driver Effort Multipliers
   •   Effort Multipliers: Marketing MIS
   •   Marketing MIS: COCOMO Calculations
   •   Effort and Schedule Distribution by Phase (%)
   •   Marketing MIS: Phase Effort and Schedule
   •   Network Precedence: Marketing MIS
   •   Effort Distribution by Activity: Marketing MIS
   •   Critical Path marketing MIS
   •   Gantt Chart/Histogram:Marketing MIS


34. Project Quality Management (58:32)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Definitions of Quality (1/2)
   •   Definitions of Quality (2/2)
   •   Quality Management Gurus
   •   Modern Quality Management Emphasizes on:
   •   Project Quality Management Subprocess
   •   Quality Policy
   •   Strategic Planning for Quality
   •   Quality Characteristics: Illustration
   •   Boehm's Description of Quality
   •   Quality Measurements are Used for:
   •   Illustration: Template for Usability
   •   Quality Benchmarking
   •   Cost of Quality
   •   Quality Planning Process: Outputs
   •   What is Quality Assurance?
   •   Main Goals of Quality Assurance:
   •   Role of QA During Development (1/2)
   •   VV&T Activities in SW Project (1/3)
   •   VV&T Activities in SW Project (2/3)
   •   VV&T Activities in SW Project (3/3)
   •   Opportunity for Improvement (OFI)


                                                     xxi
Zarko Acimovic


   •   Who Identifies OFI?
   •   Improvement in Practice and Documentation
   •   Quality Control Process
   •   QC is Performed...
   •   Pareto Chart: Illustration
   •   Control Chart: Schematic


35. Quality Management Systems - I (54:43)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061


36. Quality Management Systems (54:53)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Who is a Process?
   •   Process Capability and Maturity
   •   Concept of Maturity Level
   •   Capability Maturity Models (CMM)
   •   Some of the Existing CMMs
   •   Capability Maturity Model Integrated (CMMI)
   •   CMMI ls Tailorable
   •   Staged Model: Maturity Levels
   •   Maturity level Structure
   •   Structure of Staged Representation
   •   PA Level 2
   •   PA Level 3
   •   PA Level 4
   •   PA Level 5
   •   Process Visibility with levels
   •   Process Capability with Levels
   •   Continuous Representation
   •   Structure of Continuous Representation
   •   PAs in Staged Representation
   •   Capability and Maturity levels
   •   Progression in Staged model
   •   Progression in Continuous model
   •   When to chose continuous Representation?
   •   implementation Road Map




                                                  xxii
Software Defects Prevention Techniques – Example Project


37. Project Configuration Management (53:00)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Change Control System: Schematic
   •   What is Configuration Management(CM)?
   •   CM Functions
   •   Typical Application Specific Cls
   •   Versioning of Cls
   •   Concept of Baseline
   •   Configuration Control
   •   Change Control Procedure (1/2)
   •   Change Control Procedure (2/2)
   •   Configuration Status Accounting
   •   Configuration Audit
   •   Configuration Management Plan

38. Project Risk Management (56:04)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Project Risk Management Processes
   •   Risk Management Planning Process
   •   Risk Manage. Planning Process: Outputs
   •   Risk identification Process Involves:
   •   Risk Analysis Processes
   •   Qualitative Risk Analysis Process
   •   Illustration: Risk Impact Rating Table
   •   Impact, Frequency, and Risk Exposure
   •   Illustration: Quantitative Risk Analysis
   •   Risk Response Planning Process (2/2)
   •   Lessening the Risks
   •   Contingency Actions
   •   Risk Monitoring and Control Process
   •   Illustration: Tracking The Top 10 Risks



39. Other PM Processes (55:41)
    http://nptel.iitm.ac.in/video.php?subjectId=106101061

   •   Other Project Management Processes
   •   Project Cost Management Processes
   •   Illustration: Cost Budget (1/2)
   •   Illustration: Cost Budget (2/2)
   •   Human Resource Management Processes
   •   Impact of Organization Structure on Projects
   •   Typical Software Project Organization
   •   Software Development Responsibilities Need to be shared by all stakeholders
   •   Illustration: Responsibility Assignment Matrix
   •   Project Communications Management Processes
   •   Illustration: Stakeholder Communications Analysis


                                                    xxiii
Zarko Acimovic



        •    Project Reporting and Review: Schematic
        •    Administrative Closure Process Covers:
        •    Administrative Closure Process Outputs
        •    Project Procurement Management Processes
        •    Project Integration Management Involves:
        •    Outputs from Project Plan Process: Uses
        •    Objectives of Overall Change Control Process
        •    Integrated Change Control Involves:
        •    Organizational Learning
        •    Role of PM
        •    Important Skills for Project Manager
        •    Engineers vs. Managers




                     2 AUTOMATIC TOOLS FOR DEFECT PREVENTION

Prototyping (modeling) defect prevention method has efficiency 52%. Before implementing this method defect
potential per 1 FP (function point) was 5, after, 2.4.
Tool: ArgoUML



Static analysis of source code defect prevention method has efficiency 44%. Defect potential per 1 FP was 5, after
implementing this method is 2.8.
Tool: Coverity



Mathematical test case design defect prevention efficiency was 34%. Defect potential per 1 FP is 5, after is 3.3.
Tool: Bullseye



Bonus: Root cause analysis 1044-1993 - IEEE Standard Classification for Software Anomalies. Efficiency 41% -
Before 5 – After 2.95



Source: Chapter 3. Estimating and Measuring Software Quality. The Economics of Software Quality, ISBN:
9780132564762 , Capers Jones, Olivier Bonsignour

http://www.amazon.com/Economics-Software-Quality-Capers-Jones/dp/0132582201
http://www.informit.com/store/product.aspx?isbn=0132582201




                                                          xxiv
Software Defects Prevention Techniques – Example Project


       3 TOOLS FOR DEFECT PREVENTION IN JAVA SOFTWARE PROJECTS

Source: http://codedependents.com/2009/07/01/top-5-static-analysis-plugins-for-eclipse/



Code Coverage tool EclEmma http://www.eclemma.org/

Byte Code Analysis FindBugs http://findbugs.sourceforge.net/

Code Complexity Analysis http://www.stateofflow.com/projects/16/eclipsemetrics

Dependency Analysis JDepend4Eclipse http://andrei.gmxhome.de/jdepend4eclipse/

Source Code Analysis PMD http://pmd.sourceforge.net/




                                4 SAMPLE PROJECT SPECIFICATION

Project duration 3 months, single developer , 5000 lines of code (including comments), 15 Java 2 Micro Edition
classes



Tools used: Sun J2ME Wireless Toolkit, Eclipse, IBM WebSphere Device Developer 5.5, CVS, Motorola and Nokia
phone emulators and SDKs. Technology: J2ME, MIDP 2.0, CLDC 1.1.


Device-independent Java 2 Micro Edition (J2ME) midlet, executable in any emulator or mobile device, for displaying
map with scale, following moving objects, zoom in-out and pan, selection of location , measuring distance, following
individual or vehicle on map with route presentation, presentation of waypoints on map, presentation of list of
existing waypoints (sorted by name, type, distance) for selecting destination or editing and deletion, creating, editing
and deletion of waypoint – points with coordinates, name, type, icon; coordinates are defined by current position,
selected location on map or inserted in textual form, selection of waypoint as destination and navigation towards that
destination. Some classes implemented: MapBackground, MapObject, Point, SelectorPoint, PVector, MapsMIDlet

Project demo web site: https://sites.google.com/site/j2memaps/




                                                            xxv
Zarko Acimovic


    5 PMD, FINDBUGS AND STATEOFFLOW VIOLATIONS IN SOURCE CODE


Here are the violations detected in CommaHyphenString.java Description/ Line/ Type of tool


 Description                                                                                     Line        Type
 All classes and interfaces must belong to a named package                                               9   PMD Marker
 Unused field: CommaHyphenString.lastIndex                                                              12   FindBugs
 Use explicit scoping instead of the default package private level                                      12   PMD Marker
 Document empty constructor                                                                             13   PMD Marker
 Lines of Code in Method is 27                                                                          16   Metrics Marker
 Number of Statements is 28                                                                             16   Metrics Marker
 Avoid variables with short names like s                                                                19   PMD Marker
 Parameter 's' is not assigned and could be declared final                                              19   PMD Marker
 Use explicit scoping instead of the default package private level                                      19   PMD Marker
 Local variable 'lastIndex' could be declared final                                                     20   PMD Marker
 Avoid variables with short names like ss                                                               22   PMD Marker
 A method should have only one exit point, and that should be the last statement in the method          24   PMD Marker
 Avoid variables with short names like v                                                                27   PMD Marker
 Consider replacing this Vector with the newer java.util.List                                           27   PMD Marker
 Local variable 'v' could be declared final                                                             27   PMD Marker
 Use ArrayList instead of Vector                                                                        27   PMD Marker
 Avoid variables with short names like ss                                                               35   PMD Marker
 Lines of Code in Method is 16                                                                          44   Metrics Marker
 Avoid variables with short names like s                                                                47   PMD Marker
 Parameter 's' is not assigned and could be declared final                                              47   PMD Marker
 Use explicit scoping instead of the default package private level                                      47   PMD Marker
 Avoid using if statements without curly braces                                                         53   PMD Marker
 CommaHyphenString.getStringsOnly(String) concatenates strings using + in a loop                        54   FindBugs
 Prefer StringBuffer over += for concatenating strings                                                  54   PMD Marker
 Parameter 's' is not assigned and could be declared final                                              65   PMD Marker
 Use explicit scoping instead of the default package private level                                      65   PMD Marker



Here is the CommaHyphenString.java source code

        1   /**
        2    *
        3    * CommaHyphenString parses .properties file. It eliminates commas or low
lines
     4   * from .properties file so items in it( such as categories) could be
properly
     5   * showed on screen
     6   */
     7 import java.util.*;
     8



                                                                  xxvi
Software Defects Prevention Techniques – Example Project


 9   public class CommaHyphenString {
10
11          //String s;
12          int lastIndex;
13          CommaHyphenString(){}
14
15
16     /** Eliminates commas, returns array of strings with low line
17      * @return String[]
18      */
19          String[] getWithLowLine(String s) {
20                  int lastIndex = defineLast(s);
21                  if(lastIndex==0){
22                           String[] ss = new String[1];
23                           ss[0] = s;
24                           return ss;
25                  } else {
26                           int start = -1;
27                           Vector v = new Vector();
28                           int current = s.indexOf(',');
29                           do {
30                                   v.addElement(s.substring(start+1,current));
31                                   start = current;
32                                   current = s.indexOf(',',current+1);
33                           } while (start!=lastIndex);
34
35                              String[] ss = new String[v.size()+1];
36                              for(int i=0; i<v.size(); i++){
37                                      ss[i] = (String)v.elementAt(i);
38                              }
39                              ss[v.size()] = s.substring(lastIndex+1,s.length());
40                              return ss;
41                  }
42          }
43
44     /** Eliminates low line
45      * @return String[]
46      */
47      String[] getStringsOnly(String s){
48          String[] temp = this.getWithLowLine(s);
49          for (int i=0; i<temp.length; i++){
50                  char[] tempChar = temp[i].toCharArray();
51                  String k = "";
52                  for (int j=0; j<tempChar.length; j++){
53                          if(tempChar[j]=='_') tempChar[j]=' ';
54                          k+=tempChar[j];
55                  }
56                  temp[i] = k;
57          }
58          return temp;
59      }


                                             xxvii
Zarko Acimovic


60
61
62       /** Returns categories with low line
63        * @return String[]
64        */
65        String[] getCategoriesHyphen(String s){
66            return this.getWithLowLine(s);
67        }
68
69       /** Returns categories
70        * @return String[]
71        */
72        String[] getCategories(String s){
73            return this.getStringsOnly(s);
74        }
75
76       /** Defines index of last comma in string
77        * @return integer
78        */
79        public int defineLast(String s){
80            int lastIndex = 0;
81            char c[] = s.toCharArray();
82                    for (int i=0; i<c.length; i++){
83                            if(c[i]==',') lastIndex=i;
84                    }
85                    return lastIndex;
86        }
87
88   }




                                      xxviii
Software Defects Prevention Techniques – Example Project


CompassCanvas.java violations


 All classes and interfaces must belong to a named package                                      10   PMD Marker
 Lack of Cohesion in Methods (Henderson-Sellers) is 75%                                         10   Metrics Marker
 Lack of Cohesion in Methods (Total Correlation) is 1,668%                                      10   Metrics Marker
 Number of Fields is 23                                                                         10   Metrics Marker
 The class 'CompassCanvas' has a Cyclomatic Complexity of 6 (Highest = 17).                     10   PMD Marker
 To be compliant to J2EE, a webapp should not use any thread.                                   10   PMD Marker
 Too many fields                                                                                10   PMD Marker

 Found non-transient, non-static member. Please mark as transient or provide accessors.         11   PMD Marker
 Use explicit scoping instead of the default package private level                              11   PMD Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.         12   PMD Marker
 Use explicit scoping instead of the default package private level                              12   PMD Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.         13   PMD Marker
 Use explicit scoping instead of the default package private level                              13   PMD Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.         14   PMD Marker
 Use explicit scoping instead of the default package private level                              14   PMD Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.         15   PMD Marker
 Use explicit scoping instead of the default package private level                              15   PMD Marker
 Avoid variables with short names like c                                                        18   PMD Marker
 Unused field: CompassCanvas.c                                                                  18   FindBugs
 Avoid variables with short names like t                                                        20   PMD Marker
 To be compliant to J2EE, a webapp should not use any thread.                                   20   PMD Marker
 Unread field: CompassCanvas.switchVar                                                          22   FindBugs
 Unread field: CompassCanvas.switched                                                           23   FindBugs
 It is a good practice to call super() in a constructor                                         38   PMD Marker
 Lines of Code in Method is 24                                                                  38   Metrics Marker
 Number of Statements is 33                                                                     38   Metrics Marker
 Parameter 'mob' is not assigned and could be declared final                                    38   PMD Marker
 Avoid empty catch blocks                                                                       53   PMD Marker
 Avoid empty catch blocks                                                                       57   PMD Marker
 To be compliant to J2EE, a webapp should not use any thread.                                   59   PMD Marker
 Avoid really long methods.                                                                     63   PMD Marker
 Avoid variables with short names like g                                                        63   PMD Marker
 Cyclomatic Complexity is 10                                                                    63   Metrics Marker
 Lines of Code in Method is 220                                                                 63   Metrics Marker
 Number of Statements is 418                                                                    63   Metrics Marker
 Parameter 'g' is not assigned and could be declared final                                      63   PMD Marker
 The method 'paint' has a Cyclomatic Complexity of 17.                                          63   PMD Marker
 The method paint() has an NCSS count of 144                                                    63   PMD Marker
 The method paint() has an NPath complexity of 4375                                             63   PMD Marker
 Avoid unnecessary comparisons in boolean expressions                                           68   PMD Marker




                                                               xxix
Zarko Acimovic




CompassCanvas.java violations - continued


 Avoid unused local variables such as 'mediumX'.                    122   PMD Marker
 Dead store to mediumX in CompassCanvas.paint(Graphics)             122   FindBugs
 The local variable mediumX is never read                           122   Java Problem
 Avoid unused local variables such as 'mediumY'.                    123   PMD Marker
 Dead store to mediumY in CompassCanvas.paint(Graphics)             123   FindBugs
 The local variable mediumY is never read                           123   Java Problem
 Avoid unnecessary comparisons in boolean expressions               285   PMD Marker




CompassCanvas.java source code


     1   /**
     2    *
     3    * ComapssCanvas draws compass on screen
     4    */
     5   import javax.microedition.lcdui.*;
     6   //import javax.microedition.midlet.*;
     7
     8
     9
    10   public class CompassCanvas extends Canvas implements Runnable{
    11           long north;
    12           long south;
    13           long east;
    14           long west;
    15           int bigRadius;
    16           int smallRadius;
    17           int smallestRadius;
    18           Coordinates c;
    19           long delta = 0;
    20           Thread t;
    21           boolean end = false;
    22           boolean switchVar = false;
    23           boolean switched = false;
    24           MapObjects mob;
    25
    26             int dummy1 = 0;
    27             int dummy2 = 0;
    28             int dummy3 = 0;



                                                  xxx
Software Defects Prevention Techniques – Example Project


    29          int dummy4 = 0;
    30          Image img;
    31
    32          Image imgDest;
    33          long destUp;
    34          long destDown;
    35          long gama;
    36
    37
    38          CompassCanvas(MapObjects mob){
    39             this.mob = mob;
    40             north = MathFP.toFP("0");
    41             south = MathFP.div(Coordinates.MathFP_2PI,MathFP.toFP("2"));
    42             east = MathFP.mul(Coordinates.MathFP_2PI,MathFP.toFP("0.25"));
    43             west = MathFP.mul(Coordinates.MathFP_2PI,MathFP.toFP("0.75"));
    44
    45             destUp = MathFP.toFP("0");
    46             destDown = MathFP.div(Coordinates.MathFP_2PI,MathFP.toFP("2"));
    47
    48             bigRadius = Math.min(this.getWidth(),this.getHeight());
    49             smallRadius = (int)(0.75*bigRadius);
    50             smallestRadius = (int)(0.37*bigRadius);
    51             try{
    52                     img = Image.createImage("Arrow2.jpg");
    53             }catch(Exception e){}
    54
    55              try{
    56                     imgDest = Image.createImage("Dest.jpg");
    57             }catch(Exception e){}
    58
    59             t = new Thread(this);
    60             t.start();
    61          }
    62
    63          public void paint(Graphics g){
    64                  //System.out.println("delta="+MathFP.toString(delta));
    65                  g.setColor(255,255,255);
    66                  g.fillRect(0,0,this.getWidth(),this.getHeight());
    67                  g.setColor(0,0,0);
    68                  if(end == false){
    69                           g.drawImage(img,75,25,0);
    70
    71
//System.out.println("this.getWidth()="+this.getWidth());
    72
//System.out.println("this.getHeight()="+this.getHeight());
    73                           g.drawArc(8,0,bigRadius,bigRadius,0,360);
    74                           g.drawArc(30,22,smallRadius,smallRadius,0,360);
    75




                                                xxxi
Zarko Acimovic


    76                          String sx =
MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(Ma
thFP.sub(north,delta)))));
    77                          String sy =
MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(Ma
thFP.sub(north,delta)))));
    78                          int ix = sx.indexOf('.');
    79                          sx = sx.substring(0,ix);
    80                          int iy = sy.indexOf('.');
    81                          sy = sy.substring(0,iy);
    82
    83                          int x = Integer.parseInt(sx);
    84                          int y = Integer.parseInt(sy);
    85
    86                          String s9 =
MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(smallestRadius),M
athFP.sin(MathFP.sub(north,delta)))));
    87                          ix = s9.indexOf('.');
    88                          s9 = s9.substring(0,ix);
    89                          int NX = Integer.parseInt(s9);
    90                          String s10 =
MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),M
athFP.cos(MathFP.sub(north,delta)))));
    91                          iy = s10.indexOf('.');
    92                          s10 = s10.substring(0,iy);
    93                          int NY = Integer.parseInt(s10);
    94
    95                          g.drawString("N",x,y,0);
    96
    97                          sx =
MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(Ma
thFP.sub(south,delta)))));
    98                          sy =
MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(Ma
thFP.sub(south,delta)))));
    99                          ix = sx.indexOf('.');
   100                          sx = sx.substring(0,ix);
   101                          iy = sy.indexOf('.');
   102                          sy = sy.substring(0,iy);
   103
   104                          x = Integer.parseInt(sx);
   105                          y = Integer.parseInt(sy);
   106
   107                          String s11 =
MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(smallestRadius),M
athFP.sin(MathFP.sub(south,delta)))));
   108                          ix = s11.indexOf('.');
   109                          s11 = s11.substring(0,ix);
   110                          int SX = Integer.parseInt(s11);




                                        xxxii
Software Defects Prevention Techniques – Example Project


   111                          String s12 =
MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),M
athFP.cos(MathFP.sub(south,delta)))));
   112                          iy = s12.indexOf('.');
   113                          s12 = s12.substring(0,iy);
   114                          int SY = Integer.parseInt(s12);
   115
   116
   117
   118                          g.drawString("S",x,y,0);
   119                          int del = 0;
   120                          g.drawLine(NX-del,NY-del,SX-del,SY-del);
   121
   122                          int mediumX = (int)Math.abs((NX-SX)/2);
   123                          int mediumY = (int)Math.abs((NY-SY)/2);
   124
   125                          String s1 =
MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(10),MathFP.sin(Ma
thFP.sub(east,delta)))));
   126                          String s2 =
MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(10),MathFP.cos(Ma
thFP.sub(east,delta)))));
   127
   128                          String s3 =
MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(10),MathFP.sin(Ma
thFP.sub(west,delta)))));
   129                          String s4 =
MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(10),MathFP.cos(Ma
thFP.sub(west,delta)))));
   130
   131                          ix = s1.indexOf('.');
   132                          s1 = s1.substring(0,ix);
   133                          dummy1 = Integer.parseInt(s1);
   134
   135                          ix = s2.indexOf('.');
   136                          s2 = s2.substring(0,ix);
   137                          dummy2 = Integer.parseInt(s2);
   138
   139                          ix = s3.indexOf('.');
   140                          s3 = s3.substring(0,ix);
   141                          dummy3 = Integer.parseInt(s3);
   142
   143                          ix = s4.indexOf('.');
   144                          s4 = s4.substring(0,ix);
   145                          dummy4 = Integer.parseInt(s4);
   146
   147                          g.drawLine(NX-del,NY-del,dummy1,dummy2);
   148                          g.drawLine(dummy1,dummy2,SX-del,SY-del);
   149                          g.drawLine(NX-del,NY-del,dummy3,dummy4);
   150                          g.drawLine(dummy3,dummy4,SX-del,SY-del);
   151


                                                xxxiii
Zarko Acimovic


   152                          sx =
MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(Ma
thFP.sub(east,delta)))));
   153                          sy =
MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(Ma
thFP.sub(east,delta)))));
   154                          ix = sx.indexOf('.');
   155                          sx = sx.substring(0,ix);
   156                          iy = sy.indexOf('.');
   157                          sy = sy.substring(0,iy);
   158
   159                          x = Integer.parseInt(sx);
   160                          y = Integer.parseInt(sy);
   161
   162                          g.drawString("E",x,y,0);
   163
   164                          sx =
MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(Ma
thFP.sub(west,delta)))));
   165                          sy =
MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(Ma
thFP.sub(west,delta)))));
   166                          ix = sx.indexOf('.');
   167                          sx = sx.substring(0,ix);
   168                          iy = sy.indexOf('.');
   169                          sy = sy.substring(0,iy);
   170
   171                          x = Integer.parseInt(sx);
   172                          y = Integer.parseInt(sy);
   173
   174                          g.drawString("W",x,y,0);
   175
   176
   177
   178
   179                          gama = MathFP.sub(delta,gama);
   180                          //gama = MathFP.toFP("314");
   181                          long gamaDegrees =
Coordinates.radiansToDegrees(gama);
   182                          //long gamaDegrees = gama;
   183
//System.out.println("gama="+MathFP.toString(gamaDegrees));
   184                          //gama = Coordinates.degreesToRadians(gama);
   185
   186                          long corrX =
MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(smallestRadius),MathFP.sin(MathFP
.sub(destUp,gama))));
   187                          long corrY =
MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),MathFP.cos(MathFP
.sub(destUp,gama))));
   188


                                        xxxiv
Software Defects Prevention Techniques – Example Project


   189                           long dx = 0;
   190                           long dy = 0;
   191
   192                           if(gamaDegrees<=0) {
   193                                   gama =
MathFP.add(gama,Coordinates.MathFP_2PI);
   194                                   gamaDegrees =
MathFP.add(gamaDegrees,MathFP.toFP("360"));
   195                           }
   196
   197                           // Correction of position for imgDest
   198                           if(MathFP.toFP("0")<=gamaDegrees && gamaDegrees
<MathFP.toFP("10")){
   199                                   dx = 0-
MathFP.mul(MathFP.toFP("10"),MathFP.cos(gama));
   200                                   dy = 0-
MathFP.mul(MathFP.toFP("23"),MathFP.cos(gama));
   201                           }
   202
   203
   204                           if(MathFP.toFP("10")<=gamaDegrees && gamaDegrees
<MathFP.toFP("50")){
   205                                   dx = 0-
MathFP.mul(MathFP.toFP("25"),MathFP.cos(gama));
   206                                   dy = 0-
MathFP.mul(MathFP.toFP("23"),MathFP.cos(gama));
   207                           }
   208
   209                           if(MathFP.toFP("50")<=gamaDegrees && gamaDegrees
<MathFP.toFP("67")){
   210                                   dx = 0-
MathFP.mul(MathFP.toFP("40"),MathFP.cos(gama));
   211                                   dy = 0-
MathFP.mul(MathFP.toFP("30"),MathFP.cos(gama));
   212                           }
   213
   214                           if(MathFP.toFP("67")<=gamaDegrees && gamaDegrees
<MathFP.toFP("85")){
   215                                   dx = 0-
MathFP.mul(MathFP.toFP("25"),MathFP.sin(gama));
   216                                   dy = 0-
MathFP.mul(MathFP.toFP("12"),MathFP.sin(gama));
   217                           }
   218
   219                           if(MathFP.toFP("85")<=gamaDegrees &&
gamaDegrees<MathFP.toFP("175")){
   220                                   dx = 0-
MathFP.mul(MathFP.toFP("25"),MathFP.sin(gama));
   221                                   dy = 0-
MathFP.mul(MathFP.toFP("12"),MathFP.sin(gama));
   222                           }


                                                xxxv
Zarko Acimovic


   223
   224
   225                           if(MathFP.toFP("175")<=gamaDegrees   &&
gamaDegrees<MathFP.toFP("275")){
   226                                   dx =
MathFP.mul(MathFP.toFP("7"),MathFP.cos(gama));
   227                                   dy =
MathFP.mul(MathFP.toFP("7"),MathFP.sin(gama));
   228                           }
   229
   230                           if(MathFP.toFP("275")<=gamaDegrees   &&
gamaDegrees<=MathFP.toFP("360")){
   231                                   dx = 0-
MathFP.mul(MathFP.toFP("8"),MathFP.cos(gama));
   232                                   dy = 0-
MathFP.mul(MathFP.toFP("25"),MathFP.cos(gama));
   233
   234                           }
   235
   236
   237
   238
   239                           long prevCorrX=corrX;
   240                           long prevCorrY=corrY;
   241
   242                           corrX = MathFP.add(corrX,dx);
   243                           corrY = MathFP.add(corrY,dy);
   244
   245
   246
   247                           sx = MathFP.toString(corrX);
   248                           sy = MathFP.toString(corrY);
   249                           ix = sx.indexOf('.');
   250                           sx = sx.substring(0,ix);
   251                           iy = sy.indexOf('.');
   252                           sy = sy.substring(0,iy);
   253                           int xbear1 = Integer.parseInt(sx);
   254                           int ybear1 = Integer.parseInt(sy);
   255
   256
   257                           sx = MathFP.toString(prevCorrX);
   258                           sy = MathFP.toString(prevCorrY);
   259                           ix = sx.indexOf('.');
   260                           sx = sx.substring(0,ix);
   261                           iy = sy.indexOf('.');
   262                           sy = sy.substring(0,iy);
   263                           int xbear3 = Integer.parseInt(sx);
   264                           int ybear3 = Integer.parseInt(sy);
   265
   266
   267


                                         xxxvi
Software Defects Prevention Techniques – Example Project


   268                          sx =
MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(smallestRadius),M
athFP.sin(MathFP.sub(destDown,gama)))));
   269                          sy =
MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),M
athFP.cos(MathFP.sub(destDown,gama)))));
   270
   271
   272                          ix = sx.indexOf('.');
   273                          sx = sx.substring(0,ix);
   274                          iy = sy.indexOf('.');
   275                          sy = sy.substring(0,iy);
   276                          int xbear2 = Integer.parseInt(sx);
   277                          int ybear2 = Integer.parseInt(sy);
   278
   279                          g.drawLine(xbear2,ybear2,xbear3,ybear3);
   280                          g.drawImage(imgDest,xbear1,ybear1,0);
   281                  }
   282          }
   283
   284          public void run(){
   285                  while(end == false){
   286                          delta = mob.getDirection();
   287                          gama = mob.getBearing();
   288                          repaint();
   289                          try{
   290                                   Thread.sleep(100);
   291                          }catch(Exception e){}
   292
   293                  }
   294          }
   295
   296          public void setEnd(){
   297                  end = true;
   298          }
   299
   300 }




                                                xxxvii
Zarko Acimovic


Coordinates.java violations


 All classes and interfaces must belong to a named package                                         9   PMD Marker
 Lack of Cohesion in Methods (Henderson-Sellers) is 100%                                           9   Metrics Marker
 Lack of Cohesion in Methods (Pairwise Field Irrelation) is 100%                                   9   Metrics Marker
 Lack of Cohesion in Methods (Total Correlation) is 100%                                           9   Metrics Marker
 Parameter 'latitude' is not assigned and could be declared final                                 38   PMD Marker
 Parameter 'longitude' is not assigned and could be declared final                                38   PMD Marker
 Parameter 'original' is not assigned and could be declared final                                 47   PMD Marker
 Parameter 'latitude' is not assigned and could be declared final                                 74   PMD Marker
 Parameter 'longitude' is not assigned and could be declared final                                82   PMD Marker
 Avoid variables with short names like to                                                         92   PMD Marker
 Cyclomatic Complexity is 6                                                                       95   Metrics Marker
 Lines of Code in Method is 47                                                                    95   Metrics Marker
 Number of Statements is 47                                                                       95   Metrics Marker
 Local variable 'deltaLat' could be declared final                                               107   PMD Marker
 Avoid using if statements without curly braces                                                  122   PMD Marker
 A method should have only one exit point, and that should be the last statement in the method   123   PMD Marker
 Avoid using if statements without curly braces                                                  125   PMD Marker
 A method should have only one exit point, and that should be the last statement in the method   127   PMD Marker
 Avoid using if...else statements without curly braces                                           127   PMD Marker
 A method should have only one exit point, and that should be the last statement in the method   129   PMD Marker
 Avoid using if...else statements without curly braces                                           129   PMD Marker
 Avoid using if statements without curly braces                                                  139   PMD Marker
 Avoid variables with short names like to                                                        148   PMD Marker




Coordinates.java source code



      1     /**
      2      *
      3      * Coordinates class different performs geographical calculations
      4      */
      5
      6
      7
      8     //import net.jscience.math.MathFP;
      9     public class Coordinates {
     10       /**
     11        * Earth's radius (in meters)
     12        */
     13       public static final long EARTH_RADIUS = MathFP.toFP(6367000);
     14       public static final long EARTH_RADIUS2 = MathFP.toFP(6367000*2);
     15       /**
     16        * the WGS-84 latitude of a location
     17        */


                                                                 xxxviii
Software Defects Prevention Techniques – Example Project


    18    private long latitude;
    19    /**
    20     * the WGS-84 longitude of a location
    21     */
    22    private long longitude;
    23    /**
    24     * The altitude of the location in meters, defined as height above WGS-84
ellipsoid. Float.NaN can be used to indicate that the altitude is not known.
    25     */
    26
    27
    28    /**
    29     * Constructor
    30     * @param     latitude    latitude as WGS-84 system coordinate
    31     * @param     longitude    longitude as WGS-84 system coordinate
    32     * @param     altitude    the altitude in meters, if known, or Float.NaN
    33     * @param     timestamp    the time when information stored in this object
was created, in milliseconds since midnight January 1, 1970 GMT, or -1
    34     * @param     source    the short string describing where data contained
in this object came from, like "GPS", "Network", "Database", etc
    35     * @param     horizontalAccuracy    the horizontal accuracy of coordinates
in meters, or Float.NaN
    36     * @param     verticalAccuracy    vertical accuracy of coordinates in
meters, or Float.NaN
    37     */
    38    public Coordinates(long latitude, long longitude){
    39      this.latitude=latitude;
    40      this.longitude=longitude;
    41    }
    42
    43    /**
    44     * Copy constructor
    45     * @param     original    copied object
    46     */
    47    public Coordinates(Coordinates original){
    48      this.latitude=original.latitude;
    49      this.longitude=original.longitude;
    50    }
    51
    52
    53    /**
    54     * The WGS-84 latitude of a location
    55     * @return WGS-84 latitude
    56     */
    57    public long getLatitude(){
    58      return latitude;
    59    }
    60
    61    /**
    62     * The WGS-84 longitude of a location
    63     * @return WGS-84 longitude


                                                 xxxix
Zarko Acimovic


    64     */
    65    public long getLongitude(){
    66       return longitude;
    67    }
    68
    69
    70    /**
    71     * Set latitude as WGS-84 system coordinate.
    72     * @param latitude latitude as WGS-84 system coordinate
    73     */
    74    public void setLatitude(long latitude){
    75       this.latitude=latitude;
    76    }
    77
    78    /**
    79     * Set longitude as WGS-84 system coordinate.
    80     * @param longitude longitude as WGS-84 system coordinate
    81     */
    82    public void setLongitude(long longitude){
    83       this.longitude=longitude;
    84    }
    85
    86    /**
    87     * Calculate bearing to another location on the surface of the Earth,
using the Great Circle.
    88     * bearing - 1.way of behaving 2.connection 3.direction shown by
compass 4.understanding of one's position
    89     * @param to another point
    90     * @return long representing angle in degrees [0,360) between
corresponding meridian in first point and line on the Great Circle between those
points
    91     */
    92    public long bearing(Coordinates to){
    93       return bearing(getLatitude(), getLongitude(), to.getLatitude(),
to.getLongitude());
    94    }
    95    /**
    96     * Calculate bearing between points (latFrom, lonFrom) and (latTo,lonTo)
on the surface of the Earth, using the Great Circle.
    97     * @param latFrom latitude of the first point
    98     * @param lonFrom longitude of the first point
    99     * @param latTo latitude of the second point
   100     * @param lonTo longitude of the second point
   101     * @return long representing angle in degrees [0,360) between
corresponding meridian in first point and line on the Great Circle between those
points
   102     */
   103    protected static long bearing(long latFrom, long lonFrom, long latTo,
long lonTo){
   104       //BMa: Some numeric with MathFP still happen - but error is mostly
below 16 degrees


                                          xl
Software Defects Prevention Techniques – Example Project


   105      // This should be fixed only if the final target device stays without
not have floats or doubles (e.g. it is not CLDC 1.1)
   106      long bearing;
   107      long deltaLat=latTo-latFrom;
   108      long deltaLon=lonTo-lonFrom;
   109      if (MathFP.abs(deltaLat)<MathFP_1 && MathFP.abs(deltaLon)<MathFP_1) {
   110        // longiude and latitude distance within one deegre, could invent
better condition
   111        //This approximation works better for smaller distances
   112        latFrom = degreesToRadians(latFrom);
   113        deltaLon=MathFP.mul(deltaLon, MathFP.cos(latFrom));
   114        bearing = MathFP.atan2(deltaLat,deltaLon);
   115      }else{
   116        latFrom = degreesToRadians(latFrom);
   117        latTo = degreesToRadians(latTo);
   118        lonFrom = degreesToRadians(lonFrom);
   119        lonTo = degreesToRadians(lonTo);
   120
   121
   122        if (latFrom==latTo && lonFrom==lonTo)
   123           return 0;
   124        //if (MathFP.cos(latFrom) < Double.MIN_VALUE)   // Double.MIN_VALUE a
small number ~ machine precision, so here we check for +/-0
   125        if (MathFP.cos(latFrom) == 0 )   // Double.MIN_VALUE a small number ~
machine precision, so here we check for +/-0
   126           if (latFrom > 0)
   127             return MathFP.PI;       // starting from N pole
   128           else
   129             return MathFP_2PI;        // starting from S pole
   130        //double bearing = radiansToDegrees(Math.atan2(Math.sin(lon2-
lon1)*Math.cos(lat2),Math.cos(lat1)*Math.sin(lat2)-
Math.sin(lat1)*Math.cos(lat2)*Math.cos(lon2-lon1))%(2*Math.PI));
   131
   132        bearing = MathFP.atan2(
   133        MathFP.mul(MathFP.sin(deltaLon),MathFP.cos(latTo)),
   134        MathFP.mul(MathFP.cos(latFrom),MathFP.sin(latTo))-
   135
MathFP.mul(MathFP.mul(MathFP.sin(latFrom),MathFP.cos(latTo)),MathFP.cos(deltaLon)))
;
   136      }
   137      bearing = MathFP.mod(radiansToDegrees(bearing), MathFP_360);
   138
   139      if (bearing<0) bearing = MathFP_360 + bearing;
   140      return bearing;
   141    }
   142
   143    /**
   144     * Calculate distance to another location on the surface of the Earth,
using the Great Circle.
   145     * @param to another point



                                                 xli
Zarko Acimovic


   146     * @return distance to another location in meters, using the line on the
Great Circle
   147     */
   148    public long distance(Coordinates to){
   149       //BMa: Some numeric with MathFP are still possible - errors happen
sometimes
   150       // This should be fixed only if the final target device stays without
not have floats or doubles (e.g. it is not CLDC 1.1)
   151       return calculateDistance(getLatitude(), getLongitude(),
to.getLatitude(), to.getLongitude());
   152    }
   153
   154    /**
   155     * Calculate distance between points (latFrom, lonFrom) and (latTo,lonTo)
on the surface of the Earth, using the Great Circle.
   156     * lat , lon - degrees ([-90, +90]; [-180, +180])
   157     *
   158     * @param latFrom latitude of the first point
   159     * @param lonFrom longitude of the first point
   160     * @param latTo latitude of the second point
   161     * @param lonTo longitude of the second point
   162     * @return distance to another location in meters, using the line on the
Great Circle
   163     */
   164    public static long calculateDistance(long latFrom, long lonFrom, long
latTo, long lonTo){
   165     /*
   166       * d=2*asin(sqrt((sin((latFrom-latTo)/2))^2 +
cos(latFrom)*cos(latTo)*(sin((lonFrom-lonTo)/2))^2))
   167       * or
   168       * d=2*asin(sqrt((sin((latFrom-latTo)/2))^2 +
cos(latFrom)*cos(latTo)*(sin((lonTo-lonFrom)/2))^2))
   169       * distance = R*d
   170       */
   171
   172       latFrom = degreesToRadians(latFrom);
   173       latTo = degreesToRadians(latTo);
   174       lonFrom = degreesToRadians(lonFrom);
   175       lonTo = degreesToRadians(lonTo);
   176       //long distance = R * MathFP.acos(MathFP.sin(latFrom)*MathFP.sin(latTo)
+ MathFP.cos(latFrom)*MathFP.cos(latTo)*MathFP.cos(lonTo-lonFrom));
   177       /*
   178       double distance = R * 2 * Math.asin(
   179                                   Math.sqrt(
   180                                     Math.pow(Math.sin((lat1-lat2)/2), 2)
   181                                     +
   182
Math.cos(lat1)*Math.cos(lat2)*Math.pow(Math.sin((lon2-lon1)/2), 2)
   183                                   )
   184                                 );
   185       */


                                          xlii
Software Defects Prevention Techniques – Example Project


   186
   187 /*
   188      System.out.print("latFrom: "+MathFP.toString(latFrom));
   189      System.out.println(" lonFrom: "+MathFP.toString(lonFrom));
   190      System.out.print("latTo: "+MathFP.toString(latTo));
   191      System.out.println(" lonTo: "+MathFP.toString(lonTo));
   192      */
   193
   194      long p1=MathFP.sin(MathFP.div((latFrom-latTo), MathFP_2));
   195      p1 = MathFP.mul(p1, MathFP.toFP(1000000));
   196      //System.out.println(" p1: "+MathFP.toString(p1));
   197      p1 = MathFP.mul(p1, p1);
   198      //System.out.println(" p1: "+MathFP.toString(p1));
   199
   200      long p2=MathFP.sin(MathFP.div((lonTo-lonFrom), MathFP_2));
   201      p2 = MathFP.mul(p2, MathFP.toFP(1000000));
   202      //System.out.println(" p2: "+MathFP.toString(p2));
   203      p2 = MathFP.mul(p2, p2);
   204      //System.out.println(" p2: "+MathFP.toString(p2));
   205
   206      long sqrtarg=p1
+MathFP.mul(MathFP.mul(MathFP.cos(latFrom),MathFP.cos(latTo)),p2);
   207      //System.out.println(" sqrtarg: "+MathFP.toString(sqrtarg));
   208
   209      sqrtarg=MathFP.sqrt(sqrtarg);
   210      //System.out.println(" sqrtarg: "+MathFP.toString(sqrtarg));
   211
   212      long distance;
   213      if (sqrtarg>MathFP.toFP(19000)) { //toFP("0.019")*1000000 - boundary
for MathFP.asin approximation by X
   214         // calculation is erroneus for small angles
   215         long asinarg=MathFP.div(sqrtarg, MathFP.toFP(1000000));
   216         //System.out.println(" > asinarg: "+MathFP.toString(asinarg));
   217         asinarg=MathFP.asin(asinarg);
   218         //System.out.println(" > asinarg: "+MathFP.toString(asinarg));
   219         distance = MathFP.mul(EARTH_RADIUS2, asinarg);
   220         //System.out.println(" distance asin: "+MathFP.toString(distance));
   221      } else {
   222         //asin(X) is aproximately equall to X,
   223         //This approximation allow us to change the order of multiplication
and division in order to reduce loss of significant digits
   224
   225         distance = MathFP.mul(EARTH_RADIUS2, sqrtarg);
   226         //System.out.println(" > distance: "+MathFP.toString(distance));
   227         distance=MathFP.div(distance, MathFP.toFP(1000000));
   228
   229      }
   230
   231      //System.out.println(" distance: "+MathFP.toString(distance));
   232
   233      //if (Double.isNaN(distance)) //equivalent to (distance=0), but safer


                                                 xliii
Zarko Acimovic


   234      // return 0;
   235      return distance;
   236    }
   237
   238
   239    /**
   240     * Convert degrees to radians
   241     * @return value transformed to radians
   242     * @param    degrees    value to be transformed to radians
   243     */
   244    public static long degreesToRadians(long degrees){
   245      return MathFP.div(degrees,MathFP_180DivPI);
   246    }
   247
   248    /**
   249     * Convert radians to degrees
   250     * @return value transformed to degrees
   251     * @param    radians    value to be transformed to degrees
   252     */
   253    public static long radiansToDegrees(long radians){
   254      return MathFP.mul(radians,MathFP_180DivPI);
   255    }
   256
   257    public static final long MathFP_2 = MathFP.toFP(2);
   258    public static final long MathFP_1 = MathFP.toFP(1);
   259    public static final long MathFP_2PI = MathFP.mul(MathFP_2, MathFP.PI);
   260    public static final long MathFP_1000 = MathFP.toFP(1000);
   261    public static final long MathFP_360 = MathFP.toFP(360);
   262    public static final long MathFP_180DivPI = MathFP.div(MathFP.toFP(180),
MathFP.PI);
   263    public static final long MathFP_0_5 = MathFP.toFP("0.5");
   264
   265
   266 }




                                         xliv
Software Defects Prevention Techniques – Example Project



DelRoute.java violations


 All classes and interfaces must belong to a named package                                       5   PMD Marker
 Lack of Cohesion in Methods (Pairwise Field Irrelation) is 67%                                  5   Metrics Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.          6   PMD Marker
 Use explicit scoping instead of the default package private level                               6   PMD Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.          7   PMD Marker
 Use explicit scoping instead of the default package private level                               7   PMD Marker
 Parameter 'index' is not assigned and could be declared final                                   8   PMD Marker
 Parameter 'routeID' is not assigned and could be declared final                                 8   PMD Marker
 Use explicit scoping instead of the default package private level                              12   PMD Marker




     1 /**
     2   *
     3   * DelRoute is used when deleting route
     4   */
     5 public class DelRoute {
     6          int index;
     7          int routeID;
     8          DelRoute(int index, int routeID){
     9                  this.index = index;
    10                  this.routeID = routeID;
    11          }
    12          int getIndex(){
    13                  return index;
    14          }
    15          int getRouteID(){
    16                  return routeID;
    17          }
    18
    19          public String toString(){
    20                  return "ID Route is "+routeID+"n"+"Index of element to
delet is "+index;
    21          }
    22
    23 }




                                                                xlv
Zarko Acimovic



Friend.java violations


 All classes and interfaces must belong to a named package                                 5   PMD Marker
 Lack of Cohesion in Methods (Henderson-Sellers) is 83%                                    5   Metrics Marker
 Lack of Cohesion in Methods (Pairwise Field Irrelation) is 96%                            5   Metrics Marker
 Lack of Cohesion in Methods (Total Correlation) is 107%                                   5   Metrics Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.    6   PMD Marker
 Use explicit scoping instead of the default package private level                         6   PMD Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.    7   PMD Marker
 Use explicit scoping instead of the default package private level                         7   PMD Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.    8   PMD Marker
 Use explicit scoping instead of the default package private level                         8   PMD Marker
 Avoid variables with short names like t                                                   9   PMD Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.    9   PMD Marker
 Use explicit scoping instead of the default package private level                         9   PMD Marker
 Avoid variables with short names like t                                                  11   PMD Marker
 Parameter 'hashThread' is not assigned and could be declared final                       11   PMD Marker
 Parameter 'name' is not assigned and could be declared final                             11   PMD Marker
 Parameter 'resource' is not assigned and could be declared final                         11   PMD Marker
 Parameter 't' is not assigned and could be declared final                                11   PMD Marker
 Parameter 'hash' is not assigned and could be declared final                             30   PMD Marker
 A getX() method which returns a boolean should be named isX()                            42   PMD Marker




       1   /**
       2    *
       3    * Friend class holds all important data for a friend
       4    */
       5   public class Friend {
       6           String name;
       7           String resource;
       8           int hashThread;
       9           Thread4Friend t;
      10
      11                 Friend(String name, String resource, int hashThread, Thread4Friend
t){
      12                             this.name = name;
      13                             this.resource = resource;
      14                             this.hashThread = hashThread;
      15                             this.t = t;
      16          }
      17
      18          public String getName(){
      19              return name;
      20          }
      21
      22          public String getResource(){



                                                                xlvi
Software Defects Prevention Techniques – Example Project


23           return resource;
24       }
25
26       public int getHash(){
27           return hashThread;
28       }
29
30       public void setID(int hash){
31           hashThread = hash;
32       }
33
34       public String toString(){
35           return "Friend is "+name+"n"+"Hash is "+hashThread;
36       }
37
38       public void setFirst(){
39           t.setFirst();
40       }
41
42       public boolean getThread(){
43           if (t==null){ return false; }
44           else {return true; }
45       }
46
47       public void setThread(Thread4Friend t){
48           this.t = t;
49       }
50   }




                                             xlvii
Zarko Acimovic




HeapSorter.java violations


 All classes and interfaces must belong to a named package                5   PMD Marker
 This class has too many methods, consider refactoring it.                5   PMD Marker
 Document empty constructor                                               7   PMD Marker
 Avoid variables with short names like a                                  9   PMD Marker
 Avoid variables with short names like A                                 10   PMD Marker
 Avoid variables with short names like as                                23   PMD Marker
 Avoid variables with short names like AS                                24   PMD Marker
 Prefer StringBuffer over += for concatenating strings                   30   PMD Marker
 Avoid variables with short names like a                                 37   PMD Marker
 Parameter 'a' is not assigned and could be declared final               37   PMD Marker
 Avoid using for statements without curly braces                         38   PMD Marker
 Parameter 'as' is not assigned and could be declared final              41   PMD Marker
 Avoid using for statements without curly braces                         42   PMD Marker
 Lines of Code in Method is 21                                           45   Metrics Marker
 Parameter 'i' is not assigned and could be declared final               45   PMD Marker
 Local variable 'l' could be declared final                              46   PMD Marker
 Local variable 'r' could be declared final                              47   PMD Marker
 Local variable 'tmp' could be declared final                            62   PMD Marker
 Lines of Code in Method is 21                                           67   Metrics Marker
 Number of Statements is 21                                              67   Metrics Marker
 Parameter 'i' is not assigned and could be declared final               67   PMD Marker
 Local variable 'l' could be declared final                              68   PMD Marker




      1    /**
      2     *
      3     * HeapSorter class sorts points by distance or by name
      4     */
      5    public class HeapSorter{
      6
      7         HeapSorter(){}
      8
      9               public void heapsort(long[] a){
     10                       long[]A = setHeapWithSize(a,a.length);
     11                       buildHeap(A);
     12                       for(int i=0; i<A.length; i++){
     13                               System.out.println(A[i]);
     14                       }
     15                       for(int i=a.length; i>1; i--){
     16                               a[i-1]=A[0]; A[0]=A[i-1];
     17                               A=setHeapWithSize(A,A.length-1);
     18                               heapify(A,1);
     19                       }


                                                     xlviii
Software Defects Prevention Techniques – Example Project


    20           a[0]=A[0];
    21    }
    22
    23    public void heapsort(String[] as){
    24            String[] AS = setHeapWithSize(as,as.length);
    25            buildHeap(AS);
    26            for(int i=0; i<AS.length; i++){
    27                    System.out.println(AS[i]);
    28            }
    29            for(int i=as.length; i>1; i--){
    30                    as[i-1]=AS[0]; AS[0]=AS[i-1];
    31                    AS=setHeapWithSize(AS,AS.length-1);
    32                    heapify(AS,1);
    33            }
    34            as[0]=AS[0];
    35    }
    36
    37    public void buildHeap(long[] a){
    38            for(int i=a.length/2; i>0; i--) heapify(a,i);
    39    }
    40
    41    public void buildHeap(String[] as){
    42            for(int i=as.length/2; i>0; i--) heapify(as,i);
    43    }
    44
    45    public void   heapify(long[]a, int i){
    46            int   l=left(i);
    47            int   r=right(i);
    48            int   largest;
    49
    50           if(l<=heapSize(a) && a[l-1]>a[i-1]){
    51                   largest=l;
    52           }else{
    53                   largest=i;
    54           }
    55
    56           if(r<=heapSize(a) && a[r-1]>a[largest-1]){
    57                   largest=r;
    58           }
    59
    60            if(largest!=i){
    61                    //exchange a[i], a[largest]
    62                    long tmp=a[i-1]; a[i-1]=a[largest-1]; a[largest-
1]=tmp;
    63                       heapify(a,largest);
    64           }
    65    }
    66
    67    public void heapify(String[]as, int i){
    68            int l=left(i);
    69            int r=right(i);


                                           xlix
Zarko Acimovic


    70                   int largest;
    71
    72                   if(l<=heapSize(as) && as[l-1].charAt(0)>as[i-1].charAt(0)){
    73                           largest=l;
    74                   }else{
    75                           largest=i;
    76                   }
    77
    78                   if(r<=heapSize(as) && as[r-1].charAt(0)>as[largest-
1].charAt(0)){
    79                            largest=r;
    80                   }
    81
    82                   if(largest!=i){
    83                           //exchange a[i], a[largest]
    84                           String tmpS=as[i-1]; as[i-1]=as[largest-1];
as[largest-1]=tmpS;
    85                            heapify(as,largest);
    86                   }
    87          }
    88
    89
    90          public   int heapSize(long a[]){
    91                    return a.length;
    92          }
    93
    94          public   int heapSize(String as[]){
    95                    return as.length;
    96          }
    97
    98          public   int parent(int i){
    99                    return(i/2);
   100          }
   101
   102          public   int left(int i){
   103                    return(2*i);
   104          }
   105
   106          public   int right(int i){
   107                    return(2*i+1);
   108          }
   109
   110          public   long[] setHeapWithSize(long[]m , int n){
   111                    long[] k = new long[n];
   112                    for(int i=0; i<n; i++){
   113                            k[i]=m[i];
   114                    }
   115                    return k;
   116          }
   117
   118          public   String[] setHeapWithSize(String[]m , int n){


                                              l
Software Defects Prevention Techniques – Example Project


    119                              String[] k = new String[n];
    120                              for(int i=0; i<n; i++){
    121                                      k[i]=m[i];
    122                              }
    123                              return k;
    124                 }
    125    };

ImageCanvas3.java violations


 All classes and interfaces must belong to a named package                                      10   PMD Marker
 Avoid variables with short names like ol                                                       12   PMD Marker
 Found non-transient, non-static member. Please mark as transient or provide accessors.         12   PMD Marker
 Use explicit scoping instead of the default package private level                              12   PMD Marker
 Avoid variables with short names like ol                                                       14   PMD Marker
 It is a good practice to call super() in a constructor                                         14   PMD Marker
 Parameter 'ol' is not assigned and could be declared final                                     14   PMD Marker
 Avoid variables with short names like g                                                        19   PMD Marker
 Parameter 'g' is not assigned and could be declared final                                      19   PMD Marker
 Cyclomatic Complexity is 8                                                                     23   Metrics Marker
 Lines of Code in Method is 38                                                                  23   Metrics Marker
 Number of Statements is 25                                                                     23   Metrics Marker
 Parameter 'keyCode' is not assigned and could be declared final                                23   PMD Marker




      1    /**
      2     *
      3     * ImageCanvas3 draws elements on screen and captures events on canvas
      4     */
      5
      6    //import java.io.IOException;
      7    import javax.microedition.lcdui.*;
      8    //import java.util.*;
      9
     10    public class ImageCanvas3 extends Canvas {
     11
     12                 Outlook ol;
     13
     14           ImageCanvas3(Outlook ol){
     15               this.ol =ol;
     16               ol.setCanvasWH(this.getWidth(),this.getHeight());
     17           }
     18
     19                 public void paint(Graphics g) {
     20                         ol.drawOutlook(g);
     21           }


                                                                 li
Zarko Acimovic


22
23       public void keyPressed (int keyCode){
24
25               //keyCode+=disabler;
26
27              if(keyCode==49){
28                      ol.ZoomIn();
29              repaint();
30              }
31
32              if(keyCode==50){
33                      ol.ZoomOut();
34              repaint();
35              }
36
37              if(keyCode==51){
38                      repaint();
39              }
40
41
42               switch (getGameAction(keyCode)) {
43                       case Canvas.UP:
44                               ol.setMap('u');
45                               repaint();
46                               break;
47               case Canvas.DOWN:
48                       ol.setMap('d');
49                       repaint();
50                       break;
51               case Canvas.LEFT:
52                       ol.setMap('l');
53                               repaint();
54                               break;
55               case Canvas.RIGHT:
56                       ol.setMap('r');
57                               repaint();
58                               break;
59       }
60       }
61   }




                                   lii
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques
Defect prevention techniques

More Related Content

What's hot

Formal Verification Techniques
Formal Verification TechniquesFormal Verification Techniques
Formal Verification TechniquesDVClub
 
Software Quality Assurance
Software Quality AssuranceSoftware Quality Assurance
Software Quality AssuranceSaqib Raza
 
Software Testing interview - Q&A and tips
Software Testing interview - Q&A and tipsSoftware Testing interview - Q&A and tips
Software Testing interview - Q&A and tipsPankaj Dubey
 
System testing
System testingSystem testing
System testingSlideshare
 
Unit I Software Testing and Quality Assurance
Unit I Software Testing and Quality AssuranceUnit I Software Testing and Quality Assurance
Unit I Software Testing and Quality AssuranceVinothkumaR Ramu
 
What is Sanity Testing? Edureka
What is Sanity Testing? EdurekaWhat is Sanity Testing? Edureka
What is Sanity Testing? EdurekaEdureka!
 
Communication in client server system.pptx
Communication in client server system.pptxCommunication in client server system.pptx
Communication in client server system.pptxMSivani
 
Software Testing Basics
Software Testing BasicsSoftware Testing Basics
Software Testing BasicsBelal Raslan
 
What Is Functional Testing?
What Is Functional Testing?What Is Functional Testing?
What Is Functional Testing?QA InfoTech
 
Statistical Software Quality Assurance.pptx
Statistical Software Quality Assurance.pptxStatistical Software Quality Assurance.pptx
Statistical Software Quality Assurance.pptxKarthigaiSelviS3
 
system calls, single user, multiuser os ...
system calls, single user, multiuser os                                      ...system calls, single user, multiuser os                                      ...
system calls, single user, multiuser os ...myrajendra
 
Software quality assurance
Software quality assuranceSoftware quality assurance
Software quality assuranceAman Adhikari
 
Software Testing Techniques: An Overview
Software Testing Techniques: An Overview Software Testing Techniques: An Overview
Software Testing Techniques: An Overview QA InfoTech
 

What's hot (20)

Formal Verification Techniques
Formal Verification TechniquesFormal Verification Techniques
Formal Verification Techniques
 
Software quality management standards
Software quality management standardsSoftware quality management standards
Software quality management standards
 
Software Quality Assurance
Software Quality AssuranceSoftware Quality Assurance
Software Quality Assurance
 
Ch 2
Ch 2Ch 2
Ch 2
 
Software process
Software processSoftware process
Software process
 
Software Testing interview - Q&A and tips
Software Testing interview - Q&A and tipsSoftware Testing interview - Q&A and tips
Software Testing interview - Q&A and tips
 
System testing
System testingSystem testing
System testing
 
System Maintenance
System MaintenanceSystem Maintenance
System Maintenance
 
Unit I Software Testing and Quality Assurance
Unit I Software Testing and Quality AssuranceUnit I Software Testing and Quality Assurance
Unit I Software Testing and Quality Assurance
 
What is Sanity Testing? Edureka
What is Sanity Testing? EdurekaWhat is Sanity Testing? Edureka
What is Sanity Testing? Edureka
 
Communication in client server system.pptx
Communication in client server system.pptxCommunication in client server system.pptx
Communication in client server system.pptx
 
Software Testing Basics
Software Testing BasicsSoftware Testing Basics
Software Testing Basics
 
What Is Functional Testing?
What Is Functional Testing?What Is Functional Testing?
What Is Functional Testing?
 
Statistical Software Quality Assurance.pptx
Statistical Software Quality Assurance.pptxStatistical Software Quality Assurance.pptx
Statistical Software Quality Assurance.pptx
 
system calls, single user, multiuser os ...
system calls, single user, multiuser os                                      ...system calls, single user, multiuser os                                      ...
system calls, single user, multiuser os ...
 
Software quality assurance
Software quality assuranceSoftware quality assurance
Software quality assurance
 
COCOMO Model
COCOMO ModelCOCOMO Model
COCOMO Model
 
Software Verification & Validation
Software Verification & ValidationSoftware Verification & Validation
Software Verification & Validation
 
Chapter 1 - Basic Concepts
Chapter 1 - Basic ConceptsChapter 1 - Basic Concepts
Chapter 1 - Basic Concepts
 
Software Testing Techniques: An Overview
Software Testing Techniques: An Overview Software Testing Techniques: An Overview
Software Testing Techniques: An Overview
 

Viewers also liked

Defect analysis and prevention methods
Defect analysis and prevention methods Defect analysis and prevention methods
Defect analysis and prevention methods deep sharma
 
From Defect Reporting To Defect Prevention
From Defect Reporting To Defect PreventionFrom Defect Reporting To Defect Prevention
From Defect Reporting To Defect PreventionSune Gynthersen
 
Defect Analytics & Statistical Trends
Defect Analytics & Statistical TrendsDefect Analytics & Statistical Trends
Defect Analytics & Statistical TrendsMani Nutulapati
 
defect tracking and management
defect tracking and management   defect tracking and management
defect tracking and management Manish Chaurasia
 
Root cause Analysis of Defects
Root cause Analysis of DefectsRoot cause Analysis of Defects
Root cause Analysis of DefectsDavid Gevorgyan
 
IT Quality Testing and the Defect Management Process
IT Quality Testing and the Defect Management ProcessIT Quality Testing and the Defect Management Process
IT Quality Testing and the Defect Management ProcessYolanda Williams
 
Practical Guide To Software System Testing
Practical Guide To Software System TestingPractical Guide To Software System Testing
Practical Guide To Software System Testingvladimir zaremba
 
Defect management using kanban
Defect management using kanbanDefect management using kanban
Defect management using kanbanCarl Bruiners
 
"Visual management & 5S " in Lean T.P.S (Workshop slides)
"Visual management &  5S " in Lean T.P.S (Workshop slides)"Visual management &  5S " in Lean T.P.S (Workshop slides)
"Visual management & 5S " in Lean T.P.S (Workshop slides)Zeeshan Syed
 

Viewers also liked (13)

Defect prevention
Defect preventionDefect prevention
Defect prevention
 
Defect analysis and prevention methods
Defect analysis and prevention methods Defect analysis and prevention methods
Defect analysis and prevention methods
 
From Defect Reporting To Defect Prevention
From Defect Reporting To Defect PreventionFrom Defect Reporting To Defect Prevention
From Defect Reporting To Defect Prevention
 
Defect Prevention
Defect PreventionDefect Prevention
Defect Prevention
 
Defect Analytics & Statistical Trends
Defect Analytics & Statistical TrendsDefect Analytics & Statistical Trends
Defect Analytics & Statistical Trends
 
defect tracking and management
defect tracking and management   defect tracking and management
defect tracking and management
 
Root cause Analysis of Defects
Root cause Analysis of DefectsRoot cause Analysis of Defects
Root cause Analysis of Defects
 
Advanced Defect Management
Advanced Defect ManagementAdvanced Defect Management
Advanced Defect Management
 
IT Quality Testing and the Defect Management Process
IT Quality Testing and the Defect Management ProcessIT Quality Testing and the Defect Management Process
IT Quality Testing and the Defect Management Process
 
Practical Guide To Software System Testing
Practical Guide To Software System TestingPractical Guide To Software System Testing
Practical Guide To Software System Testing
 
Defect management using kanban
Defect management using kanbanDefect management using kanban
Defect management using kanban
 
Rajesh HR resume
Rajesh HR resumeRajesh HR resume
Rajesh HR resume
 
"Visual management & 5S " in Lean T.P.S (Workshop slides)
"Visual management &  5S " in Lean T.P.S (Workshop slides)"Visual management &  5S " in Lean T.P.S (Workshop slides)
"Visual management & 5S " in Lean T.P.S (Workshop slides)
 

Similar to Defect prevention techniques

Software defect prevention example project
Software defect prevention example projectSoftware defect prevention example project
Software defect prevention example projectZarko Acimovic
 
Agile methods and safety critical software - Peter Gardner
Agile methods and safety critical software - Peter GardnerAgile methods and safety critical software - Peter Gardner
Agile methods and safety critical software - Peter GardnerAdaCore
 
MODULE 1 Software Product and Process_ SW ENGG 22CSE141.pdf
MODULE 1 Software Product and Process_ SW ENGG  22CSE141.pdfMODULE 1 Software Product and Process_ SW ENGG  22CSE141.pdf
MODULE 1 Software Product and Process_ SW ENGG 22CSE141.pdfJayanthi Kannan MK
 
ppt_se.bdfhrfykjyftiktgdukhydiyiuoyu8otrfu
ppt_se.bdfhrfykjyftiktgdukhydiyiuoyu8otrfuppt_se.bdfhrfykjyftiktgdukhydiyiuoyu8otrfu
ppt_se.bdfhrfykjyftiktgdukhydiyiuoyu8otrfutubashaikh26
 
Lecture 1-intro-to-software-development
Lecture 1-intro-to-software-developmentLecture 1-intro-to-software-development
Lecture 1-intro-to-software-developmentZahid Hussain
 
Machine Learning in Software Engineering
Machine Learning in Software EngineeringMachine Learning in Software Engineering
Machine Learning in Software EngineeringAlaa Hamouda
 
Software Engineering The Multiview Approach And Wisdm
Software Engineering   The Multiview Approach And WisdmSoftware Engineering   The Multiview Approach And Wisdm
Software Engineering The Multiview Approach And Wisdmguestc990b6
 
SE UNIT 1 NOTES OF SE SOFTWARE ENGG AND SE
SE UNIT 1 NOTES OF SE SOFTWARE ENGG AND SESE UNIT 1 NOTES OF SE SOFTWARE ENGG AND SE
SE UNIT 1 NOTES OF SE SOFTWARE ENGG AND SEAbhishekTripathi709328
 

Similar to Defect prevention techniques (20)

Software defect prevention example project
Software defect prevention example projectSoftware defect prevention example project
Software defect prevention example project
 
Agile methods and safety critical software - Peter Gardner
Agile methods and safety critical software - Peter GardnerAgile methods and safety critical software - Peter Gardner
Agile methods and safety critical software - Peter Gardner
 
MODULE 1 Software Product and Process_ SW ENGG 22CSE141.pdf
MODULE 1 Software Product and Process_ SW ENGG  22CSE141.pdfMODULE 1 Software Product and Process_ SW ENGG  22CSE141.pdf
MODULE 1 Software Product and Process_ SW ENGG 22CSE141.pdf
 
ppt_se.bdfhrfykjyftiktgdukhydiyiuoyu8otrfu
ppt_se.bdfhrfykjyftiktgdukhydiyiuoyu8otrfuppt_se.bdfhrfykjyftiktgdukhydiyiuoyu8otrfu
ppt_se.bdfhrfykjyftiktgdukhydiyiuoyu8otrfu
 
Lecture 1-intro-to-software-development
Lecture 1-intro-to-software-developmentLecture 1-intro-to-software-development
Lecture 1-intro-to-software-development
 
1 introduction
1 introduction1 introduction
1 introduction
 
1 introduction (1)
1 introduction (1)1 introduction (1)
1 introduction (1)
 
Requirements engineering
Requirements engineeringRequirements engineering
Requirements engineering
 
ppt_se.pdf
ppt_se.pdfppt_se.pdf
ppt_se.pdf
 
1
11
1
 
Week1.pptx
Week1.pptxWeek1.pptx
Week1.pptx
 
Unit1
Unit1Unit1
Unit1
 
lecture 1.pdf
lecture 1.pdflecture 1.pdf
lecture 1.pdf
 
SE-Lecture1.ppt
SE-Lecture1.pptSE-Lecture1.ppt
SE-Lecture1.ppt
 
Machine Learning in Software Engineering
Machine Learning in Software EngineeringMachine Learning in Software Engineering
Machine Learning in Software Engineering
 
Software Engineering The Multiview Approach And Wisdm
Software Engineering   The Multiview Approach And WisdmSoftware Engineering   The Multiview Approach And Wisdm
Software Engineering The Multiview Approach And Wisdm
 
ch1_introduction (1).ppt
ch1_introduction (1).pptch1_introduction (1).ppt
ch1_introduction (1).ppt
 
ch1_introduction (2).ppt
ch1_introduction (2).pptch1_introduction (2).ppt
ch1_introduction (2).ppt
 
ch1_introduction.ppt
ch1_introduction.pptch1_introduction.ppt
ch1_introduction.ppt
 
SE UNIT 1 NOTES OF SE SOFTWARE ENGG AND SE
SE UNIT 1 NOTES OF SE SOFTWARE ENGG AND SESE UNIT 1 NOTES OF SE SOFTWARE ENGG AND SE
SE UNIT 1 NOTES OF SE SOFTWARE ENGG AND SE
 

Recently uploaded

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Recently uploaded (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

Defect prevention techniques

  • 1. Software Defect Prevention Techniques - Example Project - Zarko Acimovic Copyright © 2012 Zarko Acimovic All rights reserved. ISBN-10: 1481113305 ISBN-13: 978-1481113304
  • 2. DEDICATION I dedicate this book to my parents, Ivana and Goran
  • 3. CONTENTS 1 Introduction 2 Theoretical Foundations for Defect Prevention 1 3 Automatic Tools for Defect Prevention 24 4 Tools for Defect Prevention in Java Software Development 25 5 Sample Project Software Requirements 25 6 Source Code with Violations 26 7 Design Defects Detected by ArgoUML 192 8 Examples of Design Defects in Sample Project 196 About the Author
  • 4. Zarko Acimovic 1 INTRODUCTION I present 5000 lines of Java source code from prototype project. The code is operational and fulfills its software requirements. I wrote the code in 2004 and ever since had several business offers to commercialize it, which I resisted due to complexity of the code. I tested the code with static analysis tools PMD, FindBugs, StateOfFlow and ArgoUML in order to comprehend its architectural quality. Source code is presented as written in 2004. These tools uncovered 1123 code violations (almost 1 violation per 5 lines of code) and 121 software design violations. All these violations are presented in book with references to the source code. I recommend to readers to use these tools during development and correct all the violations reported. 2 THEORETICAL FOUNDATIONS FOR DEFECT PREVENTION Below are the details of E-learning course “Software Engineering” from IIT Bombay India >> NPTEL >> Courses >> Computer Science and Engineering >> Software Engineering (Video). My opinion is that this course provides solid theoretical foundation for applying software defect prevention techniques. The course can be found on following location http://nptel.iitm.ac.in/video.php?subjectId=106101061 Here are the details of the course: 1 - Introduction to Software Engineering (52:21) 2 - Introduction to Software Engineering (52:55) 3 - Overview of Phases (57:22) 4 - Overview of Phases (57:03) 5 - Requirements Engineering / Specification (56:39) 6 - Formal Specification (51:44) 7 - Algebraic Specification Methods (57:34) 8 - Systems Modeling Overview (59:38) 9 - Process Modeling - DFD , Function Decomp (56:28) 10 - Process Modeling - DFD, Function Decomp (53:23) 11 - Data Modeling - ER Diagrams, Mapping (1:00:55) 12 - Data Modeling - ER Diagrams, Mapping (58:08) 13 - Production Quality Software - Introduction (53:04) 14 - Software Design - Primary Consideration (1:04:43) 15 - Design Patterns (56:13) 16 - Class and Component Level Design (54:34) 17 - Architectural Design (59:28) 18 - Software Testing - I (55:39) 19 - Software Testing - II (51:18) 20 - Structural Programming and Some implementation (45:05) 21 - Software Metrics and Quality (54:51) 22 - Verification and Validation (52:43) iv
  • 5. Software Defects Prevention Techniques – Example Project 23 - Case Study (54:55) 24 - Case Study (58:39) 25 - Software Evolution (55:41) 26 - Agile Development (55:33) 27 - Software Reuse (53:43) 28 - Reuse Continued (57:07) 29 - Introduction to Project Management (52:36) 30 - Project Scope Management (1:08:45) 31 - Project Time Management (56:51) 32 - Estimation - I (51:42) 33 - Estimation - II (50:38) 34 - Project Quality Management (58:32) 35 - Quality Management Systems - I (54:43) 36 - Quality Management Systems (54:53) 37 - Project Configuration Management (53:00) 38 - Project Risk Management (56:04) 39 - Other PM Processes (55:41) Here are the details of the videos: 1. Introduction to Software Engineering (52:21) http://nptel.iitm.ac.in/video.php?subjectId=106101061 2. Introduction to Software Engineering (52:55) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Waterfall Model for Development • Deliverables in Waterfall Model • Cost/Effort Distribution • Shortcomings of Waterfall Model • Prototyping Model • Prototyping • Limitations of Prototyping • Iterative Development • Spiral Model • Project Management Process • Project Planning • Project Monitoring and Control v
  • 6. Zarko Acimovic 3. Overview of Phases in Software Development (57:22) http://nptel.iitm.ac.in/video.php?subjectId=106101061 4. Overview of Phases in Software Development (57:03) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Structured Analysis • Structured Methodology • Requirement Specification Format • System Design • Alternatives • Design goals • System Architecture • Structure Chart • Structure Chart Notation • OO Approach • Design Document Format • Detailed Design • Implementation Phase • Operations & Maintenance • Summary 5. Requirements Engineering / Specification (56:39) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Objectives • Requirements engineering • What is a requirement? • Requirements abstraction (Davis) • Types of requirement • Requirements Audience • Functional and non-functional requirements • Functional requirements • The LIBSYS system • Examples of functional requirements • Requirements imprecision • Requirements completeness and consistency • Non-functional requirements • Non-functional classifications • Non-functional requirement types • Non-functional requirements examples • Goals and requirements • Examples • User requirements • Problems with natural language • LIBSYS requirement • Editor grid requirement vi
  • 7. Software Defects Prevention Techniques – Example Project • Requirement problems • Structured presentation • Guidelines for writing requirements • System requirements • Requirements and design • Alternatives to NL specification • Structured language specifications • Form-based specifications • Tabular specification • Graphical models • PDL interface description • The requirements document • IEEE requirements standard 6. Formal Specification (51:44) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Natural Language Requirement Specification • Problem Statement • The Need for Formal Specification • Formal methods • Acceptance of formal methods • Use of formal methods • Specification in the software process • Specification techniques • Formal specification languages • Use formal specification • Development costs with formal specification • Properties of Formal Specifications • Library Example-Informal Statement • Library Example -- Formalization • Library Example -- Formalization - 2 • Library Example -- Prove Correctness • Specification Types • Interface specification • Sub-system interfaces • Behavioral specification • Key points 7. Algebraic Specification Methods (57:34) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Disadvantages of NL specifications • Another Perspective - Dangers of Physical Representations in Analysis • Towards Abstraction • What does a Abstract Data Type (ADT) consist of?7:29 • What about Post Conditions? vii
  • 8. Zarko Acimovic • Algebraic Manipulation using Axioms • Abstract Math to Concrete realizations • ADTs and Information Hiding • Completeness of Specification • Definition: sufficient completeness • ADT Consistency 8. Systems Modeling Overview (59:38) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Model types • Context models • The context of an ATM system • Process models • Behavioral models • Order processing DFD • Microwave oven model • Microwave oven state description • Microwave oven stimuli • Microwave oven state description • Microwave oven stimuli • Microwave oven operation • Semantic data models • Library semantic model • Data Dictionary Entries • Object models • Inheritance models • Multiple inheritance • Object aggregation • Object behavior modeling • Structured methods 9. Process Modeling - DFD , Function Decomposition (56:28) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • ER MODEL • ENTITY • ENTITY SET • ATTRIBUTE • DOMAIN • PRIMARY KEYS • EXAMPLE : A COLLEGE • RELATIONSHIP • RELATIONSHIP SET • DEPICTING A RELATIONSHIP • PRIMARY KEY FOR REPATIONSHIPS • RELATIONSHIP CARDINALITY viii
  • 9. Software Defects Prevention Techniques – Example Project 10. Process Modeling - DFD, Function Decomposition (53:23) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • RELATIONSHIP CARDINALITY • EXISTENCE DEPENDENCE • TERNARY RELATIONSHIPS • WEAK ENTITY • EXTENDED E-R MODEL • Generalization 11. Data Modeling - ER Diagrams, Mapping (1:00:55) • Generalization • Specialization • Inheritance • Aggregation • Process Model • Function Decomposition • FD Diagrams: Examples 12. Data Modeling - ER Diagrams, Mapping (58:08) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Data Flow Diagram (DFD) • DFD Notation • Context Diagram • Process Refinement • Physical DFD • Showing Boundaries • DFD Example 1: Payroll • DFD Example 2: Old Car Mart • DFD Example Old Car Mart • Example 3: Book Supplier • Book Supplier: Exploding Process 2 • Book Supplier : homework 13. Production Quality Software - Introduction (53:04) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Software construction then and now • Software Crisis (Late 1980s) • More perspective on the Software Crisis • Brian Russell's Laws of Software Relativity • Properties of Failing software • Common Error in Managing the Process ix
  • 10. Zarko Acimovic • Software Maintenance • Quality Factors for Software • Quality Factors • Quality Factors - contd. • Quality Factors • Keys to achieving Structural Quality • What ls Abstraction? • Abstraction • Abstraction Techniques • Encapsulation • Modules • Desirable Characteristics - Weak Coupling • Information Hiding • Protocol Vs Behavior • IH and Abstraction • Factorization and Specialization • Inclusion • Benefits of Inheritance • Uses for inheritance 14. Software Design - Primary Consideration (1:04:43) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • What's Design? • Example Designs in Real Life • Programs • Example Designs in Real Life • Design in Software Engineering • Examples of Process Design • What is covered in Product Design? • From Analysis to Design • Factors To be considered in Design • Factors to be considered in Design • Process of Complex System Design • Top-down Vs. Bottom-up Approach • Decomposition • Composition/Interconnection • Basic Principles To be applied during design • Abstraction • Example Abstractions • Describing Abstractions • Encapsulation • Refinement • Refinement and Change Process • Communication • Other Kinds of Communication x
  • 11. Software Defects Prevention Techniques – Example Project 15. Design Patterns (56:13) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Reuse in Software Engineering • Patterns in Software Engineering • Design Patterns • Describing a Design Pattern • Pattern Description Template provided by • Classification of Patterns • Examples of Creational Patterns • Behavioral Patterns • A Problem • The Solution • The Design Pattern: Prototype • Singleton Pattern • Implementing Singleton • Adapter Pattern • Composite Pattern • The Solution • Instance Structure for an Instance of a Composite Class • The Composite Pattern • The Facade Pattern • How to interact with components with a subsystem? • The Facade Pattern • Proxy Pattern: A Mechanic for Communication • Real object and Proxy object are different • The Proxy Pattern • The Decorator Pattern: Object Diagram • Visual Component • The Template Method Pattern • Strategy Pattern 16. Class and Component Level Design (54:34) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Class • Example Classes • Kinds of Classes • Levels of Abstraction • Beck and Cunningham's CRC Method • CRC: our recommendation • A system decomposed in CRCs • Contributions of CRC • Bertrand Meyer' Design-by-Contract • Design by Contact Method • Contracts • An Example Contact for class Book xi
  • 12. Zarko Acimovic • A Contact Specification • Class Design • Part-Whole Design • Odell's Classification Criteria • Component-Integral Object • Material-Object (made of) • Portion-Object • Place-Area • Member-Bunch • Member-Partnership • Non-aggregation relations • Transitivity in Part-Whole • Two Kinds of Part-whole Relations in UML • Designing New Subclasses From Old: Inheritance • Use of Inheritance in a Subclass • Components • Use of Inheritance in a Subclass • Components • Design of Components • Decisions about component's non-functional properties • Reuse in Component Technologies 17. Architectural Design (59:28) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Software Architecture • Why Do We need Architecture? • Basic Principles applied by Architects • Several Approaches to Architecture • The Zachman Framework • Open Distributed Processing Reference Model (ODP-RM) • ODP: Enterprise viewpoint • ODP: Information viewpoint • ODP: Computational viewpoint • ODP: Computation viewpoint • ODP: Engineering viewpoint • ODP: Transparencies • ODP: Transparencies Defined • 4+1 View Model • Unified Process Model of Architecture • Commonly occurring Architectural Patterns • Layers • Peers • Client-server • Pipelines • Transactional Flows xii
  • 13. Software Defects Prevention Techniques – Example Project • Filters • Blankboards • Facade • Broker • MVC • Microkernel • Framework Architectures • A Framework • References/Readings 18. Software Testing - I (55:39) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Why Testing? • A Test Case • What criteria to use? • Black Box Testing • White Box Testing • Levels of Testing • Stub Modules • Test Drivers • Test Drivers during Partial Integration • Testing Modules with Top Down Integration • Testing Modules with Bottom Up Integration • Regression Testing • Monitoring Behavior of Programs • Documentation Probes • Standard Error Probes and Exceptions (user defined) • Assertions for defensive programming • Different Types of Assertions • IS the output of a test correct? • Test Objectives • Alpha testing and Beta testing • Debugging • Testing In Software Development 19. Software Testing - II (51:18) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Black box vs. white box testing • Black Box Testing (External) • White Box Testing (Internal) • Statement Coverage • An Example for Statement Coverage • Observations xiii
  • 14. Zarko Acimovic • An Example for Statement Coverage • Observations • Implicit statements • Basic Path Testing • A Sequential Composition • A Branching Statement • A While Statement • A Repeat Statement • A Switch Case Statement • A Compound Condition • Cyclomatic Complexity • Cyclomatic Complexity Example • Condition Testing • Condition Testing Strategies • Data Flow Testing Strategies • Exercise: Try different strategies on the below program 20. Structural Programming and Some implementation (45:05) http://nptel.iitm.ac.in/video.php?subjectId=106101061 21. Software Metrics and Quality (54:51) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Why Measurement? • Use of Software Measurement • The attributes that can be captured • Which one is a good measure? • What to measure in software? • Measurement Scales • Ordinal Scale • Interval Scale • Ratio Scale • Absolute Scale • Size Metrics • Length • Functionality • Complexity • Measuring Structure • Coupling and cohesion • Object Oriented Metrics: CK and MOOD • Quality Guidelines for Coding and Development • Defensive Programming for Modules, Functions, Procedures, Classes • Preconditions • Invariants xiv
  • 15. Software Defects Prevention Techniques – Example Project • Use of Software Measurement • Separate Compilation • Makefile • Separate Compilation • Makefile • A Sample Makefile • Code organization • Development • Some good practices 22. Verification and Validation (52:43) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Verification vs validation • The V & V process • V & V goals • V & V confidence • Static and dynamic verification • Program testing • Types of testing • Testing and debugging • The debugging process • V & V planning • V-model of development • The Structure of a software test plan • Software inspections • Inspection success • Inspections testing • Program inspections • Inspection pre-conditions • Inspection procedure • Inspection Roles • Inspection Checklists (2) • Inspection Checklists (3) • Inspection rate • Automated static analysis • Static Analysis Checks • Stages of static analysis • LINT static analysis • Verification and formal methods • Arguments for formal methods 23. Case Study (54:55) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Case study: library book circulation system • BOOK CIRCULATION xv
  • 16. Zarko Acimovic • STATEMENT OF PROJECT SCOPE AND OBJECTIVES • THE FEASIBILITY STUDY: CIRCULATION • Financial analysis for alternatives 1 : • Alternatives 2 • Plan for alternatives 1 • Feasibility ... • Requirements Analysis • Circulation System • Draw first level DFD • Requirements Analysis 24. Case Study (58:39) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Requirements Analysis... • Refinement of issue process • Requirements Analysis... • Requirements Specification... • SRS ... • System Design: CIRCULATION • System Design ... • System Design • E-R DIAGRAM • System Design ... • Table Design • Physical DB Design • Physical DB Design... • Physical DB Design... • System Design ... • Software Architecture • Software Architecture... • Implementation Schedule • Implementation Schedule... • Design documentation • Detailed Design • Data and Module Specification • Module ... • Implementation 25. Software Evolution (55:41) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Software Change • Software change control • Software change strategies • Program evolution dynamics xvi
  • 17. Software Defects Prevention Techniques – Example Project • Laws of Program Evolution • Applicability of Lehman's laws • Software maintenance • Maintenance is inevitable • Causes of maintenance • Distribution of maintenance effort • Types of Maintenance • Breakup of costs • Spiral maintenance model • Maintenance costs • Maintenance costs factors • Problems facing Maintainers • Approaches to Maintenance • The Change process • Change requests • Change implementation • Maintenance prediction • Change prediction • Complexity metrics • Process metrics 26. Agile Development (55:33) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Objectives • Requirements • Characteristics of Agile Processes • An iterative development process • Advantages of incremental development • Problems with incremental development • Prototyping • Software prototyping • Benefits of prototyping • Throw -away prototypes • Incremental Development & Prototyping • Conflicting objectives • Agile methods • Principles of Agile Methods • Problems with agile methods • Extreme programming • The Four Core Values of XP • Communication • Feedback • Courage • The XP release cycle • XP Practices • XP Practices - 2 xvii
  • 18. Zarko Acimovic • XP and agile principles • Requirements scenarios • Story Card for document downloading • XP Design Guidelines • XP and change • Testing in XP • Task cards for document downloading • Test Case Description • Test- first development • Pair programming • XP Summary 27. Software Reuse (53:43) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Design with Reuse • Objectives • Software reuse • Benefits of reuse • Requirements for design with reuse • Reuse problems • Generator-based reuse • Types of program generator • Reuse through program generation • Component-based development • Components • Component abstractions • CBSE processes • An opportunistic reuse process • Development with reuse • CBSE problems • Application frameworks • Framework classes • Extending frameworks 28. Reuse Continued (57:07) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Application frameworks • Framework classes • Extending frameworks • Evaluating Frameworks • Framework evaluation criteria xviii
  • 19. Software Defects Prevention Techniques – Example Project • Evaluating Frameworks • COTS product reuse • Integration Approaches • Examples of COTS muse • COTS system integration problems • Component development for reuse • Reusable components • Re-usability enhancement • Generalization Techniques • Generating good mental Models • Application families • Application family specialization • Inventory management systems • Application family architectures • A library system • Library system • Family member development • Design patterns • The Observer pattern 29. Introduction to Project Management (52:36) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • What is Project Management ? • Who Executes a Project? • An Effective PM Needs to Do the Following: • Productivity Gains With Standards and Procedures • Software Process is a Part of Organizational Process • Software Project Phases and Activities • Software Development Strategies at a Glance • Project Management Process Groups: Schematic • Illustration: Interaction Within and Across Project • Software Development Methodology: Schematic • PMBOK (2000) • Framework for Project Management • PMI Developed Code Of Ethics (1/2) • Impact of Good Project Management • Software Project Management • Suggested Readings xix
  • 20. Zarko Acimovic 30. Project Scope Management (1:08:45) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Scope Management Subprocesses • Illustrative Comparison of Projects • Another Way of Comparing Projects: • PM Must Question ALL Aspects of a Project • Illustration: Stakeholder Analysis • Illustration: Objectives of a Hospital IS • Illustration: Project Charter (1/3) • Illustration: Project Charter (2/3) • Illustration: Project Charter (3/3) • Illustration: WBS Organized by phases • Summary: Scope management Subprocesses 31. Project Time Management (56:51) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Project Time Management Subprocesses • WBS to Precedence Relationship • Precedence Diagramming Method (PDM): Types of Dependencies • Illustration: PDM Network • Illustration: Arrow Diagramming Method (ADM) Network • Precedence Relationship to Schedule • Schedule Development Preferences • Illustration of a Schedule • Software Support for Project Management • Summary: Time Management Process 32. Estimation - I (51:42) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Estimation is an Ongoing Activity • Stages in Project Estimation • Estimation Approaches • PERT Sizing Approach to Estimation • Estimation: Levels of Application • Function Point Counting Procedure • Components of FP Count • FP for Average Complexity Functions xx
  • 21. Software Defects Prevention Techniques – Example Project 33. Estimation - II (50:38) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Marketing MIS: data flow diagram • General Systems Characteristics (GSCs) • Value Adjustment Factor (VAF) • GSC and FPC: Marketing MIS • Marketing MIS: Cost and Price • COnstructive COst MOdel (COCOMO): Intd. • Marketing MIS Modules • Marketing MIS: Pert sizing • COCOMO Equations • COCOMO Cost Drivers (1/2) • COCOMO Cost Drivers (2/2) • Cost Driver Effort Multipliers • Effort Multipliers: Marketing MIS • Marketing MIS: COCOMO Calculations • Effort and Schedule Distribution by Phase (%) • Marketing MIS: Phase Effort and Schedule • Network Precedence: Marketing MIS • Effort Distribution by Activity: Marketing MIS • Critical Path marketing MIS • Gantt Chart/Histogram:Marketing MIS 34. Project Quality Management (58:32) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Definitions of Quality (1/2) • Definitions of Quality (2/2) • Quality Management Gurus • Modern Quality Management Emphasizes on: • Project Quality Management Subprocess • Quality Policy • Strategic Planning for Quality • Quality Characteristics: Illustration • Boehm's Description of Quality • Quality Measurements are Used for: • Illustration: Template for Usability • Quality Benchmarking • Cost of Quality • Quality Planning Process: Outputs • What is Quality Assurance? • Main Goals of Quality Assurance: • Role of QA During Development (1/2) • VV&T Activities in SW Project (1/3) • VV&T Activities in SW Project (2/3) • VV&T Activities in SW Project (3/3) • Opportunity for Improvement (OFI) xxi
  • 22. Zarko Acimovic • Who Identifies OFI? • Improvement in Practice and Documentation • Quality Control Process • QC is Performed... • Pareto Chart: Illustration • Control Chart: Schematic 35. Quality Management Systems - I (54:43) http://nptel.iitm.ac.in/video.php?subjectId=106101061 36. Quality Management Systems (54:53) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Who is a Process? • Process Capability and Maturity • Concept of Maturity Level • Capability Maturity Models (CMM) • Some of the Existing CMMs • Capability Maturity Model Integrated (CMMI) • CMMI ls Tailorable • Staged Model: Maturity Levels • Maturity level Structure • Structure of Staged Representation • PA Level 2 • PA Level 3 • PA Level 4 • PA Level 5 • Process Visibility with levels • Process Capability with Levels • Continuous Representation • Structure of Continuous Representation • PAs in Staged Representation • Capability and Maturity levels • Progression in Staged model • Progression in Continuous model • When to chose continuous Representation? • implementation Road Map xxii
  • 23. Software Defects Prevention Techniques – Example Project 37. Project Configuration Management (53:00) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Change Control System: Schematic • What is Configuration Management(CM)? • CM Functions • Typical Application Specific Cls • Versioning of Cls • Concept of Baseline • Configuration Control • Change Control Procedure (1/2) • Change Control Procedure (2/2) • Configuration Status Accounting • Configuration Audit • Configuration Management Plan 38. Project Risk Management (56:04) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Project Risk Management Processes • Risk Management Planning Process • Risk Manage. Planning Process: Outputs • Risk identification Process Involves: • Risk Analysis Processes • Qualitative Risk Analysis Process • Illustration: Risk Impact Rating Table • Impact, Frequency, and Risk Exposure • Illustration: Quantitative Risk Analysis • Risk Response Planning Process (2/2) • Lessening the Risks • Contingency Actions • Risk Monitoring and Control Process • Illustration: Tracking The Top 10 Risks 39. Other PM Processes (55:41) http://nptel.iitm.ac.in/video.php?subjectId=106101061 • Other Project Management Processes • Project Cost Management Processes • Illustration: Cost Budget (1/2) • Illustration: Cost Budget (2/2) • Human Resource Management Processes • Impact of Organization Structure on Projects • Typical Software Project Organization • Software Development Responsibilities Need to be shared by all stakeholders • Illustration: Responsibility Assignment Matrix • Project Communications Management Processes • Illustration: Stakeholder Communications Analysis xxiii
  • 24. Zarko Acimovic • Project Reporting and Review: Schematic • Administrative Closure Process Covers: • Administrative Closure Process Outputs • Project Procurement Management Processes • Project Integration Management Involves: • Outputs from Project Plan Process: Uses • Objectives of Overall Change Control Process • Integrated Change Control Involves: • Organizational Learning • Role of PM • Important Skills for Project Manager • Engineers vs. Managers 2 AUTOMATIC TOOLS FOR DEFECT PREVENTION Prototyping (modeling) defect prevention method has efficiency 52%. Before implementing this method defect potential per 1 FP (function point) was 5, after, 2.4. Tool: ArgoUML Static analysis of source code defect prevention method has efficiency 44%. Defect potential per 1 FP was 5, after implementing this method is 2.8. Tool: Coverity Mathematical test case design defect prevention efficiency was 34%. Defect potential per 1 FP is 5, after is 3.3. Tool: Bullseye Bonus: Root cause analysis 1044-1993 - IEEE Standard Classification for Software Anomalies. Efficiency 41% - Before 5 – After 2.95 Source: Chapter 3. Estimating and Measuring Software Quality. The Economics of Software Quality, ISBN: 9780132564762 , Capers Jones, Olivier Bonsignour http://www.amazon.com/Economics-Software-Quality-Capers-Jones/dp/0132582201 http://www.informit.com/store/product.aspx?isbn=0132582201 xxiv
  • 25. Software Defects Prevention Techniques – Example Project 3 TOOLS FOR DEFECT PREVENTION IN JAVA SOFTWARE PROJECTS Source: http://codedependents.com/2009/07/01/top-5-static-analysis-plugins-for-eclipse/ Code Coverage tool EclEmma http://www.eclemma.org/ Byte Code Analysis FindBugs http://findbugs.sourceforge.net/ Code Complexity Analysis http://www.stateofflow.com/projects/16/eclipsemetrics Dependency Analysis JDepend4Eclipse http://andrei.gmxhome.de/jdepend4eclipse/ Source Code Analysis PMD http://pmd.sourceforge.net/ 4 SAMPLE PROJECT SPECIFICATION Project duration 3 months, single developer , 5000 lines of code (including comments), 15 Java 2 Micro Edition classes Tools used: Sun J2ME Wireless Toolkit, Eclipse, IBM WebSphere Device Developer 5.5, CVS, Motorola and Nokia phone emulators and SDKs. Technology: J2ME, MIDP 2.0, CLDC 1.1. Device-independent Java 2 Micro Edition (J2ME) midlet, executable in any emulator or mobile device, for displaying map with scale, following moving objects, zoom in-out and pan, selection of location , measuring distance, following individual or vehicle on map with route presentation, presentation of waypoints on map, presentation of list of existing waypoints (sorted by name, type, distance) for selecting destination or editing and deletion, creating, editing and deletion of waypoint – points with coordinates, name, type, icon; coordinates are defined by current position, selected location on map or inserted in textual form, selection of waypoint as destination and navigation towards that destination. Some classes implemented: MapBackground, MapObject, Point, SelectorPoint, PVector, MapsMIDlet Project demo web site: https://sites.google.com/site/j2memaps/ xxv
  • 26. Zarko Acimovic 5 PMD, FINDBUGS AND STATEOFFLOW VIOLATIONS IN SOURCE CODE Here are the violations detected in CommaHyphenString.java Description/ Line/ Type of tool Description Line Type All classes and interfaces must belong to a named package 9 PMD Marker Unused field: CommaHyphenString.lastIndex 12 FindBugs Use explicit scoping instead of the default package private level 12 PMD Marker Document empty constructor 13 PMD Marker Lines of Code in Method is 27 16 Metrics Marker Number of Statements is 28 16 Metrics Marker Avoid variables with short names like s 19 PMD Marker Parameter 's' is not assigned and could be declared final 19 PMD Marker Use explicit scoping instead of the default package private level 19 PMD Marker Local variable 'lastIndex' could be declared final 20 PMD Marker Avoid variables with short names like ss 22 PMD Marker A method should have only one exit point, and that should be the last statement in the method 24 PMD Marker Avoid variables with short names like v 27 PMD Marker Consider replacing this Vector with the newer java.util.List 27 PMD Marker Local variable 'v' could be declared final 27 PMD Marker Use ArrayList instead of Vector 27 PMD Marker Avoid variables with short names like ss 35 PMD Marker Lines of Code in Method is 16 44 Metrics Marker Avoid variables with short names like s 47 PMD Marker Parameter 's' is not assigned and could be declared final 47 PMD Marker Use explicit scoping instead of the default package private level 47 PMD Marker Avoid using if statements without curly braces 53 PMD Marker CommaHyphenString.getStringsOnly(String) concatenates strings using + in a loop 54 FindBugs Prefer StringBuffer over += for concatenating strings 54 PMD Marker Parameter 's' is not assigned and could be declared final 65 PMD Marker Use explicit scoping instead of the default package private level 65 PMD Marker Here is the CommaHyphenString.java source code 1 /** 2 * 3 * CommaHyphenString parses .properties file. It eliminates commas or low lines 4 * from .properties file so items in it( such as categories) could be properly 5 * showed on screen 6 */ 7 import java.util.*; 8 xxvi
  • 27. Software Defects Prevention Techniques – Example Project 9 public class CommaHyphenString { 10 11 //String s; 12 int lastIndex; 13 CommaHyphenString(){} 14 15 16 /** Eliminates commas, returns array of strings with low line 17 * @return String[] 18 */ 19 String[] getWithLowLine(String s) { 20 int lastIndex = defineLast(s); 21 if(lastIndex==0){ 22 String[] ss = new String[1]; 23 ss[0] = s; 24 return ss; 25 } else { 26 int start = -1; 27 Vector v = new Vector(); 28 int current = s.indexOf(','); 29 do { 30 v.addElement(s.substring(start+1,current)); 31 start = current; 32 current = s.indexOf(',',current+1); 33 } while (start!=lastIndex); 34 35 String[] ss = new String[v.size()+1]; 36 for(int i=0; i<v.size(); i++){ 37 ss[i] = (String)v.elementAt(i); 38 } 39 ss[v.size()] = s.substring(lastIndex+1,s.length()); 40 return ss; 41 } 42 } 43 44 /** Eliminates low line 45 * @return String[] 46 */ 47 String[] getStringsOnly(String s){ 48 String[] temp = this.getWithLowLine(s); 49 for (int i=0; i<temp.length; i++){ 50 char[] tempChar = temp[i].toCharArray(); 51 String k = ""; 52 for (int j=0; j<tempChar.length; j++){ 53 if(tempChar[j]=='_') tempChar[j]=' '; 54 k+=tempChar[j]; 55 } 56 temp[i] = k; 57 } 58 return temp; 59 } xxvii
  • 28. Zarko Acimovic 60 61 62 /** Returns categories with low line 63 * @return String[] 64 */ 65 String[] getCategoriesHyphen(String s){ 66 return this.getWithLowLine(s); 67 } 68 69 /** Returns categories 70 * @return String[] 71 */ 72 String[] getCategories(String s){ 73 return this.getStringsOnly(s); 74 } 75 76 /** Defines index of last comma in string 77 * @return integer 78 */ 79 public int defineLast(String s){ 80 int lastIndex = 0; 81 char c[] = s.toCharArray(); 82 for (int i=0; i<c.length; i++){ 83 if(c[i]==',') lastIndex=i; 84 } 85 return lastIndex; 86 } 87 88 } xxviii
  • 29. Software Defects Prevention Techniques – Example Project CompassCanvas.java violations All classes and interfaces must belong to a named package 10 PMD Marker Lack of Cohesion in Methods (Henderson-Sellers) is 75% 10 Metrics Marker Lack of Cohesion in Methods (Total Correlation) is 1,668% 10 Metrics Marker Number of Fields is 23 10 Metrics Marker The class 'CompassCanvas' has a Cyclomatic Complexity of 6 (Highest = 17). 10 PMD Marker To be compliant to J2EE, a webapp should not use any thread. 10 PMD Marker Too many fields 10 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 11 PMD Marker Use explicit scoping instead of the default package private level 11 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 12 PMD Marker Use explicit scoping instead of the default package private level 12 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 13 PMD Marker Use explicit scoping instead of the default package private level 13 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 14 PMD Marker Use explicit scoping instead of the default package private level 14 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 15 PMD Marker Use explicit scoping instead of the default package private level 15 PMD Marker Avoid variables with short names like c 18 PMD Marker Unused field: CompassCanvas.c 18 FindBugs Avoid variables with short names like t 20 PMD Marker To be compliant to J2EE, a webapp should not use any thread. 20 PMD Marker Unread field: CompassCanvas.switchVar 22 FindBugs Unread field: CompassCanvas.switched 23 FindBugs It is a good practice to call super() in a constructor 38 PMD Marker Lines of Code in Method is 24 38 Metrics Marker Number of Statements is 33 38 Metrics Marker Parameter 'mob' is not assigned and could be declared final 38 PMD Marker Avoid empty catch blocks 53 PMD Marker Avoid empty catch blocks 57 PMD Marker To be compliant to J2EE, a webapp should not use any thread. 59 PMD Marker Avoid really long methods. 63 PMD Marker Avoid variables with short names like g 63 PMD Marker Cyclomatic Complexity is 10 63 Metrics Marker Lines of Code in Method is 220 63 Metrics Marker Number of Statements is 418 63 Metrics Marker Parameter 'g' is not assigned and could be declared final 63 PMD Marker The method 'paint' has a Cyclomatic Complexity of 17. 63 PMD Marker The method paint() has an NCSS count of 144 63 PMD Marker The method paint() has an NPath complexity of 4375 63 PMD Marker Avoid unnecessary comparisons in boolean expressions 68 PMD Marker xxix
  • 30. Zarko Acimovic CompassCanvas.java violations - continued Avoid unused local variables such as 'mediumX'. 122 PMD Marker Dead store to mediumX in CompassCanvas.paint(Graphics) 122 FindBugs The local variable mediumX is never read 122 Java Problem Avoid unused local variables such as 'mediumY'. 123 PMD Marker Dead store to mediumY in CompassCanvas.paint(Graphics) 123 FindBugs The local variable mediumY is never read 123 Java Problem Avoid unnecessary comparisons in boolean expressions 285 PMD Marker CompassCanvas.java source code 1 /** 2 * 3 * ComapssCanvas draws compass on screen 4 */ 5 import javax.microedition.lcdui.*; 6 //import javax.microedition.midlet.*; 7 8 9 10 public class CompassCanvas extends Canvas implements Runnable{ 11 long north; 12 long south; 13 long east; 14 long west; 15 int bigRadius; 16 int smallRadius; 17 int smallestRadius; 18 Coordinates c; 19 long delta = 0; 20 Thread t; 21 boolean end = false; 22 boolean switchVar = false; 23 boolean switched = false; 24 MapObjects mob; 25 26 int dummy1 = 0; 27 int dummy2 = 0; 28 int dummy3 = 0; xxx
  • 31. Software Defects Prevention Techniques – Example Project 29 int dummy4 = 0; 30 Image img; 31 32 Image imgDest; 33 long destUp; 34 long destDown; 35 long gama; 36 37 38 CompassCanvas(MapObjects mob){ 39 this.mob = mob; 40 north = MathFP.toFP("0"); 41 south = MathFP.div(Coordinates.MathFP_2PI,MathFP.toFP("2")); 42 east = MathFP.mul(Coordinates.MathFP_2PI,MathFP.toFP("0.25")); 43 west = MathFP.mul(Coordinates.MathFP_2PI,MathFP.toFP("0.75")); 44 45 destUp = MathFP.toFP("0"); 46 destDown = MathFP.div(Coordinates.MathFP_2PI,MathFP.toFP("2")); 47 48 bigRadius = Math.min(this.getWidth(),this.getHeight()); 49 smallRadius = (int)(0.75*bigRadius); 50 smallestRadius = (int)(0.37*bigRadius); 51 try{ 52 img = Image.createImage("Arrow2.jpg"); 53 }catch(Exception e){} 54 55 try{ 56 imgDest = Image.createImage("Dest.jpg"); 57 }catch(Exception e){} 58 59 t = new Thread(this); 60 t.start(); 61 } 62 63 public void paint(Graphics g){ 64 //System.out.println("delta="+MathFP.toString(delta)); 65 g.setColor(255,255,255); 66 g.fillRect(0,0,this.getWidth(),this.getHeight()); 67 g.setColor(0,0,0); 68 if(end == false){ 69 g.drawImage(img,75,25,0); 70 71 //System.out.println("this.getWidth()="+this.getWidth()); 72 //System.out.println("this.getHeight()="+this.getHeight()); 73 g.drawArc(8,0,bigRadius,bigRadius,0,360); 74 g.drawArc(30,22,smallRadius,smallRadius,0,360); 75 xxxi
  • 32. Zarko Acimovic 76 String sx = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(Ma thFP.sub(north,delta))))); 77 String sy = MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(Ma thFP.sub(north,delta))))); 78 int ix = sx.indexOf('.'); 79 sx = sx.substring(0,ix); 80 int iy = sy.indexOf('.'); 81 sy = sy.substring(0,iy); 82 83 int x = Integer.parseInt(sx); 84 int y = Integer.parseInt(sy); 85 86 String s9 = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(smallestRadius),M athFP.sin(MathFP.sub(north,delta))))); 87 ix = s9.indexOf('.'); 88 s9 = s9.substring(0,ix); 89 int NX = Integer.parseInt(s9); 90 String s10 = MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),M athFP.cos(MathFP.sub(north,delta))))); 91 iy = s10.indexOf('.'); 92 s10 = s10.substring(0,iy); 93 int NY = Integer.parseInt(s10); 94 95 g.drawString("N",x,y,0); 96 97 sx = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(Ma thFP.sub(south,delta))))); 98 sy = MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(Ma thFP.sub(south,delta))))); 99 ix = sx.indexOf('.'); 100 sx = sx.substring(0,ix); 101 iy = sy.indexOf('.'); 102 sy = sy.substring(0,iy); 103 104 x = Integer.parseInt(sx); 105 y = Integer.parseInt(sy); 106 107 String s11 = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(smallestRadius),M athFP.sin(MathFP.sub(south,delta))))); 108 ix = s11.indexOf('.'); 109 s11 = s11.substring(0,ix); 110 int SX = Integer.parseInt(s11); xxxii
  • 33. Software Defects Prevention Techniques – Example Project 111 String s12 = MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),M athFP.cos(MathFP.sub(south,delta))))); 112 iy = s12.indexOf('.'); 113 s12 = s12.substring(0,iy); 114 int SY = Integer.parseInt(s12); 115 116 117 118 g.drawString("S",x,y,0); 119 int del = 0; 120 g.drawLine(NX-del,NY-del,SX-del,SY-del); 121 122 int mediumX = (int)Math.abs((NX-SX)/2); 123 int mediumY = (int)Math.abs((NY-SY)/2); 124 125 String s1 = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(10),MathFP.sin(Ma thFP.sub(east,delta))))); 126 String s2 = MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(10),MathFP.cos(Ma thFP.sub(east,delta))))); 127 128 String s3 = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(10),MathFP.sin(Ma thFP.sub(west,delta))))); 129 String s4 = MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(10),MathFP.cos(Ma thFP.sub(west,delta))))); 130 131 ix = s1.indexOf('.'); 132 s1 = s1.substring(0,ix); 133 dummy1 = Integer.parseInt(s1); 134 135 ix = s2.indexOf('.'); 136 s2 = s2.substring(0,ix); 137 dummy2 = Integer.parseInt(s2); 138 139 ix = s3.indexOf('.'); 140 s3 = s3.substring(0,ix); 141 dummy3 = Integer.parseInt(s3); 142 143 ix = s4.indexOf('.'); 144 s4 = s4.substring(0,ix); 145 dummy4 = Integer.parseInt(s4); 146 147 g.drawLine(NX-del,NY-del,dummy1,dummy2); 148 g.drawLine(dummy1,dummy2,SX-del,SY-del); 149 g.drawLine(NX-del,NY-del,dummy3,dummy4); 150 g.drawLine(dummy3,dummy4,SX-del,SY-del); 151 xxxiii
  • 34. Zarko Acimovic 152 sx = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(Ma thFP.sub(east,delta))))); 153 sy = MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(Ma thFP.sub(east,delta))))); 154 ix = sx.indexOf('.'); 155 sx = sx.substring(0,ix); 156 iy = sy.indexOf('.'); 157 sy = sy.substring(0,iy); 158 159 x = Integer.parseInt(sx); 160 y = Integer.parseInt(sy); 161 162 g.drawString("E",x,y,0); 163 164 sx = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(Ma thFP.sub(west,delta))))); 165 sy = MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(Ma thFP.sub(west,delta))))); 166 ix = sx.indexOf('.'); 167 sx = sx.substring(0,ix); 168 iy = sy.indexOf('.'); 169 sy = sy.substring(0,iy); 170 171 x = Integer.parseInt(sx); 172 y = Integer.parseInt(sy); 173 174 g.drawString("W",x,y,0); 175 176 177 178 179 gama = MathFP.sub(delta,gama); 180 //gama = MathFP.toFP("314"); 181 long gamaDegrees = Coordinates.radiansToDegrees(gama); 182 //long gamaDegrees = gama; 183 //System.out.println("gama="+MathFP.toString(gamaDegrees)); 184 //gama = Coordinates.degreesToRadians(gama); 185 186 long corrX = MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(smallestRadius),MathFP.sin(MathFP .sub(destUp,gama)))); 187 long corrY = MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),MathFP.cos(MathFP .sub(destUp,gama)))); 188 xxxiv
  • 35. Software Defects Prevention Techniques – Example Project 189 long dx = 0; 190 long dy = 0; 191 192 if(gamaDegrees<=0) { 193 gama = MathFP.add(gama,Coordinates.MathFP_2PI); 194 gamaDegrees = MathFP.add(gamaDegrees,MathFP.toFP("360")); 195 } 196 197 // Correction of position for imgDest 198 if(MathFP.toFP("0")<=gamaDegrees && gamaDegrees <MathFP.toFP("10")){ 199 dx = 0- MathFP.mul(MathFP.toFP("10"),MathFP.cos(gama)); 200 dy = 0- MathFP.mul(MathFP.toFP("23"),MathFP.cos(gama)); 201 } 202 203 204 if(MathFP.toFP("10")<=gamaDegrees && gamaDegrees <MathFP.toFP("50")){ 205 dx = 0- MathFP.mul(MathFP.toFP("25"),MathFP.cos(gama)); 206 dy = 0- MathFP.mul(MathFP.toFP("23"),MathFP.cos(gama)); 207 } 208 209 if(MathFP.toFP("50")<=gamaDegrees && gamaDegrees <MathFP.toFP("67")){ 210 dx = 0- MathFP.mul(MathFP.toFP("40"),MathFP.cos(gama)); 211 dy = 0- MathFP.mul(MathFP.toFP("30"),MathFP.cos(gama)); 212 } 213 214 if(MathFP.toFP("67")<=gamaDegrees && gamaDegrees <MathFP.toFP("85")){ 215 dx = 0- MathFP.mul(MathFP.toFP("25"),MathFP.sin(gama)); 216 dy = 0- MathFP.mul(MathFP.toFP("12"),MathFP.sin(gama)); 217 } 218 219 if(MathFP.toFP("85")<=gamaDegrees && gamaDegrees<MathFP.toFP("175")){ 220 dx = 0- MathFP.mul(MathFP.toFP("25"),MathFP.sin(gama)); 221 dy = 0- MathFP.mul(MathFP.toFP("12"),MathFP.sin(gama)); 222 } xxxv
  • 36. Zarko Acimovic 223 224 225 if(MathFP.toFP("175")<=gamaDegrees && gamaDegrees<MathFP.toFP("275")){ 226 dx = MathFP.mul(MathFP.toFP("7"),MathFP.cos(gama)); 227 dy = MathFP.mul(MathFP.toFP("7"),MathFP.sin(gama)); 228 } 229 230 if(MathFP.toFP("275")<=gamaDegrees && gamaDegrees<=MathFP.toFP("360")){ 231 dx = 0- MathFP.mul(MathFP.toFP("8"),MathFP.cos(gama)); 232 dy = 0- MathFP.mul(MathFP.toFP("25"),MathFP.cos(gama)); 233 234 } 235 236 237 238 239 long prevCorrX=corrX; 240 long prevCorrY=corrY; 241 242 corrX = MathFP.add(corrX,dx); 243 corrY = MathFP.add(corrY,dy); 244 245 246 247 sx = MathFP.toString(corrX); 248 sy = MathFP.toString(corrY); 249 ix = sx.indexOf('.'); 250 sx = sx.substring(0,ix); 251 iy = sy.indexOf('.'); 252 sy = sy.substring(0,iy); 253 int xbear1 = Integer.parseInt(sx); 254 int ybear1 = Integer.parseInt(sy); 255 256 257 sx = MathFP.toString(prevCorrX); 258 sy = MathFP.toString(prevCorrY); 259 ix = sx.indexOf('.'); 260 sx = sx.substring(0,ix); 261 iy = sy.indexOf('.'); 262 sy = sy.substring(0,iy); 263 int xbear3 = Integer.parseInt(sx); 264 int ybear3 = Integer.parseInt(sy); 265 266 267 xxxvi
  • 37. Software Defects Prevention Techniques – Example Project 268 sx = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(smallestRadius),M athFP.sin(MathFP.sub(destDown,gama))))); 269 sy = MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),M athFP.cos(MathFP.sub(destDown,gama))))); 270 271 272 ix = sx.indexOf('.'); 273 sx = sx.substring(0,ix); 274 iy = sy.indexOf('.'); 275 sy = sy.substring(0,iy); 276 int xbear2 = Integer.parseInt(sx); 277 int ybear2 = Integer.parseInt(sy); 278 279 g.drawLine(xbear2,ybear2,xbear3,ybear3); 280 g.drawImage(imgDest,xbear1,ybear1,0); 281 } 282 } 283 284 public void run(){ 285 while(end == false){ 286 delta = mob.getDirection(); 287 gama = mob.getBearing(); 288 repaint(); 289 try{ 290 Thread.sleep(100); 291 }catch(Exception e){} 292 293 } 294 } 295 296 public void setEnd(){ 297 end = true; 298 } 299 300 } xxxvii
  • 38. Zarko Acimovic Coordinates.java violations All classes and interfaces must belong to a named package 9 PMD Marker Lack of Cohesion in Methods (Henderson-Sellers) is 100% 9 Metrics Marker Lack of Cohesion in Methods (Pairwise Field Irrelation) is 100% 9 Metrics Marker Lack of Cohesion in Methods (Total Correlation) is 100% 9 Metrics Marker Parameter 'latitude' is not assigned and could be declared final 38 PMD Marker Parameter 'longitude' is not assigned and could be declared final 38 PMD Marker Parameter 'original' is not assigned and could be declared final 47 PMD Marker Parameter 'latitude' is not assigned and could be declared final 74 PMD Marker Parameter 'longitude' is not assigned and could be declared final 82 PMD Marker Avoid variables with short names like to 92 PMD Marker Cyclomatic Complexity is 6 95 Metrics Marker Lines of Code in Method is 47 95 Metrics Marker Number of Statements is 47 95 Metrics Marker Local variable 'deltaLat' could be declared final 107 PMD Marker Avoid using if statements without curly braces 122 PMD Marker A method should have only one exit point, and that should be the last statement in the method 123 PMD Marker Avoid using if statements without curly braces 125 PMD Marker A method should have only one exit point, and that should be the last statement in the method 127 PMD Marker Avoid using if...else statements without curly braces 127 PMD Marker A method should have only one exit point, and that should be the last statement in the method 129 PMD Marker Avoid using if...else statements without curly braces 129 PMD Marker Avoid using if statements without curly braces 139 PMD Marker Avoid variables with short names like to 148 PMD Marker Coordinates.java source code 1 /** 2 * 3 * Coordinates class different performs geographical calculations 4 */ 5 6 7 8 //import net.jscience.math.MathFP; 9 public class Coordinates { 10 /** 11 * Earth's radius (in meters) 12 */ 13 public static final long EARTH_RADIUS = MathFP.toFP(6367000); 14 public static final long EARTH_RADIUS2 = MathFP.toFP(6367000*2); 15 /** 16 * the WGS-84 latitude of a location 17 */ xxxviii
  • 39. Software Defects Prevention Techniques – Example Project 18 private long latitude; 19 /** 20 * the WGS-84 longitude of a location 21 */ 22 private long longitude; 23 /** 24 * The altitude of the location in meters, defined as height above WGS-84 ellipsoid. Float.NaN can be used to indicate that the altitude is not known. 25 */ 26 27 28 /** 29 * Constructor 30 * @param latitude latitude as WGS-84 system coordinate 31 * @param longitude longitude as WGS-84 system coordinate 32 * @param altitude the altitude in meters, if known, or Float.NaN 33 * @param timestamp the time when information stored in this object was created, in milliseconds since midnight January 1, 1970 GMT, or -1 34 * @param source the short string describing where data contained in this object came from, like "GPS", "Network", "Database", etc 35 * @param horizontalAccuracy the horizontal accuracy of coordinates in meters, or Float.NaN 36 * @param verticalAccuracy vertical accuracy of coordinates in meters, or Float.NaN 37 */ 38 public Coordinates(long latitude, long longitude){ 39 this.latitude=latitude; 40 this.longitude=longitude; 41 } 42 43 /** 44 * Copy constructor 45 * @param original copied object 46 */ 47 public Coordinates(Coordinates original){ 48 this.latitude=original.latitude; 49 this.longitude=original.longitude; 50 } 51 52 53 /** 54 * The WGS-84 latitude of a location 55 * @return WGS-84 latitude 56 */ 57 public long getLatitude(){ 58 return latitude; 59 } 60 61 /** 62 * The WGS-84 longitude of a location 63 * @return WGS-84 longitude xxxix
  • 40. Zarko Acimovic 64 */ 65 public long getLongitude(){ 66 return longitude; 67 } 68 69 70 /** 71 * Set latitude as WGS-84 system coordinate. 72 * @param latitude latitude as WGS-84 system coordinate 73 */ 74 public void setLatitude(long latitude){ 75 this.latitude=latitude; 76 } 77 78 /** 79 * Set longitude as WGS-84 system coordinate. 80 * @param longitude longitude as WGS-84 system coordinate 81 */ 82 public void setLongitude(long longitude){ 83 this.longitude=longitude; 84 } 85 86 /** 87 * Calculate bearing to another location on the surface of the Earth, using the Great Circle. 88 * bearing - 1.way of behaving 2.connection 3.direction shown by compass 4.understanding of one's position 89 * @param to another point 90 * @return long representing angle in degrees [0,360) between corresponding meridian in first point and line on the Great Circle between those points 91 */ 92 public long bearing(Coordinates to){ 93 return bearing(getLatitude(), getLongitude(), to.getLatitude(), to.getLongitude()); 94 } 95 /** 96 * Calculate bearing between points (latFrom, lonFrom) and (latTo,lonTo) on the surface of the Earth, using the Great Circle. 97 * @param latFrom latitude of the first point 98 * @param lonFrom longitude of the first point 99 * @param latTo latitude of the second point 100 * @param lonTo longitude of the second point 101 * @return long representing angle in degrees [0,360) between corresponding meridian in first point and line on the Great Circle between those points 102 */ 103 protected static long bearing(long latFrom, long lonFrom, long latTo, long lonTo){ 104 //BMa: Some numeric with MathFP still happen - but error is mostly below 16 degrees xl
  • 41. Software Defects Prevention Techniques – Example Project 105 // This should be fixed only if the final target device stays without not have floats or doubles (e.g. it is not CLDC 1.1) 106 long bearing; 107 long deltaLat=latTo-latFrom; 108 long deltaLon=lonTo-lonFrom; 109 if (MathFP.abs(deltaLat)<MathFP_1 && MathFP.abs(deltaLon)<MathFP_1) { 110 // longiude and latitude distance within one deegre, could invent better condition 111 //This approximation works better for smaller distances 112 latFrom = degreesToRadians(latFrom); 113 deltaLon=MathFP.mul(deltaLon, MathFP.cos(latFrom)); 114 bearing = MathFP.atan2(deltaLat,deltaLon); 115 }else{ 116 latFrom = degreesToRadians(latFrom); 117 latTo = degreesToRadians(latTo); 118 lonFrom = degreesToRadians(lonFrom); 119 lonTo = degreesToRadians(lonTo); 120 121 122 if (latFrom==latTo && lonFrom==lonTo) 123 return 0; 124 //if (MathFP.cos(latFrom) < Double.MIN_VALUE) // Double.MIN_VALUE a small number ~ machine precision, so here we check for +/-0 125 if (MathFP.cos(latFrom) == 0 ) // Double.MIN_VALUE a small number ~ machine precision, so here we check for +/-0 126 if (latFrom > 0) 127 return MathFP.PI; // starting from N pole 128 else 129 return MathFP_2PI; // starting from S pole 130 //double bearing = radiansToDegrees(Math.atan2(Math.sin(lon2- lon1)*Math.cos(lat2),Math.cos(lat1)*Math.sin(lat2)- Math.sin(lat1)*Math.cos(lat2)*Math.cos(lon2-lon1))%(2*Math.PI)); 131 132 bearing = MathFP.atan2( 133 MathFP.mul(MathFP.sin(deltaLon),MathFP.cos(latTo)), 134 MathFP.mul(MathFP.cos(latFrom),MathFP.sin(latTo))- 135 MathFP.mul(MathFP.mul(MathFP.sin(latFrom),MathFP.cos(latTo)),MathFP.cos(deltaLon))) ; 136 } 137 bearing = MathFP.mod(radiansToDegrees(bearing), MathFP_360); 138 139 if (bearing<0) bearing = MathFP_360 + bearing; 140 return bearing; 141 } 142 143 /** 144 * Calculate distance to another location on the surface of the Earth, using the Great Circle. 145 * @param to another point xli
  • 42. Zarko Acimovic 146 * @return distance to another location in meters, using the line on the Great Circle 147 */ 148 public long distance(Coordinates to){ 149 //BMa: Some numeric with MathFP are still possible - errors happen sometimes 150 // This should be fixed only if the final target device stays without not have floats or doubles (e.g. it is not CLDC 1.1) 151 return calculateDistance(getLatitude(), getLongitude(), to.getLatitude(), to.getLongitude()); 152 } 153 154 /** 155 * Calculate distance between points (latFrom, lonFrom) and (latTo,lonTo) on the surface of the Earth, using the Great Circle. 156 * lat , lon - degrees ([-90, +90]; [-180, +180]) 157 * 158 * @param latFrom latitude of the first point 159 * @param lonFrom longitude of the first point 160 * @param latTo latitude of the second point 161 * @param lonTo longitude of the second point 162 * @return distance to another location in meters, using the line on the Great Circle 163 */ 164 public static long calculateDistance(long latFrom, long lonFrom, long latTo, long lonTo){ 165 /* 166 * d=2*asin(sqrt((sin((latFrom-latTo)/2))^2 + cos(latFrom)*cos(latTo)*(sin((lonFrom-lonTo)/2))^2)) 167 * or 168 * d=2*asin(sqrt((sin((latFrom-latTo)/2))^2 + cos(latFrom)*cos(latTo)*(sin((lonTo-lonFrom)/2))^2)) 169 * distance = R*d 170 */ 171 172 latFrom = degreesToRadians(latFrom); 173 latTo = degreesToRadians(latTo); 174 lonFrom = degreesToRadians(lonFrom); 175 lonTo = degreesToRadians(lonTo); 176 //long distance = R * MathFP.acos(MathFP.sin(latFrom)*MathFP.sin(latTo) + MathFP.cos(latFrom)*MathFP.cos(latTo)*MathFP.cos(lonTo-lonFrom)); 177 /* 178 double distance = R * 2 * Math.asin( 179 Math.sqrt( 180 Math.pow(Math.sin((lat1-lat2)/2), 2) 181 + 182 Math.cos(lat1)*Math.cos(lat2)*Math.pow(Math.sin((lon2-lon1)/2), 2) 183 ) 184 ); 185 */ xlii
  • 43. Software Defects Prevention Techniques – Example Project 186 187 /* 188 System.out.print("latFrom: "+MathFP.toString(latFrom)); 189 System.out.println(" lonFrom: "+MathFP.toString(lonFrom)); 190 System.out.print("latTo: "+MathFP.toString(latTo)); 191 System.out.println(" lonTo: "+MathFP.toString(lonTo)); 192 */ 193 194 long p1=MathFP.sin(MathFP.div((latFrom-latTo), MathFP_2)); 195 p1 = MathFP.mul(p1, MathFP.toFP(1000000)); 196 //System.out.println(" p1: "+MathFP.toString(p1)); 197 p1 = MathFP.mul(p1, p1); 198 //System.out.println(" p1: "+MathFP.toString(p1)); 199 200 long p2=MathFP.sin(MathFP.div((lonTo-lonFrom), MathFP_2)); 201 p2 = MathFP.mul(p2, MathFP.toFP(1000000)); 202 //System.out.println(" p2: "+MathFP.toString(p2)); 203 p2 = MathFP.mul(p2, p2); 204 //System.out.println(" p2: "+MathFP.toString(p2)); 205 206 long sqrtarg=p1 +MathFP.mul(MathFP.mul(MathFP.cos(latFrom),MathFP.cos(latTo)),p2); 207 //System.out.println(" sqrtarg: "+MathFP.toString(sqrtarg)); 208 209 sqrtarg=MathFP.sqrt(sqrtarg); 210 //System.out.println(" sqrtarg: "+MathFP.toString(sqrtarg)); 211 212 long distance; 213 if (sqrtarg>MathFP.toFP(19000)) { //toFP("0.019")*1000000 - boundary for MathFP.asin approximation by X 214 // calculation is erroneus for small angles 215 long asinarg=MathFP.div(sqrtarg, MathFP.toFP(1000000)); 216 //System.out.println(" > asinarg: "+MathFP.toString(asinarg)); 217 asinarg=MathFP.asin(asinarg); 218 //System.out.println(" > asinarg: "+MathFP.toString(asinarg)); 219 distance = MathFP.mul(EARTH_RADIUS2, asinarg); 220 //System.out.println(" distance asin: "+MathFP.toString(distance)); 221 } else { 222 //asin(X) is aproximately equall to X, 223 //This approximation allow us to change the order of multiplication and division in order to reduce loss of significant digits 224 225 distance = MathFP.mul(EARTH_RADIUS2, sqrtarg); 226 //System.out.println(" > distance: "+MathFP.toString(distance)); 227 distance=MathFP.div(distance, MathFP.toFP(1000000)); 228 229 } 230 231 //System.out.println(" distance: "+MathFP.toString(distance)); 232 233 //if (Double.isNaN(distance)) //equivalent to (distance=0), but safer xliii
  • 44. Zarko Acimovic 234 // return 0; 235 return distance; 236 } 237 238 239 /** 240 * Convert degrees to radians 241 * @return value transformed to radians 242 * @param degrees value to be transformed to radians 243 */ 244 public static long degreesToRadians(long degrees){ 245 return MathFP.div(degrees,MathFP_180DivPI); 246 } 247 248 /** 249 * Convert radians to degrees 250 * @return value transformed to degrees 251 * @param radians value to be transformed to degrees 252 */ 253 public static long radiansToDegrees(long radians){ 254 return MathFP.mul(radians,MathFP_180DivPI); 255 } 256 257 public static final long MathFP_2 = MathFP.toFP(2); 258 public static final long MathFP_1 = MathFP.toFP(1); 259 public static final long MathFP_2PI = MathFP.mul(MathFP_2, MathFP.PI); 260 public static final long MathFP_1000 = MathFP.toFP(1000); 261 public static final long MathFP_360 = MathFP.toFP(360); 262 public static final long MathFP_180DivPI = MathFP.div(MathFP.toFP(180), MathFP.PI); 263 public static final long MathFP_0_5 = MathFP.toFP("0.5"); 264 265 266 } xliv
  • 45. Software Defects Prevention Techniques – Example Project DelRoute.java violations All classes and interfaces must belong to a named package 5 PMD Marker Lack of Cohesion in Methods (Pairwise Field Irrelation) is 67% 5 Metrics Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 6 PMD Marker Use explicit scoping instead of the default package private level 6 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 7 PMD Marker Use explicit scoping instead of the default package private level 7 PMD Marker Parameter 'index' is not assigned and could be declared final 8 PMD Marker Parameter 'routeID' is not assigned and could be declared final 8 PMD Marker Use explicit scoping instead of the default package private level 12 PMD Marker 1 /** 2 * 3 * DelRoute is used when deleting route 4 */ 5 public class DelRoute { 6 int index; 7 int routeID; 8 DelRoute(int index, int routeID){ 9 this.index = index; 10 this.routeID = routeID; 11 } 12 int getIndex(){ 13 return index; 14 } 15 int getRouteID(){ 16 return routeID; 17 } 18 19 public String toString(){ 20 return "ID Route is "+routeID+"n"+"Index of element to delet is "+index; 21 } 22 23 } xlv
  • 46. Zarko Acimovic Friend.java violations All classes and interfaces must belong to a named package 5 PMD Marker Lack of Cohesion in Methods (Henderson-Sellers) is 83% 5 Metrics Marker Lack of Cohesion in Methods (Pairwise Field Irrelation) is 96% 5 Metrics Marker Lack of Cohesion in Methods (Total Correlation) is 107% 5 Metrics Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 6 PMD Marker Use explicit scoping instead of the default package private level 6 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 7 PMD Marker Use explicit scoping instead of the default package private level 7 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 8 PMD Marker Use explicit scoping instead of the default package private level 8 PMD Marker Avoid variables with short names like t 9 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 9 PMD Marker Use explicit scoping instead of the default package private level 9 PMD Marker Avoid variables with short names like t 11 PMD Marker Parameter 'hashThread' is not assigned and could be declared final 11 PMD Marker Parameter 'name' is not assigned and could be declared final 11 PMD Marker Parameter 'resource' is not assigned and could be declared final 11 PMD Marker Parameter 't' is not assigned and could be declared final 11 PMD Marker Parameter 'hash' is not assigned and could be declared final 30 PMD Marker A getX() method which returns a boolean should be named isX() 42 PMD Marker 1 /** 2 * 3 * Friend class holds all important data for a friend 4 */ 5 public class Friend { 6 String name; 7 String resource; 8 int hashThread; 9 Thread4Friend t; 10 11 Friend(String name, String resource, int hashThread, Thread4Friend t){ 12 this.name = name; 13 this.resource = resource; 14 this.hashThread = hashThread; 15 this.t = t; 16 } 17 18 public String getName(){ 19 return name; 20 } 21 22 public String getResource(){ xlvi
  • 47. Software Defects Prevention Techniques – Example Project 23 return resource; 24 } 25 26 public int getHash(){ 27 return hashThread; 28 } 29 30 public void setID(int hash){ 31 hashThread = hash; 32 } 33 34 public String toString(){ 35 return "Friend is "+name+"n"+"Hash is "+hashThread; 36 } 37 38 public void setFirst(){ 39 t.setFirst(); 40 } 41 42 public boolean getThread(){ 43 if (t==null){ return false; } 44 else {return true; } 45 } 46 47 public void setThread(Thread4Friend t){ 48 this.t = t; 49 } 50 } xlvii
  • 48. Zarko Acimovic HeapSorter.java violations All classes and interfaces must belong to a named package 5 PMD Marker This class has too many methods, consider refactoring it. 5 PMD Marker Document empty constructor 7 PMD Marker Avoid variables with short names like a 9 PMD Marker Avoid variables with short names like A 10 PMD Marker Avoid variables with short names like as 23 PMD Marker Avoid variables with short names like AS 24 PMD Marker Prefer StringBuffer over += for concatenating strings 30 PMD Marker Avoid variables with short names like a 37 PMD Marker Parameter 'a' is not assigned and could be declared final 37 PMD Marker Avoid using for statements without curly braces 38 PMD Marker Parameter 'as' is not assigned and could be declared final 41 PMD Marker Avoid using for statements without curly braces 42 PMD Marker Lines of Code in Method is 21 45 Metrics Marker Parameter 'i' is not assigned and could be declared final 45 PMD Marker Local variable 'l' could be declared final 46 PMD Marker Local variable 'r' could be declared final 47 PMD Marker Local variable 'tmp' could be declared final 62 PMD Marker Lines of Code in Method is 21 67 Metrics Marker Number of Statements is 21 67 Metrics Marker Parameter 'i' is not assigned and could be declared final 67 PMD Marker Local variable 'l' could be declared final 68 PMD Marker 1 /** 2 * 3 * HeapSorter class sorts points by distance or by name 4 */ 5 public class HeapSorter{ 6 7 HeapSorter(){} 8 9 public void heapsort(long[] a){ 10 long[]A = setHeapWithSize(a,a.length); 11 buildHeap(A); 12 for(int i=0; i<A.length; i++){ 13 System.out.println(A[i]); 14 } 15 for(int i=a.length; i>1; i--){ 16 a[i-1]=A[0]; A[0]=A[i-1]; 17 A=setHeapWithSize(A,A.length-1); 18 heapify(A,1); 19 } xlviii
  • 49. Software Defects Prevention Techniques – Example Project 20 a[0]=A[0]; 21 } 22 23 public void heapsort(String[] as){ 24 String[] AS = setHeapWithSize(as,as.length); 25 buildHeap(AS); 26 for(int i=0; i<AS.length; i++){ 27 System.out.println(AS[i]); 28 } 29 for(int i=as.length; i>1; i--){ 30 as[i-1]=AS[0]; AS[0]=AS[i-1]; 31 AS=setHeapWithSize(AS,AS.length-1); 32 heapify(AS,1); 33 } 34 as[0]=AS[0]; 35 } 36 37 public void buildHeap(long[] a){ 38 for(int i=a.length/2; i>0; i--) heapify(a,i); 39 } 40 41 public void buildHeap(String[] as){ 42 for(int i=as.length/2; i>0; i--) heapify(as,i); 43 } 44 45 public void heapify(long[]a, int i){ 46 int l=left(i); 47 int r=right(i); 48 int largest; 49 50 if(l<=heapSize(a) && a[l-1]>a[i-1]){ 51 largest=l; 52 }else{ 53 largest=i; 54 } 55 56 if(r<=heapSize(a) && a[r-1]>a[largest-1]){ 57 largest=r; 58 } 59 60 if(largest!=i){ 61 //exchange a[i], a[largest] 62 long tmp=a[i-1]; a[i-1]=a[largest-1]; a[largest- 1]=tmp; 63 heapify(a,largest); 64 } 65 } 66 67 public void heapify(String[]as, int i){ 68 int l=left(i); 69 int r=right(i); xlix
  • 50. Zarko Acimovic 70 int largest; 71 72 if(l<=heapSize(as) && as[l-1].charAt(0)>as[i-1].charAt(0)){ 73 largest=l; 74 }else{ 75 largest=i; 76 } 77 78 if(r<=heapSize(as) && as[r-1].charAt(0)>as[largest- 1].charAt(0)){ 79 largest=r; 80 } 81 82 if(largest!=i){ 83 //exchange a[i], a[largest] 84 String tmpS=as[i-1]; as[i-1]=as[largest-1]; as[largest-1]=tmpS; 85 heapify(as,largest); 86 } 87 } 88 89 90 public int heapSize(long a[]){ 91 return a.length; 92 } 93 94 public int heapSize(String as[]){ 95 return as.length; 96 } 97 98 public int parent(int i){ 99 return(i/2); 100 } 101 102 public int left(int i){ 103 return(2*i); 104 } 105 106 public int right(int i){ 107 return(2*i+1); 108 } 109 110 public long[] setHeapWithSize(long[]m , int n){ 111 long[] k = new long[n]; 112 for(int i=0; i<n; i++){ 113 k[i]=m[i]; 114 } 115 return k; 116 } 117 118 public String[] setHeapWithSize(String[]m , int n){ l
  • 51. Software Defects Prevention Techniques – Example Project 119 String[] k = new String[n]; 120 for(int i=0; i<n; i++){ 121 k[i]=m[i]; 122 } 123 return k; 124 } 125 }; ImageCanvas3.java violations All classes and interfaces must belong to a named package 10 PMD Marker Avoid variables with short names like ol 12 PMD Marker Found non-transient, non-static member. Please mark as transient or provide accessors. 12 PMD Marker Use explicit scoping instead of the default package private level 12 PMD Marker Avoid variables with short names like ol 14 PMD Marker It is a good practice to call super() in a constructor 14 PMD Marker Parameter 'ol' is not assigned and could be declared final 14 PMD Marker Avoid variables with short names like g 19 PMD Marker Parameter 'g' is not assigned and could be declared final 19 PMD Marker Cyclomatic Complexity is 8 23 Metrics Marker Lines of Code in Method is 38 23 Metrics Marker Number of Statements is 25 23 Metrics Marker Parameter 'keyCode' is not assigned and could be declared final 23 PMD Marker 1 /** 2 * 3 * ImageCanvas3 draws elements on screen and captures events on canvas 4 */ 5 6 //import java.io.IOException; 7 import javax.microedition.lcdui.*; 8 //import java.util.*; 9 10 public class ImageCanvas3 extends Canvas { 11 12 Outlook ol; 13 14 ImageCanvas3(Outlook ol){ 15 this.ol =ol; 16 ol.setCanvasWH(this.getWidth(),this.getHeight()); 17 } 18 19 public void paint(Graphics g) { 20 ol.drawOutlook(g); 21 } li
  • 52. Zarko Acimovic 22 23 public void keyPressed (int keyCode){ 24 25 //keyCode+=disabler; 26 27 if(keyCode==49){ 28 ol.ZoomIn(); 29 repaint(); 30 } 31 32 if(keyCode==50){ 33 ol.ZoomOut(); 34 repaint(); 35 } 36 37 if(keyCode==51){ 38 repaint(); 39 } 40 41 42 switch (getGameAction(keyCode)) { 43 case Canvas.UP: 44 ol.setMap('u'); 45 repaint(); 46 break; 47 case Canvas.DOWN: 48 ol.setMap('d'); 49 repaint(); 50 break; 51 case Canvas.LEFT: 52 ol.setMap('l'); 53 repaint(); 54 break; 55 case Canvas.RIGHT: 56 ol.setMap('r'); 57 repaint(); 58 break; 59 } 60 } 61 } lii