Software Defect Prevention Techniques         ~ Example Project ~               Zarko Acimovic             Copyright © 201...
DEDICATIONI dedicate this book to my parents, Ivana and Goran
CONTENTS1   Introduction2   Theoretical Foundations for Defect Prevention              13   Automatic Tools for Defect Pre...
Zarko Acimovic                                             1 INTRODUCTIONI present 5000 lines of Java source code mostly w...
Software Defects Prevention Techniques – Example Project17 - Architectural Design (59:28)18 - Software Testing - I (55:39)...
Zarko Acimovic    3. Overview of Phases in Software Development (57:22)http://nptel.iitm.ac.in/video.php?subjectId=1061010...
Software Defects Prevention Techniques – Example Project       •   Requirement problems       •   Structured presentation ...
Zarko Acimovic       •   Algebraic Manipulation using Axioms       •   Abstract Math to Concrete realizations       •   AD...
Software Defects Prevention Techniques – Example Project    10. Process Modeling - DFD, Function Decomposition (53:23)http...
Zarko Acimovic            •   Software Maintenance            •   Quality Factors for Software            •   Quality Fact...
Software Defects Prevention Techniques – Example Project    15. Design Patterns (56:13)http://nptel.iitm.ac.in/video.php?s...
Zarko Acimovic       •   Class Design       •   Part-Whole Design       •   Odells Classification Criteria       •   Compo...
Software Defects Prevention Techniques – Example Project       •   Facade       •   Broker       •   MVC       •   Microke...
Zarko Acimovic       •   Basic Path Testing       •   A Sequential Composition       •   A Branching Statement       •   A...
Software Defects Prevention Techniques – Example Project       •   Makefile       •   A Sample Makefile       •   Code org...
Zarko Acimovic       •   Feasibility ...       •   Requirements Analysis       •   Circulation System       •   Draw first...
Software Defects Prevention Techniques – Example Project       •   Types of Maintenance       •   Breakup of costs       •...
Zarko Acimovic       •   Test Case Description       •   Test- first development       •   Pair programming       •   XP S...
Software Defects Prevention Techniques – Example Project       •   Generalization Techniques       •   Generating good men...
Zarko Acimovic       •   Illustration: Objectives of a Hospital IS       •   Illustration: Project Charter (1/3)       •  ...
Software Defects Prevention Techniques – Example Project       •   COnstructive COst MOdel (COCOMO): Intd.       •   Marke...
Zarko Acimovic    35. Quality Management Systems - I (54:43)http://nptel.iitm.ac.in/video.php?subjectId=106101061    36. Q...
Software Defects Prevention Techniques – Example Project    38. Project Risk Management (56:04)http://nptel.iitm.ac.in/vid...
Zarko Acimovic                     2 AUTOMATIC TOOLS FOR DEFECT PREVENTIONPrototyping (modeling) defect prevention method ...
Software Defects Prevention Techniques – Example Project                                4 SAMPLE PROJECT SPECIFICATIONProj...
Zarko Acimovic Description                                                                                     Line       ...
Software Defects Prevention Techniques – Example Project17   * @return String[]18   */19       String[] getWithLowLine(Str...
Zarko Acimovic    68    69       /** Returns categories    70        * @return String[]    71        */    72        Strin...
Software Defects Prevention Techniques – Example ProjectAll classes and interfaces must belong to a named package         ...
Zarko AcimovicCompassCanvas.java violations - continued Avoid unused local variables such as mediumX.                   12...
Software Defects Prevention Techniques – Example Project    32          Image imgDest;    33          long destUp;    34  ...
Zarko Acimovic    77                          String sy =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP...
Software Defects Prevention Techniques – Example Project   114                          int SY = Integer.parseInt(s12);   ...
Zarko Acimovic   153                          sy =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),Ma...
Software Defects Prevention Techniques – Example Project   192                           if(gamaDegrees<=0) {   193       ...
Zarko Acimovic   225                           if(MathFP.toFP("175")<=gamaDegrees   &&gamaDegrees<MathFP.toFP("275")){   2...
Software Defects Prevention Techniques – Example Project   268                          sx =MathFP.toString(MathFP.add(Mat...
Zarko AcimovicCoordinates.java violations All classes and interfaces must belong to a named package                       ...
Software Defects Prevention Techniques – Example Project    18    private long latitude;    19    /**    20     * the WGS-...
Zarko Acimovic    64     */    65    public long getLongitude(){    66       return longitude;    67    }    68    69    7...
Software Defects Prevention Techniques – Example Project   105      // This should be fixed only if the final target devic...
Zarko Acimovic   146     * @return distance to another location in meters, using the line on theGreat Circle   147     */ ...
Software Defects Prevention Techniques – Example Project   186   187 /*   188      System.out.print("latFrom: "+MathFP.toS...
Zarko Acimovic   234      // return 0;   235      return distance;   236    }   237   238   239    /**   240     * Convert...
Software Defects Prevention Techniques – Example ProjectDelRoute.java violations All classes and interfaces must belong to...
Zarko AcimovicFriend.java violations All classes and interfaces must belong to a named package                            ...
Software Defects Prevention Techniques – Example Project23           return resource;24       }2526       public int getHa...
Zarko AcimovicHeapSorter.java violations All classes and interfaces must belong to a named package                5   PMD ...
Software Defects Prevention Techniques – Example Project    20           a[0]=A[0];    21    }    22    23    public void ...
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Software defect prevention example project
Upcoming SlideShare
Loading in …5
×

Software defect prevention example project

550 views

Published on

Example Java software project with 5000 lines of code examined with defect prevention tools such as PMD and FindBugs

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
550
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Software defect prevention example project

  1. 1. Software Defect Prevention Techniques ~ Example Project ~ Zarko Acimovic Copyright © 2013 Zarko Acimovic All rights reserved. ISBN-10: 1481113305 ISBN-13: 978-1481113304
  2. 2. DEDICATIONI dedicate this book to my parents, Ivana and Goran
  3. 3. CONTENTS1 Introduction2 Theoretical Foundations for Defect Prevention 13 Automatic Tools for Defect Prevention 244 Tools for Defect Prevention in Java Software Development 255 Sample Project Software Requirements 256 Source Code with Violations 267 Design Defects Detected by ArgoUML 1928 Examples of Design Defects in Sample Project 196 About the Author
  4. 4. Zarko Acimovic 1 INTRODUCTIONI present 5000 lines of Java source code mostly written by using trial/error code/test technique. The code was writtenfor prototype project in three months without using defect prevention techniques ( that is, tools such as PMD,FindBugs, StateOfFlow or ArgoUML) I wrote the code in 2004 and ever since had several business offers tocommercialize it which I resisted due to complexity of the code.8 years after completing project I run the defect prevention tools against the code and uncovered 1123 code violations(almost 1 violation per 5 lines of code) and 121 software design violations. All these violations are presented in bookwith references to the source code lines where they live. Its worth mentioning that these violations are not defects –being present at the code, they just make it easier for you to make mistake when maintaining code or implementingnew feature.I recommend readers to use these tools during development and correct all violations on the fly, or switch to someother risk-free programming language such as Haskell, Erlang or Lisp. 2 THEORETICAL FOUNDATIONS FOR DEFECT PREVENTIONBelow 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 preventiontechniques. The course can be found on following locationhttp://nptel.iitm.ac.in/video.php?subjectId=106101061Here is high level overview 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) iv
  5. 5. Software Defects Prevention Techniques – Example Project17 - 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)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. 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. 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. 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. 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 Russells Laws of Software Relativity • Properties of Failing software • Common Error in Managing the Process ix
  10. 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 • Whats 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. 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 Cunninghams 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 • A Contact Specification xi
  12. 12. Zarko Acimovic • Class Design • Part-Whole Design • Odells 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 components 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 • Filters • Blankboards xii
  13. 13. Software Defects Prevention Techniques – Example Project • 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 • An Example for Statement Coverage • Observations • Implicit statements xiii
  14. 14. Zarko Acimovic • 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 • Use of Software Measurement • Separate Compilation • Makefile • Separate Compilation xiv
  15. 15. Software Defects Prevention Techniques – Example Project • 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 • STATEMENT OF PROJECT SCOPE AND OBJECTIVES • THE FEASIBILITY STUDY: CIRCULATION • Financial analysis for alternatives 1 : • Alternatives 2 • Plan for alternatives 1 xv
  16. 16. Zarko Acimovic • 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 • Laws of Program Evolution • Applicability of Lehmans laws • Software maintenance • Maintenance is inevitable • Causes of maintenance • Distribution of maintenance effort xvi
  17. 17. Software Defects Prevention Techniques – Example Project • 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 • 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 xvii
  18. 18. Zarko Acimovic • 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 • Evaluating Frameworks • COTS product reuse • Integration Approaches • Examples of COTS muse • COTS system integration problems • Component development for reuse • Reusable components • Re-usability enhancement xviii
  19. 19. Software Defects Prevention Techniques – Example Project • 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 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 xix
  20. 20. Zarko Acimovic • 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 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 xx
  21. 21. Software Defects Prevention Techniques – Example Project • 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 • Boehms 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) • Who Identifies OFI? • Improvement in Practice and Documentation • Quality Control Process • QC is Performed... • Pareto Chart: Illustration • Control Chart: Schematic xxi
  22. 22. Zarko Acimovic 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 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 • xxii
  23. 23. Software Defects Prevention Techniques – Example Project 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 • 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 xxiii
  24. 24. Zarko Acimovic 2 AUTOMATIC TOOLS FOR DEFECT PREVENTIONPrototyping (modeling) defect prevention method has efficiency 52%. Before implementing this method defectpotential per 1 FP (function point) was 5, after, 2.4.Tool: ArgoUMLStatic analysis of source code defect prevention method has efficiency 44%. Defect potential per 1 FP was 5, afterimplementing this method is 2.8.Tool: CoverityMathematical test case design defect prevention efficiency was 34%. Defect potential per 1 FP is 5, after is 3.3.Tool: BullseyeBonus: Root cause analysis 1044-1993 - IEEE Standard Classification for Software Anomalies. Efficiency 41% -Before 5 – After 2.95Source: Chapter 3. Estimating and Measuring Software Quality. The Economics of Software Quality, ISBN:9780132564762 , Capers Jones, Olivier Bonsignourhttp://www.amazon.com/Economics-Software-Quality-Capers-Jones/dp/0132582201http://www.informit.com/store/product.aspx?isbn=0132582201 3 TOOLS FOR DEFECT PREVENTION IN JAVA SOFTWARE PROJECTSSource: 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/eclipsemetricsDependency Analysis JDepend4Eclipse http://andrei.gmxhome.de/jdepend4eclipse/Source Code Analysis PMD http://pmd.sourceforge.net/ xxiv
  25. 25. Software Defects Prevention Techniques – Example Project 4 SAMPLE PROJECT SPECIFICATIONProject duration 3 months, single developer , 5000 lines of code (including comments), 15 Java 2 Micro EditionclassesTools used: Sun J2ME Wireless Toolkit, Eclipse, IBM WebSphere Device Developer 5.5, CVS, Motorola and Nokiaphone 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 displayingmap with scale, following moving objects, zoom in-out and pan, selection of location , measuring distance, followingindividual or vehicle on map with route presentation, presentation of waypoints on map, presentation of list ofexisting waypoints (sorted by name, type, distance) for selecting destination or editing and deletion, creating, editingand 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 thatdestination. Some classes implemented: MapBackground, MapObject, Point, SelectorPoint, PVector, MapsMIDletProject demo web site: https://sites.google.com/site/j2memaps/ 5 PMD, FINDBUGS AND STATEOFFLOW VIOLATIONS IN SOURCE CODEHere are the violations detected in CommaHyphenString.java Description/ Line/ Type of tool xxv
  26. 26. Zarko Acimovic 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 MarkerHere is the CommaHyphenString.java source code 1 /** 2 * 3 * CommaHyphenString parses .properties file. It eliminates commas or lowlines 4 * from .properties file so items in it( such as categories) could beproperly 5 * showed on screen 6 */ 7 import java.util.*; 8 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 xxvi
  27. 27. Software Defects Prevention Techniques – Example Project17 * @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);3435 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 }4344 /** Eliminates low line45 * @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 }606162 /** Returns categories with low line63 * @return String[]64 */65 String[] getCategoriesHyphen(String s){66 return this.getWithLowLine(s);67 } xxvii
  28. 28. Zarko Acimovic 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 }CompassCanvas.java violations xxviii
  29. 29. Software Defects Prevention Techniques – Example ProjectAll classes and interfaces must belong to a named package 10 PMD MarkerLack of Cohesion in Methods (Henderson-Sellers) is 75% 10 Metrics MarkerLack of Cohesion in Methods (Total Correlation) is 1,668% 10 Metrics MarkerNumber of Fields is 23 10 Metrics MarkerThe class CompassCanvas has a Cyclomatic Complexity of 6 (Highest = 17). 10 PMD MarkerTo be compliant to J2EE, a webapp should not use any thread. 10 PMD MarkerToo many fields 10 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 11 PMD MarkerUse explicit scoping instead of the default package private level 11 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 12 PMD MarkerUse explicit scoping instead of the default package private level 12 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 13 PMD MarkerUse explicit scoping instead of the default package private level 13 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 14 PMD MarkerUse explicit scoping instead of the default package private level 14 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 15 PMD MarkerUse explicit scoping instead of the default package private level 15 PMD MarkerAvoid variables with short names like c 18 PMD MarkerUnused field: CompassCanvas.c 18 FindBugsAvoid variables with short names like t 20 PMD MarkerTo be compliant to J2EE, a webapp should not use any thread. 20 PMD MarkerUnread field: CompassCanvas.switchVar 22 FindBugsUnread field: CompassCanvas.switched 23 FindBugsIt is a good practice to call super() in a constructor 38 PMD MarkerLines of Code in Method is 24 38 Metrics MarkerNumber of Statements is 33 38 Metrics MarkerParameter mob is not assigned and could be declared final 38 PMD MarkerAvoid empty catch blocks 53 PMD MarkerAvoid empty catch blocks 57 PMD MarkerTo be compliant to J2EE, a webapp should not use any thread. 59 PMD MarkerAvoid really long methods. 63 PMD MarkerAvoid variables with short names like g 63 PMD MarkerCyclomatic Complexity is 10 63 Metrics MarkerLines of Code in Method is 220 63 Metrics MarkerNumber of Statements is 418 63 Metrics MarkerParameter g is not assigned and could be declared final 63 PMD MarkerThe method paint has a Cyclomatic Complexity of 17. 63 PMD MarkerThe method paint() has an NCSS count of 144 63 PMD MarkerThe method paint() has an NPath complexity of 4375 63 PMD MarkerAvoid unnecessary comparisons in boolean expressions 68 PMD Marker xxix
  30. 30. Zarko AcimovicCompassCanvas.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 MarkerCompassCanvas.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; 29 int dummy4 = 0; 30 Image img; 31 xxx
  31. 31. Software Defects Prevention Techniques – Example Project 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 76 String sx =MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(MathFP.sub(north,delta))))); xxxi
  32. 32. Zarko Acimovic 77 String sy =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(MathFP.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),MathFP.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),MathFP.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(MathFP.sub(south,delta))))); 98 sy =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(MathFP.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),MathFP.sin(MathFP.sub(south,delta))))); 108 ix = s11.indexOf(.); 109 s11 = s11.substring(0,ix); 110 int SX = Integer.parseInt(s11); 111 String s12 =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),MathFP.cos(MathFP.sub(south,delta))))); 112 iy = s12.indexOf(.); 113 s12 = s12.substring(0,iy); xxxii
  33. 33. Software Defects Prevention Techniques – Example Project 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(MathFP.sub(east,delta))))); 126 String s2 =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(10),MathFP.cos(MathFP.sub(east,delta))))); 127 128 String s3 =MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(10),MathFP.sin(MathFP.sub(west,delta))))); 129 String s4 =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(10),MathFP.cos(MathFP.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 152 sx =MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(MathFP.sub(east,delta))))); xxxiii
  34. 34. Zarko Acimovic 153 sy =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(MathFP.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(MathFP.sub(west,delta))))); 165 sy =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(75),MathFP.cos(MathFP.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 189 long dx = 0; 190 long dy = 0; 191 xxxiv
  35. 35. Software Defects Prevention Techniques – Example Project 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 } 223 224 xxxv
  36. 36. Zarko Acimovic 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. 37. Software Defects Prevention Techniques – Example Project 268 sx =MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(smallestRadius),MathFP.sin(MathFP.sub(destDown,gama))))); 269 sy =MathFP.toString(MathFP.sub(MathFP.toFP(85),MathFP.mul(MathFP.toFP(smallestRadius),MathFP.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. 38. Zarko AcimovicCoordinates.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 MarkerCoordinates.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 * Earths 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. 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-84ellipsoid. 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 objectwas created, in milliseconds since midnight January 1, 1970 GMT, or -1 34 * @param source the short string describing where data containedin this object came from, like "GPS", "Network", "Database", etc 35 * @param horizontalAccuracy the horizontal accuracy of coordinatesin meters, or Float.NaN 36 * @param verticalAccuracy vertical accuracy of coordinates inmeters, 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. 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 bycompass 4.understanding of ones position 89 * @param to another point 90 * @return long representing angle in degrees [0,360) betweencorresponding meridian in first point and line on the Great Circle between thosepoints 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) betweencorresponding meridian in first point and line on the Great Circle between thosepoints 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 mostlybelow 16 degrees xl
  41. 41. Software Defects Prevention Techniques – Example Project 105 // This should be fixed only if the final target device stays withoutnot 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 inventbetter 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 asmall 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))- 135MathFP.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. 42. Zarko Acimovic 146 * @return distance to another location in meters, using the line on theGreat Circle 147 */ 148 public long distance(Coordinates to){ 149 //BMa: Some numeric with MathFP are still possible - errors happensometimes 150 // This should be fixed only if the final target device stays withoutnot 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 theGreat Circle 163 */ 164 public static long calculateDistance(long latFrom, long lonFrom, longlatTo, 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 + 182Math.cos(lat1)*Math.cos(lat2)*Math.pow(Math.sin((lon2-lon1)/2), 2) 183 ) 184 ); 185 */ xlii
  43. 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 - boundaryfor 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 multiplicationand 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. 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. 45. Software Defects Prevention Techniques – Example ProjectDelRoute.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 todelet is "+index; 21 } 22 23 } xlv
  46. 46. Zarko AcimovicFriend.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, Thread4Friendt){ 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. 47. Software Defects Prevention Techniques – Example Project23 return resource;24 }2526 public int getHash(){27 return hashThread;28 }2930 public void setID(int hash){31 hashThread = hash;32 }3334 public String toString(){35 return "Friend is "+name+"n"+"Hash is "+hashThread;36 }3738 public void setFirst(){39 t.setFirst();40 }4142 public boolean getThread(){43 if (t==null){ return false; }44 else {return true; }45 }4647 public void setThread(Thread4Friend t){48 this.t = t;49 }50 } xlvii
  48. 48. Zarko AcimovicHeapSorter.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. 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

×