defect prevention techniques

199
Software Defect Prevention Techniques - Example Project - Zarko Acimovic Copyright © 2012 Zarko Acimovic All rights reserved. ISBN-10: 1481113305 ISBN-13: 978-1481113304

Upload: zarko-acimovic

Post on 25-May-2015

937 views

Category:

Technology


3 download

DESCRIPTION

Defect prevention techniques

TRANSCRIPT

Page 1: Defect prevention techniques

Software Defect Prevention Techniques - Example Project -

Zarko Acimovic

Copyright © 2012 Zarko Acimovic

All rights reserved.

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

Page 2: Defect prevention techniques

DEDICATION

I dedicate this book to my parents, Ivana and Goran

Page 3: Defect prevention techniques

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

Page 4: Defect prevention techniques

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

Page 5: Defect prevention techniques

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

Page 6: Defect prevention techniques

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

Page 7: Defect prevention techniques

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

Page 8: Defect prevention techniques

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

Page 9: Defect prevention techniques

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

Page 10: Defect prevention techniques

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

Page 11: Defect prevention techniques

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

Page 12: Defect prevention techniques

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

Page 13: Defect prevention techniques

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

Page 14: Defect prevention techniques

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

Page 15: Defect prevention techniques

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

Page 16: Defect prevention techniques

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

Page 17: Defect prevention techniques

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

Page 18: Defect prevention techniques

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

Page 19: Defect prevention techniques

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

Page 20: Defect prevention techniques

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

Page 21: Defect prevention techniques

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

Page 22: Defect prevention techniques

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

Page 23: Defect prevention techniques

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

Page 24: Defect prevention techniques

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

Page 25: Defect prevention techniques

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

Page 26: Defect prevention techniques

Zarko Acimovic

5 PMD, FINDBUGS AND STATEOFFLOW VIOLATIONS IN SOURCE CODE

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

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

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 MarkerAvoid 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 MarkerUse explicit scoping instead of the default package private level 65 PMD Marker

Page 27: Defect prevention techniques

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

Page 28: Defect prevention techniques

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

Page 29: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

CompassCanvas.java violations

xxix

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

Page 30: Defect prevention techniques

Zarko Acimovic

CompassCanvas.java violations - continued

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

Avoid unused local variables such as 'mediumX'. 122 PMD MarkerDead store to mediumX in CompassCanvas.paint(Graphics) 122 FindBugs

The local variable mediumX is never read 122 Java ProblemAvoid unused local variables such as 'mediumY'. 123 PMD Marker

Dead store to mediumY in CompassCanvas.paint(Graphics) 123 FindBugsThe local variable mediumY is never read 123 Java Problem

Avoid unnecessary comparisons in boolean expressions 285 PMD Marker

Page 31: Defect prevention techniques

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

Page 32: Defect prevention techniques

Zarko Acimovic

76 String sx = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(MathFP.sub(north,delta))))); 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);

xxxii

Page 33: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

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); 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

xxxiii

Page 34: Defect prevention techniques

Zarko Acimovic

152 sx = MathFP.toString(MathFP.add(MathFP.toFP(93),MathFP.mul(MathFP.toFP(75),MathFP.sin(MathFP.sub(east,delta))))); 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

xxxiv

Page 35: Defect prevention techniques

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

Page 36: Defect prevention techniques

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

Page 37: Defect prevention techniques

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

Page 38: Defect prevention techniques

Zarko Acimovic

Coordinates.java violations

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

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

Page 39: Defect prevention techniques

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

Page 40: Defect prevention techniques

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

Page 41: Defect prevention techniques

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

Page 42: Defect prevention techniques

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

Page 43: Defect prevention techniques

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

Page 44: Defect prevention techniques

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

Page 45: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

DelRoute.java violations

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

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

Page 46: Defect prevention techniques

Zarko Acimovic

Friend.java violations

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

All classes and interfaces must belong to a named package 5 PMD MarkerLack of Cohesion in Methods (Henderson-Sellers) is 83% 5 Metrics Marker

Lack of Cohesion in Methods (Pairwise Field Irrelation) is 96% 5 Metrics MarkerLack 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 MarkerUse 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 MarkerUse explicit scoping instead of the default package private level 9 PMD Marker

Avoid variables with short names like t 11 PMD MarkerParameter 'hashThread' is not assigned and could be declared final 11 PMD Marker

Parameter 'name' is not assigned and could be declared final 11 PMD MarkerParameter 'resource' is not assigned and could be declared final 11 PMD MarkerParameter 't' is not assigned and could be declared final 11 PMD Marker

Parameter 'hash' is not assigned and could be declared final 30 PMD MarkerA getX() method which returns a boolean should be named isX() 42 PMD Marker

Page 47: Defect prevention techniques

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

Page 48: Defect prevention techniques

Zarko Acimovic

HeapSorter.java violations

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

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

Page 49: Defect prevention techniques

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

Page 50: Defect prevention techniques

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

Page 51: Defect prevention techniques

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

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

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 MarkerAvoid variables with short names like ol 14 PMD Marker

It is a good practice to call super() in a constructor 14 PMD MarkerParameter 'ol' is not assigned and could be declared final 14 PMD Marker

Avoid variables with short names like g 19 PMD MarkerParameter 'g' is not assigned and could be declared final 19 PMD Marker

Cyclomatic Complexity is 8 23 Metrics MarkerLines of Code in Method is 38 23 Metrics Marker

Number of Statements is 25 23 Metrics MarkerParameter 'keyCode' is not assigned and could be declared final 23 PMD Marker

Page 52: Defect prevention techniques

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

Page 53: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

MapBackground.java violations

liii

All classes and interfaces must belong to a named package 10 PMD Marker

Lack of Cohesion in Methods (Chidamber & Kemerer) is 214 10 Metrics Marker

Lack of Cohesion in Methods (Henderson-Sellers) is 92% 10 Metrics Marker

Lack of Cohesion in Methods (Pairwise Field Irrelation) is 82% 10 Metrics Marker

Lack of Cohesion in Methods (Total Correlation) is 1,010% 10 Metrics Marker

Number of Fields is 47 10 Metrics Marker

The class 'MapBackground' has a Cyclomatic Complexity of 2 (Highest = 15). 10 PMD Marker

Too many fields 10 PMD Marker

Weighted Methods per Class is 64 10 Metrics Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 14 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 18 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 20 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 24 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 28 PMD Marker

Avoid unused private fields such as 'upDlat'. 65 PMD Marker

The field MapBackground.upDlat is never read locally 65 Java Problem

Unused field: MapBackground.upDlat 65 FindBugs

Avoid unused private fields such as 'upMlat'. 69 PMD Marker

The field MapBackground.upMlat is never read locally 69 Java Problem

Unused field: MapBackground.upMlat 69 FindBugs

Avoid unused private fields such as 'upSlat'. 73 PMD Marker

The field MapBackground.upSlat is never read locally 73 Java Problem

Unused field: MapBackground.upSlat 73 FindBugs

Avoid unused private fields such as 'dwDlat'. 77 PMD Marker

The field MapBackground.dwDlat is never read locally 77 Java Problem

Unused field: MapBackground.dwDlat 77 FindBugs

Avoid unused private fields such as 'dwMlat'. 81 PMD Marker

The field MapBackground.dwMlat is never read locally 81 Java Problem

Unused field: MapBackground.dwMlat 81 FindBugs

The field MapBackground.dwSlat is never read locally 85 Java Problem

Unused field: MapBackground.dwSlat 85 FindBugs

The field MapBackground.lfDlon is never read locally 90 Java Problem

Unused field: MapBackground.lfDlon 90 FindBugs

The field MapBackground.lfMlon is never read locally 94 Java Problem

Unused field: MapBackground.lfMlon 94 FindBugs

The field MapBackground.lfSlon is never read locally 98 Java Problem

Unused field: MapBackground.lfSlon 98 FindBugs

The field MapBackground.rtDlon is never read locally 102 Java Problem

Unused field: MapBackground.rtDlon 102 FindBugs

The field MapBackground.rtMlon is never read locally 106 Java Problem

Page 54: Defect prevention techniques

Zarko Acimovic

MapBacground.java violations – continued

liv

Use explicit scoping instead of the default package private level 137 PMD Marker

Use explicit scoping instead of the default package private level 142 PMD Marker

Use explicit scoping instead of the default package private level 147 PMD Marker

Unused field: MapBackground.sidePan 151 FindBugs

Avoid variables with short names like x 155 PMD Marker

Avoid variables with short names like y 159 PMD Marker

Unread field: MapBackground.param 208 FindBugs

Lines of Code in Method is 44 211 Metrics Marker

Number of Parameters is 7 211 Metrics Marker

Number of Statements is 47 211 Metrics Marker

Parameter 'name0' is not assigned and could be declared final 211 PMD Marker

Parameter 'name1' is not assigned and could be declared final 211 PMD Marker

Parameter 'name2' is not assigned and could be declared final 211 PMD Marker

Parameter 'latStr1' is not assigned and could be declared final 212 PMD Marker

Parameter 'lonStr1' is not assigned and could be declared final 213 PMD Marker

Avoid empty catch blocks 239 PMD Marker

The String literal "3600" appears 4 times in this file; the first occurrence is on 249 249 PMD Marker

Local variable 'pxy1' could be declared final 277 PMD Marker

Local variable 'pxy2' could be declared final 280 PMD Marker

Local variable 'tt1' could be declared final 333 PMD Marker

Local variable 'tt2' could be declared final 334 PMD Marker

Cyclomatic Complexity is 15 361 Metrics Marker

Lines of Code in Method is 50 361 Metrics Marker

Number of Statements is 37 361 Metrics Marker

The method 'setMap' has a Cyclomatic Complexity of 15. 364 PMD Marker

The method setMap() has an NPath complexity of 672 364 PMD Marker

Avoid unnecessary comparisons in boolean expressions 367 PMD Marker

Avoid using if statements without curly braces 369 PMD Marker

Avoid using if statements without curly braces 373 PMD Marker

Avoid unnecessary comparisons in boolean expressions 378 PMD Marker

These nested if statements could be combined 378 PMD Marker

Avoid using if statements without curly braces 382 PMD Marker

Avoid unnecessary comparisons in boolean expressions 388 PMD Marker

These nested if statements could be combined 388 PMD Marker

Avoid using if statements without curly braces 390 PMD Marker

Avoid using if statements without curly braces 393 PMD Marker

Avoid unnecessary comparisons in boolean expressions 399 PMD Marker

These nested if statements could be combined 399 PMD Marker

Lines of Code in Method is 27 425 Metrics Marker

Number of Statements is 22 425 Metrics Marker

Page 55: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

MapBackground.java violations continued

1 /** 2 * 3 * MapBackground transforms map according to user actions, zoom In, zoom out or pan 4 */ 5 import java.util.*; 6 import java.io.*; 7 import javax.microedition.lcdui.*; 8 9 10 public class MapBackground { 11 12 /** Current JPEG Background of map 13 */ 14 private Image img; 15 16 /** Images for Different Zoom Levels; 17 */ 18 private Image[] zoomImg = new Image[3]; 19 20 private int zoomLevel = 0; 21 22 /** Width of current background image 23 */ 24 private long sizeX; 25 26 /** Height of current background image 27 */ 28 private long sizeY; 29 30 31 /** Float-point value of upper limit 32 */

lv

Consider replacing this Vector with the newer java.util.List 478 PMD MarkerAvoid using implementation types like 'Vector'; use the interface instead 484 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 484 PMD Marker

Avoid variables with short names like v 484 PMD MarkerConsider replacing this Vector with the newer java.util.List 484 PMD Marker

Avoid variables with short names like g 490 PMD Marker

Local variable 'lx' could be declared final 491 PMD Marker

Cyclomatic Complexity is 11 542 Metrics MarkerLines of Code in Method is 67 542 Metrics Marker

Number of Statements is 69 542 Metrics Marker

Page 56: Defect prevention techniques

Zarko Acimovic

33 private long upLat; 34 35 /** Float-point value of lower limit 36 */ 37 private long downLat; 38 39 /** Side of upper limit 40 */ 41 //private char upNS; 42 43 /** Side of lower limit 44 */ 45 //private char downNS; 46 47 /** Float-point value of left limit 48 */ 49 private long leftLon; 50 51 /** Float-point value of right limit 52 */ 53 private long rightLon; 54 55 /** Side of left limit 56 */ 57 //private char leftWE; 58 59 /** Side of right limit 60 */ 61 ///private char rightWE; 62 63 /** Integer value of latitude degrees of upper limit 64 */ 65 private long upDlat; 66 67 /** Integer value of latitude minutes of upper limit 68 */ 69 private long upMlat; 70 71 /** Integer value of latitude seconds of upper limit 72 */ 73 private long upSlat; 74 75 /** Integer value of latitude degrees of lower limit 76 */ 77 private long dwDlat; 78 79 /** Integer value of latitude minutes of lower limit 80 */ 81 private long dwMlat; 82 83 /** Integer value of latitude seconds of upper limit

lvi

Page 57: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

84 */ 85 private long dwSlat; 86 87 88 /** Integer value of longitude degrees of left limit 89 */ 90 private long lfDlon; 91 92 /** Integer value of longitude minutes of left limit 93 */ 94 private long lfMlon; 95 96 /** Integer value of longitude seconds of left limit 97 */ 98 private long lfSlon; 99 100 /** Integer value of longitude degrees of right limit 101 */ 102 private long rtDlon; 103 104 /** Integer value of longitude minutes of right limit 105 */ 106 private long rtMlon; 107 108 /** Integer value of longitude seconds of right limit 109 */ 110 private long rtSlon; 111 112 113 /** Scale of map 114 */ 115 private long scale; 116 117 /** Number of lat-seconds per pixel 118 */ 119 private long pixLat; 120 121 /** Number of lon-seconds per pixel 122 */ 123 private long pixLon; 124 125 126 /** Total number of Latitude seconds for upper limit point 127 */ 128 long totLatSec ; 129 130 /** Total number of Longitude seconds for left limit point 131 */ 132 long totLonSec ; 133 134 /** new upper left edge due to pan or Zoom;

lvii

Page 58: Defect prevention techniques

Zarko Acimovic

135 * newEdge represents Point of upper left corner of visible screen 136 */ 137 Point newEdge; 138 139 /** new upper left edge due to pan or Zoom; 140 * newEdge represents Point of upper left corner of visible screen 141 */ 142 Point previousEdge; 143 144 145 /** World coordinates of Down end of Image 146 */ 147 Point downEnd; 148 149 /** Character that represents side of Pan 150 */ 151 char sidePan; 152 153 /** x-coordinate of begining of image 154 */ 155 long x = 0; 156 157 /** y-coordinate of begining of image 158 */ 159 long y = 0; 160 161 /** Indicates beginning of pan range verticaly 162 */ 163 boolean reachBeginV = true; 164 165 /** Indicates end of pan range verticaly 166 */ 167 boolean reachEndV = false; 168 169 /** Indicates beginning of pan range horizontaly 170 */ 171 boolean reachBeginH = true; 172 173 /** Indicates end of pan range horizontaly 174 */ 175 boolean reachEndH = false; 176 177 /** Step of panning 178 */ 179 long step = 30; 180 181 /** Counter of shifts vertically 182 */ 183 long movV=0; 184 185 /** Counter of shifts horizontally

lviii

Page 59: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

186 */ 187 long movH=0; 188 189 /** Name of smallest image 190 */ 191 String[] imgArray = new String[3]; 192 193 /** Canvas Height 194 */ 195 private long canvasHeight; 196 197 /** Canvas Width 198 */ 199 private long canvasWidth; 200 201 202 long previousPixLat; 203 long previousPixLon; 204 205 long minX; 206 long minY; 207 208 boolean param = false; 209 210 211 MapBackground( String name0, String name1, String name2, 212 String latStr1, 213 String lonStr1, 214 String latStr2, 215 String lonStr2 ) { 216 if(MathFP.toFP(latStr1)>MathFP.toFP(latStr2)){ 217 this.upLat = MathFP.toFP(latStr1); 218 this.downLat = MathFP.toFP(latStr2); 219 } else { 220 this.upLat = MathFP.toFP(latStr2); 221 this.downLat = MathFP.toFP(latStr1); 222 } 223 224 if(MathFP.toFP(lonStr1)>MathFP.toFP(lonStr2)){ 225 this.leftLon = MathFP.toFP(lonStr2); 226 this.rightLon = MathFP.toFP(lonStr1); 227 } else { 228 this.leftLon = MathFP.toFP(lonStr1); 229 this.rightLon = MathFP.toFP(lonStr2); 230 } 231 232 233 imgArray[0] = name0; 234 imgArray[1] = name1; 235 imgArray[2] = name2; 236

lix

Page 60: Defect prevention techniques

Zarko Acimovic

237 try { 238 zoomImg[0] = Image.createImage(imgArray[0]); 239 } catch (IOException e) {} 240 241 img = zoomImg[0]; 242 sizeX = img.getWidth(); 243 sizeY = img.getHeight(); 244 245 newEdge = new Point(MathFP.toString(upLat),MathFP.toString(leftLon),"newEdge","","blanco",false); 246 247 downEnd = new Point(MathFP.toString(downLat),MathFP.toString(rightLon),"downEnd","","blanco",false); 248 249 this.totLatSec = MathFP.mul(this.upLat,MathFP.toFP("3600")); 250 this.totLonSec = MathFP.mul(this.leftLon,MathFP.toFP("3600")); 251 252 253 this.setPixels(); 254 } 255 256 257 258 /** Returns number of longitude seconds per pixel 259 * @return int 260 * 261 */ 262 public long getPixLon(){ 263 return pixLon; 264 } 265 266 /** Returns number of latitude seconds per pixel 267 * @return int 268 */ 269 public long getPixLat(){ 270 return pixLat; 271 } 272 273 /** Sets pixels as Float-Point when main constructor is called 274 * and when Zoom In/Out is applied 275 */ 276 public void setPixels(){ 277 long pxy1 = MathFP.mul(MathFP.sub(rightLon,leftLon),MathFP.toFP("3600")); 278 pixLon = MathFP.div(pxy1,MathFP.toFP(sizeX)); 279 280 long pxy2 = MathFP.mul(MathFP.sub(upLat,downLat),MathFP.toFP("3600"));

lx

Page 61: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

281 pixLat = MathFP.div(pxy2,MathFP.toFP(sizeY)); 282 } 283 284 /** Returns image to draw 285 * 286 * @return Image 287 */ 288 public Image getImage(){ 289 return img; 290 } 291 292 293 /** Returns total number of seconds for LEFT LONGITUDE 294 * @return int 295 */ 296 public long getLonSec() { 297 return this.totLonSec; 298 } 299 300 /** Returns total number of seconds for UPPER LATITUDE 301 * @return int 302 */ 303 public long getLatSec() { 304 return this.totLatSec; 305 } 306 307 308 /** Returns Canvas height 309 * 310 * @return int 311 */ 312 public long getCanvasHeight(){ 313 return canvasHeight; 314 } 315 316 /** Returns Canvas width 317 * 318 * @return int 319 */ 320 public long getCanvasWidth(){ 321 return canvasWidth; 322 } 323 324 /** Sets newEdge; new Edge is created every time when user pans or zooms map ; 325 * newEdge represents Point of upper left corner of visible screen (x=0 and 326 * y=0 for newEdge) 327 * 328 * @return Point 329 */

lxi

Page 62: Defect prevention techniques

Zarko Acimovic

330 public void setNewEdge(){ 331 previousEdge = newEdge; 332 333 long tt1 = MathFP.mul(this.getPixLat(),MathFP.toFP(Math.abs(this.getY()))); 334 long tt2 = MathFP.mul(this.getPixLon(),MathFP.toFP(Math.abs(this.getX()))); 335 336 newEdge = new Point(MathFP.sub(this.getLatSec(),tt1), 337 MathFP.add(this.getLonSec(),tt2),"","",false); 338 } 339 340 /** Returns new edge 341 */ 342 public Point getNewEdge(){ 343 return newEdge; 344 } 345 346 /** Returns down End 347 */ 348 public Point getDownEnd(){ 349 return downEnd; 350 } 351 352 /** Returns new Edge as String 353 * 354 * @return String 355 */ 356 public String getNEdgeStr(){ 357 return newEdge.toString(); 358 } 359 360 361 /** Sets map due to Pan transformation 362 * 363 */ 364 public void setMap(char side){ 365 366 if (side=='u'){ 367 if(reachBeginV==false){ 368 y+=((this.img.getHeight() - canvasHeight)/step); 369 if(y>0) y=0; 370 movV--; 371 } 372 reachEndV=false; 373 if(movV==0) reachBeginV=true; 374 375 } 376 377 if (side=='d'){

lxii

Page 63: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

378 if(reachEndV==false){ 379 y-=((this.img.getHeight()-canvasHeight)/step); 380 movV++; 381 reachBeginV=false; 382 if(movV==step) reachEndV=true; 383 } 384 385 } 386 387 if (side=='l'){ 388 if(reachBeginH==false){ 389 x+=((this.img.getWidth()-canvasWidth)/step); 390 if(x>0) x=0; 391 movH--; 392 reachEndH=false; 393 if(movH==0) reachBeginH=true; 394 } 395 396 } 397 398 if (side=='r'){ 399 if(reachEndH==false) { 400 x-=((this.img.getWidth()-canvasWidth)/step); 401 movH++; 402 reachBeginH=false; 403 if(movH==step) reachEndH=true; 404 405 } 406 } 407 408 this.setNewEdge(); 409 410 } 411 412 413 /** returns x-coordinate of begining of Image 414 */ 415 public long getX(){ 416 return x; 417 } 418 419 /** returns y-coordinate of begining of Image 420 */ 421 public long getY(){ 422 return y; 423 } 424 425 /** Zoom In 426 */ 427 public boolean ZoomIn(){ 428 boolean zoom = false;

lxiii

Page 64: Defect prevention techniques

Zarko Acimovic

429 if(zoomLevel<2){ 430 zoom = true; 431 this.setPreviousEdge(); 432 433 zoomLevel++; 434 if (zoomImg[zoomLevel]==null){ 435 try{ 436 zoomImg[zoomLevel] = Image.createImage(imgArray[zoomLevel]); 437 } catch(Exception e){} 438 } 439 this.img = zoomImg[zoomLevel]; 440 this.sizeX = this.img.getWidth(); 441 this.sizeY = this.img.getHeight(); 442 this.setPixels(); 443 444 x=0-(((this.img.getWidth()-canvasWidth)/step)*movH); 445 y=0-(((this.img.getHeight()-canvasHeight)/step)*movV); 446 447 this.setNewEdge(); 448 449 } 450 return zoom; 451 } 452 453 /** Zoom Out 454 */ 455 public boolean ZoomOut(){ 456 boolean zoom = false; 457 if(zoomLevel>0){ 458 zoom = true; 459 this.setPreviousEdge(); 460 461 zoomLevel--; 462 this.img = zoomImg[zoomLevel]; 463 this.sizeX = this.img.getWidth(); 464 this.sizeY = this.img.getHeight(); 465 this.setPixels(); 466 467 x=0-(((this.img.getWidth()-canvasWidth)/step)*movH); 468 y=0-(((this.img.getHeight()-canvasHeight)/step)*movV); 469 470 this.setNewEdge(); 471 } 472 return zoom; 473 } 474 475 476 /** Increments Pan level 477 */ 478 public void incPan(Vector v){

lxiv

Page 65: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

479 if (step<10) step++; 480 } 481 482 /** Decrements Pan level 483 */ 484 public void decPan(Vector v){ 485 if (step>3) step--; 486 } 487 488 /** Draws Layout 489 */ 490 public void drawMapBackground(Graphics g){ 491 Long lx = new Long(x); 492 Long ly = new Long(y); 493 int xx = Integer.parseInt(lx.toString()); 494 int yy = Integer.parseInt(ly.toString()); 495 496 g.drawImage(img,xx,yy,0); 497 } 498 499 /** Set Canvas width and height 500 */ 501 public void setCanvasWH(int canvasWidth, int canvasHeight){ 502 this.canvasWidth = (long)canvasWidth; 503 this.canvasHeight = (long)canvasHeight; 504 } 505 506 public Point getPreviousEdge(){ 507 return previousEdge; 508 } 509 510 public void setPreviousEdge(){ 511 previousEdge = newEdge; 512 previousPixLat = pixLat; 513 previousPixLon = pixLon; 514 } 515 516 public long getPreviousPixLat(){ 517 return previousPixLat; 518 } 519 520 public long getPreviousPixLon(){ 521 return previousPixLon; 522 } 523 524 public long getZoomLevel(){ 525 return zoomLevel; 526 } 527 528 public long imageHeight(){ 529 return (long)img.getHeight();

lxv

Page 66: Defect prevention techniques

Zarko Acimovic

530 } 531 532 public long imageWidth(){ 533 return (long)img.getWidth(); 534 } 535 536 public long getStep(){ 537 return step; 538 } 539 540 541 542 /** Sets Background for selected Point 543 * Used in SelectorPoint.selectWP 544 */ 545 public void setBackground(Point ww){ 546 547 long imgWidth = (long) this.img.getWidth(); 548 long imgHeight= (long) this.img.getHeight(); 549 minX = -Math.abs(imgWidth-canvasWidth); 550 minY = -Math.abs(imgHeight-canvasHeight); 551 552 long difLat = MathFP.div(Math.abs(ww.getLatSec()-this.getLatSec()),pixLat); //x pixel of ww 553 long difLon = MathFP.div(Math.abs(ww.getLonSec()-this.getLonSec()),pixLon); //y pixel of ww 554 long p1 = MathFP.div(difLat,MathFP.div((this.img.getHeight()-canvasHeight),step)); 555 long p2 = MathFP.div(difLon,MathFP.div((this.img.getWidth()-canvasWidth),step)); 556 557 p1 = MathFP.toLong(p1); 558 p2 = MathFP.toLong(p2); 559 p1--; 560 p2--; 561 562 563 564 p1*=((this.img.getHeight()-canvasHeight)/step); 565 p2*=((this.img.getWidth()-canvasWidth)/step); 566 567 /** 568 if(param==true) { 569 p1 -=((this.img.getHeight()-canvasHeight)/step); 570 p2-=((this.img.getWidth()-canvasWidth)/step); 571 572 p1 -=((this.img.getHeight()-canvasHeight)/step); 573 p2-=((this.img.getWidth()-canvasWidth)/step); 574 p2-=((this.img.getWidth()-canvasWidth)/step); 575 }*/ 576

lxvi

Page 67: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

577 578 this.x = 0 - p2; // x value of screen begining 579 this.y = 0 - p1; // y value of screen begining 580 581 582 583 movV = p1/((this.img.getHeight()-canvasHeight)/step); 584 movH = p2/((this.img.getWidth()-canvasWidth)/step); 585 586 if(x<minX){ 587 x=minX; 588 movH=step; 589 } 590 if(y<minY){ 591 y=minY; 592 movV=step; 593 } 594 595 if(x>0) x=0; 596 if(y>0) y=0; 597 if(movV<0) movV=0; 598 if(movH<0) movH=0; 599 600 if (movV==step) {reachEndV=true;} else {reachEndV=false;} 601 if (movV==0) {reachBeginV=true;} else {reachBeginV=false;} 602 if (movH==step) {reachEndH=true;} else {reachEndH=false;} 603 if (movH==0) {reachBeginH=true;} else {reachBeginH=false;} 604 605 this.setNewEdge(); 606 607 608 } 609 610 /** 611 public void stela(long p1,long p2){ 612 p1 -=((this.img.getHeight()-canvasHeight)/step); 613 p2+=((this.img.getWidth()-canvasWidth)/step); 614 615 p1 -=((this.img.getHeight()-canvasHeight)/step); 616 p2+=((this.img.getWidth()-canvasWidth)/step); 617 p2+=((this.img.getWidth()-canvasWidth)/step); 618 p2+=((this.img.getWidth()-canvasWidth)/step); 619 }*/ 620 621 622 623 624 625 } 626

lxvii

Page 68: Defect prevention techniques

Zarko Acimovic

MapBackgroundFactory.java violations

1 /** 2 * 3 * Different map formats could be implemented and dealt with with MapBackgroundFactory 4 */ 5 public class MapBackgroundFactory { 6 7 MapBackground m; 8 9 /** 10 MapBackgroundFactory(String name0, String name1, String name2, 11 int dLat1, int mLat1, int sLat1, char sdNS1, 12 int dLon1, int mLon1, int sLon1, char sdWE1, 13 int dLat2, int mLat2, int sLat2, char sdNS2, 14 int dLon2, int mLon2, int sLon2, char sdWE2, int scale){ 15 16 //m = new MapBackground(name0,name1,name2, 17 dLat1,mLat1,sLat1,sdNS1,dLon1,mLon1,sLon1,sdWE1, 18 dLat2,mLat2,sLat2,sdNS2,dLon2,mLon2,sLon2,sdWE2, scale); 19 }*/ 20 21 MapBackgroundFactory(String name0, String name1, String name2, 22 String lat1, String lon1, String lat2, String lon2){ 23 m = new MapBackground(name0,name1,name2, 24 lat1,lon1,lat2,lon2); 25 }

lxviii

All classes and interfaces must belong to a named package 5 PMD Marker

Avoid variables with short names like m 7 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 MarkerLines of Code in Method is 17 9 Metrics MarkerNumber of Parameters is 7 9 Metrics Marker

Parameter 'name0' is not assigned and could be declared final 21 PMD MarkerParameter 'name1' is not assigned and could be declared final 21 PMD MarkerParameter 'name2' is not assigned and could be declared final 21 PMD Marker

Page 69: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

26 27 28 public MapBackground getMapBackground(){ 29 return m; 30 } 31 32 }

MapObjects.java violations

lxix

All classes and interfaces must belong to a named package 9 PMD Marker

Lack of Cohesion in Methods (Chidamber & Kemerer) is 101 9 Metrics Marker

Lack of Cohesion in Methods (Henderson-Sellers) is 83% 9 Metrics Marker

Lack of Cohesion in Methods (Pairwise Field Irrelation) is 84% 9 Metrics Marker

Lack of Cohesion in Methods (Total Correlation) is 359% 9 Metrics Marker

Number of Fields is 12 9 Metrics Marker

The class 'MapObjects' has a Cyclomatic Complexity of 3 (Highest = 17). 9 PMD Marker

This class has too many methods, consider refactoring it. 9 PMD Marker

Weighted Methods per Class is 72 9 Metrics Marker

Avoid variables with short names like mb 11 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

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

Avoid excessively long variable names like destinationPosition 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 using implementation types like 'Vector'; use the interface instead 16 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 16 PMD Marker

Consider replacing this Vector with the newer java.util.List 16 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 16 PMD Marker

Unused field: MapObjects.currentRoute 17 FindBugs

Avoid using implementation types like 'Vector'; use the interface instead 18 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 18 PMD Marker

Consider replacing this Vector with the newer java.util.List 18 PMD Marker

Page 70: Defect prevention techniques

Zarko Acimovic

MapObjects.java violations – continued

lxx

Avoid variables with short names like mb 26 PMD Marker

Parameter 'mb' is not assigned and could be declared final 26 PMD Marker

Use ArrayList instead of Vector 32 PMD Marker

Cyclomatic Complexity is 7 36 Metrics Marker

Lines of Code in Method is 41 36 Metrics Marker

Number of Statements is 56 36 Metrics Marker

Consider replacing this Vector with the newer java.util.List 40 PMD Marker

Local variable 'temp1' could be declared final 40 PMD Marker

Use ArrayList instead of Vector 40 PMD Marker

Consider replacing this Vector with the newer java.util.List 41 PMD Marker

Avoid variables with short names like wp 56 PMD Marker

Local variable 'wp' could be declared final 56 PMD Marker

Avoid variables with short names like v 64 PMD Marker

Local variable 'v' could be declared final 64 PMD Marker

Avoid unnecessary comparisons in boolean expressions 65 PMD Marker

Avoid variables with short names like wp 69 PMD Marker

Local variable 'wp' could be declared final 69 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 81 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 81 PMD Marker

Consider replacing this Vector with the newer java.util.List 81 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 86 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 86 PMD Marker

Parameter 'wp' is not assigned and could be declared final 92 PMD Marker

Parameter 'wp' is not assigned and could be declared final 117 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 139 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 139 PMD Marker

Cyclomatic Complexity is 9 149 Metrics Marker

Lines of Code in Method is 47 149 Metrics Marker

Number of Levels is 5 149 Metrics Marker

Number of Locals in Scope is 7 149 Metrics Marker

Number of Statements is 73 149 Metrics Marker

Parameter 'g' is not assigned and could be declared final 151 PMD Marker

Page 71: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

MapsObjects.java violations

lxxi

Avoid unnecessary comparisons in boolean expressions 181 PMD Marker

Avoid unnecessary comparisons in boolean expressions 184 PMD Marker

Cyclomatic Complexity is 7 197 Metrics Marker

Lines of Code in Method is 23 197 Metrics Marker

Number of Statements is 42 197 Metrics Marker

Avoid using if statements without curly braces 204 PMD Marker

Avoid unnecessary comparisons in boolean expressions 206 PMD Marker

Avoid using if statements without curly braces 217 PMD Marker

Avoid using if statements without curly braces 218 PMD Marker

A method should have only one exit point, and that should be the last statement in the method 259 PMD Marker

Comparison of String parameter using == or != in MapObjects.removeRoute(String) 281 FindBugs

Cyclomatic Complexity is 9 288 Metrics Marker

Lines of Code in Method is 20 288 Metrics Marker

Number of Statements is 36 288 Metrics Marker

The method 'getDirection' has a Cyclomatic Complexity of 17. 288 PMD Marker

The method getDirection() has an NPath complexity of 6561 288 PMD Marker

Avoid using if statements without curly braces 296 PMD Marker

Avoid using if statements without curly braces 297 PMD Marker

Cyclomatic Complexity is 9 309 Metrics Marker

Lines of Code in Method is 29 309 Metrics Marker

Number of Statements is 48 309 Metrics Marker

Page 72: Defect prevention techniques

Zarko Acimovic

MapObjects.java

1 /** 2 * 3 * MapObjects controls appearance of all map objects on current screen 4 */ 5 import java.util.*; 6 //import java.io.*; 7 import javax.microedition.lcdui.*; 8 9 public class MapObjects { 10 11 MapBackground mb; 12 Point currentPosition; 13 Point previousPosition; 14 Point destinationPosition; 15 PVector freeWaypoints; 16 Vector routes; 17 PVector currentRoute; 18 Vector drawablePoints; 19 Hashtable friends; 20 boolean drawLine = false; 21 boolean destSet = false; 22 boolean currentSet = false; 23 24 25 26 MapObjects(MapBackground mb){ 27 this.mb = mb; 28 currentPosition = mb.getNewEdge(); 29 destinationPosition = mb.getNewEdge(); 30 currentPosition.setName("dummy"); 31 destinationPosition.setName("dummy"); 32 routes = new Vector(); 33 friends = new Hashtable(); 34 } 35 36 /** Sets drawable Points for current Screen 37 * 38 */ 39 public void setDrawablePoints(){ 40 Vector temp1 = new Vector(); 41 Vector temp2; 42 43 //check if current and destination are visible 44 if(this.currentPosition.check(mb.getNewEdge(), mb.getDownEnd())) { 45 currentPosition.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat());

lxxii

Page 73: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

46 temp1.addElement(currentPosition); 47 } 48 if(this.destinationPosition.check(mb.getNewEdge(), mb.getDownEnd())) { 49 destinationPosition.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 50 temp1.addElement(destinationPosition); 51 } 52 53 //check which free waypoints are visible 54 temp2 = freeWaypoints.getPoints(mb.getNewEdge(),mb.getDownEnd()); 55 for (int j=0; j<temp2.size(); j++){ 56 Point wp = (Point)temp2.elementAt(j); 57 wp.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 58 temp1.addElement(wp); 59 } 60 61 62 //check which route points are visible 63 for (int i=0; i<routes.size(); i++){ 64 PVector v = (PVector)routes.elementAt(i); 65 if (v.getVisible()==true){ 66 temp2 = v.getPoints(mb.getNewEdge(),mb.getDownEnd()); 67 68 for (int j=0; j<temp2.size(); j++){ 69 Point wp = (Point)temp2.elementAt(j); 70 wp.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 71 temp1.addElement(wp); 72 } 73 } 74 } 75 drawablePoints = temp1; 76 } 77 78 /** Returns drawable Points for current Screen 79 * @return Vector 80 */ 81 public Vector getDrawablePointsOld(){ 82 83 return drawablePoints; 84 } 85 86 public Vector getDrawablePoints(){ 87 this.setDrawablePoints(); 88 return drawablePoints; 89 } 90 91 92 public void setCurrentPosition(Point wp){

lxxiii

Page 74: Defect prevention techniques

Zarko Acimovic

93 previousPosition = currentPosition; 94 currentPosition = wp; 95 currentPosition.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 96 currentSet = true; 97 } 98 99 /** Reset current position 100 */ 101 public void resetCurrentPosition(){ 102 currentPosition = mb.getNewEdge(); 103 drawLine = false; 104 currentSet = false; 105 } 106 107 /** Returns current position 108 * @return Point 109 */ 110 public Point getCurrentPosition(){ 111 return currentPosition; 112 } 113 114 115 /** Set destination position 116 */ 117 public void setDestinationPosition(Point wp){ 118 destinationPosition = wp; 119 destSet = true; 120 } 121 122 /** Reset destination position 123 */ 124 public void resetDestinationPosition(){ 125 destinationPosition = mb.getNewEdge(); 126 drawLine = false; 127 destSet = false; 128 } 129 130 /** Returns destination position 131 * @return Point 132 */ 133 public Point getDestinationPosition(){ 134 return destinationPosition; 135 } 136 137 /** Returns all routes 138 */ 139 public Vector getRoutes(){ 140 return routes; 141 } 142

lxxiv

Page 75: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

143 /** Returns free Vector of free Points 144 */ 145 public PVector getFreeWaypoints(){ 146 return freeWaypoints; 147 } 148 149 /** Draws MapObjects --- OBSOLETED!!! 150 */ 151 public void drawMOBold(Graphics g, boolean route){ 152 long zl = mb.getZoomLevel()+1; 153 Long zzl = new Long(zl); 154 int zoomL = Integer.parseInt(zzl.toString()); 155 this.setDrawablePoints(); 156 157 // Drawing of line beetwen destination and current position 158 if(drawLine==true){ 159 currentPosition.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 160 destinationPosition.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 161 g.drawLine(currentPosition.getXX(),currentPosition.getYY(),destinationPosition.getXX(),destinationPosition.getYY()); 162 } 163 164 // Drawing of free Points, current position and destination position 165 for(int i=0; i<drawablePoints.size(); i++){ 166 Point wp = (Point)drawablePoints.elementAt(i); 167 if(wp.getImage().equals("blanco")){ 168 g.fillRect(wp.getXX(),wp.getYY(),5*zoomL,5*zoomL); 169 g.drawString(wp.getName(),wp.getXX()+5,wp.getYY()+5,0); 170 } else { 171 Image img = null; 172 try{ 173 img = Image.createImage(wp.getImage()); 174 }catch(Exception e){} 175 g.drawImage(img,wp.getXX(),wp.getYY(),0); 176 } 177 178 } 179 180 // Drawing of route 181 if(route==true){ 182 for(int i=0; i<routes.size(); i++){ 183 PVector wpv = (PVector)routes.elementAt(i); 184 if(wpv.getVisible()==true){ 185 for(int j=0; j<wpv.size()-1; j++){

lxxv

Page 76: Defect prevention techniques

Zarko Acimovic

186 Point wp1 = (Point) wpv.elementAt(j); 187 Point wp2 = (Point) wpv.elementAt(j+1); 188 wp1.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 189 wp2.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 190 g.drawLine(wp1.getXX(),wp1.getYY(),wp2.getXX(),wp2.getYY()); 191 } 192 } 193 } 194 } 195 } 196 197 /** Draws MapObjects 198 */ 199 public void drawMOB(Graphics g, boolean route){ 200 g.setColor(0,0,0); 201 202 freeWaypoints.drawVector(g,false,mb.getNewEdge(),mb.getPixLon(),mb.getPixLat(),mb.getZoomLevel()); 203 204 if(friends.size()!=0) this.getFriends().drawVector(g,false,mb.getNewEdge(),mb.getPixLon(),mb.getPixLat(),0); 205 206 if(route==true){ 207 for (int i =0; i<routes.size(); i++){ 208 PVector wpv = (PVector)routes.elementAt(i); 209 wpv.drawVector(g,route,mb.getNewEdge(),mb.getPixLon(),mb.getPixLat(),mb.getZoomLevel()); 210 } 211 } 212 213 if(currentSet) { 214 currentPosition.drawPoint(g,mb.getNewEdge(),mb.getPixLat(),mb.getPixLon(),mb.getZoomLevel()); 215 216 } 217 if(destSet) destinationPosition.drawPoint(g,mb.getNewEdge(),mb.getPixLat(),mb.getPixLon(),mb.getZoomLevel()); 218 if(currentSet && destSet) g.drawLine(currentPosition.getXX(),currentPosition.getYY(),destinationPosition.getXX(),destinationPosition.getYY()); 219 }

lxxvi

Page 77: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

220 221 222 223 224 /** Adds free Point 225 */ 226 public void addFreeWaypoint(Point wp){ 227 this.freeWaypoints.addElement(wp); 228 } 229 230 /** Adds new route 231 */ 232 public void addRoute(PVector v){ 233 this.routes.addElement(v); 234 } 235 236 /** Adds new Point to route with routeID on position pos 237 */ 238 public void addWP2Route(Point wp, int routeID, int pos) { 239 PVector route; 240 for (int i=0; i<routes.size(); i++){ 241 route = (PVector)routes.elementAt(i); 242 if(route.getID()==routeID){ 243 route.insertElementAt(wp,pos); 244 i=1000; 245 } 246 } 247 } 248 249 /** Sets free waypoints vector 250 */ 251 public void setFreeWaypointsV(PVector wpv){ 252 this.freeWaypoints = wpv; 253 } 254 255 /** Measure distance 256 */ 257 public long measureDistance(Point wp){ 258 if (currentPosition.equals(mb.getNewEdge())) { 259 return -1; 260 } else { 261 return currentPosition.measureDistance(wp); 262 } 263 } 264 265 public boolean currentSet(){ 266 return currentSet; 267 } 268 269 public boolean destSet(){ 270 return destSet;

lxxvii

Page 78: Defect prevention techniques

Zarko Acimovic

271 } 272 273 274 public void removeRoute(PVector wr){ 275 routes.removeElement(wr); 276 } 277 278 public void removeRoute(String s){ 279 for(int i=0; i<routes.size(); i++){ 280 PVector rt = (PVector)routes.elementAt(i); 281 if (rt.getName()==s) { 282 routes.removeElementAt(i); 283 i=1000; 284 } 285 } 286 } 287 288 public long getDirection(){ 289 290 long direction = 0; 291 long latP = previousPosition.getLat(); 292 long lonP = previousPosition.getLon(); 293 long latC = currentPosition.getLat(); 294 long lonC = currentPosition.getLon(); 295 296 if(latC>latP && lonP==lonC) direction = MathFP.toFP("0"); 297 if(latC>latP && lonC>lonP) direction = MathFP.toFP("45"); 298 if(latP==latC && lonC>lonP) direction = MathFP.toFP("90"); 299 if(latC<latP && lonC>lonP) direction = MathFP.toFP("135"); 300 if(latC<latP && lonP==lonC) direction = MathFP.toFP("180"); 301 if(latC<latP && lonC<lonP) direction = MathFP.toFP("225"); 302 if(latP==latC && lonC<lonP) direction = MathFP.toFP("270"); 303 if(latC>latP && lonC<lonP) direction = MathFP.toFP("315"); 304 305 direction = Coordinates.degreesToRadians(direction); 306 return direction; 307 } 308 309 /** This is not working well 310 */ 311 public long getBearing(){ 312 313 long bearing = 0; 314 long latP = previousPosition.getLat(); 315 long lonP = previousPosition.getLon(); 316 long latD = destinationPosition.getLat(); 317 long lonD = destinationPosition.getLon(); 318 319 320 //if(latD>latP && lonD==lonP) bearing = MathFP.toFP("0");

lxxviii

Page 79: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

321 if( latD>latP && MathFP.abs(MathFP.sub(lonD,lonP))<MathFP.toFP("5") ) bearing = MathFP.toFP("0"); 322 if(latD>latP && lonD>lonP) bearing = MathFP.toFP("45"); 323 //if(latD==latP && lonD>lonP) bearing = MathFP.toFP("90"); 324 if(MathFP.abs(MathFP.sub(latD,latP))<MathFP.toFP("5") && lonD>lonP) bearing = MathFP.toFP("90"); 325 if(latD<latP && lonD>lonP) bearing = MathFP.toFP("135"); 326 //if(latD<latP && lonP==lonD) bearing = MathFP.toFP("180"); 327 if(latD<latP && MathFP.abs(MathFP.sub(lonD,lonP))<MathFP.toFP("5") ) bearing = MathFP.toFP("180"); 328 if(latD<latP && lonD<lonP) bearing = MathFP.toFP("225"); 329 //if(latP==latD && lonD<lonP) bearing = MathFP.toFP("270"); 330 if(MathFP.abs(MathFP.sub(latD,latP))<MathFP.toFP("5") && lonD<lonP) bearing = MathFP.toFP("270"); 331 if(latD>latP && lonD<lonP) bearing = MathFP.toFP("315"); 332 333 334 bearing = Coordinates.degreesToRadians(bearing); 335 return bearing; 336 337 } 338 339 340 public void addNewFriend(int friendID){ 341 Point dummy = new Point(currentPosition,false); 342 Integer frID = new Integer(friendID); 343 friends.put(frID,dummy); 344 } 345 346 public void updateFriend(Integer friendID,Point p){ 347 friends.put(friendID,p); 348 } 349 350 public void deleteFriend(int friendID){ 351 Integer frID = new Integer(friendID); 352 friends.remove(frID); 353 System.out.println(friends); 354 } 355 356 public void deleteAllFriends(){ 357 //System.out.println("YIPI YAAA YEEEEE"); 358 friends.clear(); 359 //System.out.println(friends); 360 } 361 362 363 /** Conversion of hashtable into vector 364 */ 365 public PVector getFriends(){ 366 Vector v = new Vector(); 367 Enumeration e = friends.elements();

lxxix

Page 80: Defect prevention techniques

Zarko Acimovic

368 while(e.hasMoreElements()){ 369 v.addElement((Point)e.nextElement()); 370 } 371 372 PVector PFriends = new PVector(v,false); 373 return PFriends; 374 } 375 376 377 378 }

lxxx

Page 81: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

MapsMIDlet.java

lxxxi

All classes and interfaces must belong to a named package 17 PMD Marker

Avoid really long classes. 17 PMD Marker

Efferent Couplings is 36 17 Metrics Marker

Lack of Cohesion in Methods (Henderson-Sellers) is 90% 17 Metrics Marker

Lack of Cohesion in Methods (Total Correlation) is 7,735% 17 Metrics Marker

Number of Fields is 121 17 Metrics Marker

The class 'MapsMIDlet' has a Cyclomatic Complexity of 22 (Highest = 202). 17 PMD Marker

To be compliant to J2EE, a webapp should not use any thread. 17 PMD Marker

Too many fields 17 PMD Marker

Weighted Methods per Class is 150 17 Metrics Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 20 PMD Marker

Use explicit scoping instead of the default package private level 20 PMD Marker

Avoid variables with short names like mb 24 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 24 PMD Marker

Use explicit scoping instead of the default package private level 24 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 25 PMD Marker

Use explicit scoping instead of the default package private level 25 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 26 PMD Marker

Use explicit scoping instead of the default package private level 26 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 27 PMD Marker

Use explicit scoping instead of the default package private level 27 PMD Marker

Avoid variables with short names like ic 30 PMD Marker

Avoid variables with short names like cc 31 PMD Marker

The field name indicates a constant but its modifiers do not 75 PMD Marker

The field name indicates a constant but its modifiers do not 76 PMD Marker

The field name indicates a constant but its modifiers do not 77 PMD Marker

Avoid variables with short names like d 79 PMD Marker

Avoid variables with short names like t1 100 PMD Marker

To be compliant to J2EE, a webapp should not use any thread. 100 PMD Marker

To be compliant to J2EE, a webapp should not use any thread. 101 PMD Marker

Unused field: MapsMIDlet.t2 101 FindBugs

Unread field: MapsMIDlet.first 106 FindBugs

Unread field: MapsMIDlet.gpsHash 112 FindBugs

Unread field: MapsMIDlet.gpsThr 114 FindBugs

Unread field: MapsMIDlet.frndThr 115 FindBugs

Page 82: Defect prevention techniques

Zarko Acimovic

MapsMIDlet.java

lxxxii

Avoid using implementation types like 'Vector'; use the interface instead 129 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 129 PMD Marker

Consider replacing this Vector with the newer java.util.List 129 PMD Marker

Avoid excessively long variable names like synchronizationDone 134 PMD Marker

Unread field: MapsMIDlet.synchronizationDone 134 FindBugs

Unused field: MapsMIDlet.setLine 142 FindBugs

Unused field: MapsMIDlet.resetLine 143 FindBugs

The field name indicates a constant but its modifiers do not 158 PMD Marker

The field name indicates a constant but its modifiers do not 159 PMD Marker

Unused field: MapsMIDlet.routeList 186 FindBugs

Unused field: MapsMIDlet.allRoutes 188 FindBugs

Unused field: MapsMIDlet.hideRoutes 189 FindBugs

Unused field: MapsMIDlet.delRouteList 191 FindBugs

Unused field: MapsMIDlet.delAllRoutes 192 FindBugs

Unused field: MapsMIDlet.categories 197 FindBugs

Lines of Code in Method is 165 201 Metrics Marker

Number of Statements is 121 201 Metrics Marker

Avoid really long methods. 204 PMD Marker

The method startApp() has an NCSS count of 113 204 PMD Marker

The String literal "Categories" appears 8 times in this file; the first occurrence is on 332 332 PMD Marker

Use ArrayList instead of Vector 362 PMD Marker

Avoid really long methods. 368 PMD Marker

Cyclomatic Complexity is 121 368 Metrics Marker

Lines of Code in Method is 819 368 Metrics Marker

Number of Levels is 6 368 Metrics Marker

Number of Locals in Scope is 30 368 Metrics Marker

Number of Statements is 716 368 Metrics Marker

Parameter 'c' is not assigned and could be declared final 368 PMD Marker

Parameter 's' is not assigned and could be declared final 368 PMD Marker

The method 'commandAction' has a Cyclomatic Complexity of 202. 368 PMD Marker

The method commandAction() has an NCSS count of 539 368 PMD Marker

Avoid using if statements without curly braces 370 PMD Marker

Use equals() to compare object references. 370 PMD Marker

Use equals() to compare object references. 371 PMD Marker

Use equals() to compare object references. 371 PMD Marker

Use equals() to compare object references. 374 PMD Marker

Use equals() to compare object references. 374 PMD Marker

Avoid empty catch blocks 399 PMD Marker

MapsMIDlet.commandAction(Command, Displayable) might ignore java.lang.Exception 399 FindBugs

Avoid unnecessary comparisons in boolean expressions 413 PMD Marker

Page 83: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

MapsMIDLet.java

lxxxiii

Avoid unnecessary comparisons in boolean expressions 422 PMD Marker

Avoid using if statements without curly braces 422 PMD Marker

Local variable 'wp' could be declared final 428 PMD Marker

Local variable 'wp' could be declared final 434 PMD Marker

Local variable 'name' could be declared final 450 PMD Marker

Local variable 'sel' could be declared final 451 PMD Marker

Local variable 'category' could be declared final 456 PMD Marker

The local variable category is never read 456 Java Problem

Do not add empty strings 468 PMD Marker

Do not add empty strings 468 PMD Marker

Avoid empty catch blocks 479 PMD Marker

MapsMIDlet.commandAction(Command, Displayable) might ignore java.lang.Exception 479 FindBugs

The local variable category is never read 551 Java Problem

Do not add empty strings 563 PMD Marker

Do not add empty strings 563 PMD Marker

Avoid empty catch blocks 574 PMD Marker

MapsMIDlet.commandAction(Command, Displayable) might ignore java.lang.Exception 574 FindBugs

Deeply nested if..then statements are hard to read 599 PMD Marker

Avoid using if statements without curly braces 643 PMD Marker

Avoid using if statements without curly braces 644 PMD Marker

Avoid unnecessary comparisons in boolean expressions 670 PMD Marker

Avoid unnecessary comparisons in boolean expressions 695 PMD Marker

Avoid instantiating new objects inside loops 700 PMD Marker

Avoid instantiating new objects inside loops 735 PMD Marker

Consider replacing this Vector with the newer java.util.List 766 PMD Marker

Avoid instantiating new objects inside loops 775 PMD Marker

Avoid instantiating new objects inside loops 786 PMD Marker

Avoid instantiating new objects inside loops 828 PMD Marker

Consider replacing this Vector with the newer java.util.List 881 PMD Marker

Consider replacing this Vector with the newer java.util.List 881 PMD Marker

1023 FindBugs

To be compliant to J2EE, a webapp should not use any thread. 1028 PMD Marker

Substitute calls to size() == 0 (or size() != 0) with calls to isEmpty() 1049 PMD Marker

Substitute calls to size() == 0 (or size() != 0) with calls to isEmpty() 1105 PMD Marker

Cyclomatic Complexity is 11 1190 Metrics Marker

Lines of Code in Method is 87 1190 Metrics Marker

Number of Levels is 7 1190 Metrics Marker

Number of Locals in Scope is 16 1190 Metrics Marker

Number of Statements is 73 1190 Metrics Marker

The method 'run' has a Cyclomatic Complexity of 17. 1190 PMD Marker

Write to static field MapsMIDlet.resource from instance method MapsMIDlet.commandAction(Command, Displayable)

Page 84: Defect prevention techniques

Zarko Acimovic

MapsMIDlet.java

1 /** 2 * 3 * MapsMIDlet creates control menus due to user's actions and handles GPS issues 4 * 5 */ 6 import javax.microedition.lcdui.*; 7 8 import javax.microedition.midlet.*; 9 10 import java.util.*; 11 import java.io.*; 12 13 14 15 16 17 public class MapsMIDlet extends MIDlet implements CommandListener,Runnable { 18 19

lxxxiv

Parameter 'flag' is not assigned and could be declared final 1287 PMD Marker

Lines of Code in Method is 16 1291 Metrics MarkerParameter 's' is not assigned and could be declared final 1296 PMD MarkerAvoid unused local variables such as 'k'. 1297 PMD Marker

Dead store to k in MapsMIDlet.compact(String) 1297 FindBugsThe local variable k is never read 1297 Java Problem

MapsMIDlet.compact(String) concatenates strings using + in a loop 1302 FindBugsPrefer StringBuffer over += for concatenating strings 1302 PMD MarkerAvoid unused local variables such as 'kk'. 1304 PMD Marker

Dead store to kk in MapsMIDlet.compact(String) 1304 FindBugsThe local variable kk is never read 1304 Java Problem

Parameter 's' is not assigned and could be declared final 1308 PMD MarkerAvoid unused local variables such as 'k'. 1309 PMD MarkerDead store to k in MapsMIDlet.compactFine(String) 1309 FindBugs

The local variable k is never read 1309 Java ProblemMapsMIDlet.compactFine(String) concatenates strings using + in a loop 1314 FindBugs

Prefer StringBuffer over += for concatenating strings 1314 PMD MarkerAvoid unused local variables such as 'kk'. 1316 PMD MarkerDead store to kk in MapsMIDlet.compactFine(String) 1316 FindBugs

The local variable kk is never read 1316 Java ProblemCyclomatic Complexity is 6 1320 Metrics Marker

Lines of Code in Method is 31 1320 Metrics MarkerNumber of Statements is 26 1320 Metrics MarkerAvoid empty catch blocks 1335 PMD Marker

Page 85: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

20 MapBackgroundFactory mbf = new MapBackgroundFactory("/Mali2.png", "/Srednji.png","/Veliki.png", 21 "44.83049905", "20.44570857", "44.79241639", "20.48713523"); 22 23 24 MapBackground mb; 25 MapObjects mob; 26 SelectorPoint selP; 27 Outlook oul; 28 29 PVector vwpF = new PVector("free",false); 30 ImageCanvas3 ic; 31 CompassCanvas cc; 32 33 //Point wp3 = new Point("44.81916183","20.45417165","Klub'Akademija'","j","/Cultural_or_Tourist/Event.png",true); 34 Point wp2 = new Point("44.82990854","20.45661377","25. maj","j","/Sport/Swimming.png",true); 35 Point wp1 = new Point("44.81573706","20.45998215","Sp. Knezu Mihailu","j","/Cultural_or_Tourist/Monument.png",true); 36 37 Point wp4 = new Point("44.8178034","20.45177167","Saborna crkva","j","/Cultural_or_Tourist/Church.png",true); 38 Point wp5 = new Point("44.82577520","20.45459270","Zooloski vrt","j","/Cultural_or_Tourist/Zoo.png",true); 39 40 Point wp6 = new Point("44.81293225","20.46132951","Grinet kafe","j","/Service_or_Utility/Cafe.png",true); 41 Point wp7 = new Point("44.81426084","20.45943480","Trzni centar 'Sremska'","j","/Service_or_Utility/Shop.png",true); 42 Point wp8 = new Point("44.81248939","20.46006637","Bioskop 20.oktobar","j","/Service_or_Utility/Cinema.png",true); 43 Point wp9 = new Point("44.81293225","20.46743470","Policija","j","/Service_or_Utility/Police.png",true); 44 Point wp10 = new Point("44.81854182","20.45711898","Filoloski fakultet","j","/Service_or_Utility/School.png",true); 45 Point wp11 = new Point("44.82518476","20.45737165","Bioskop REX","j","/Service_or_Utility/Cinema.png",true); 46 Point wp12 = new Point("44.80496078","20.47652941","Elektrotehnicki fakultet","j","/Service_or_Utility/School.png",true); 47 Point wp13 = new Point("44.80466556","20.47337150","RCUB","j","/Service_or_Utility/School.png",true); 48 Point wp14 = new Point("44.80865126","20.46368736","Apoteka","j","/Service_or_Utility/Pharmacy.png",true); 49 Point wp15 = new Point("44.80067980","20.45737165","Urgentni centar","j","/Service_or_Utility/Redcross.png",true);

lxxxv

Page 86: Defect prevention techniques

Zarko Acimovic

50 51 52 53 54 /** Point wp3 = new Point(45,2 , 1,'N',22,20, 5,'E',"c1","j"); 55 Point wp4 = new Point(45,13, 2,'N',21,58, 5,'E',"d1","j"); 56 Point wp5 = new Point(46,45, 1,'N',21,20, 5,'E',"e1","j"); 57 Point wp6 = new Point(46,48,23,'N',21,23, 9,'E',"f1","j"); 58 Point wp7 = new Point(46,30,50,'N',22,25,50,'E',"g1","j"); 59 Point wp8 = new Point(46,48,59,'N',20,27,17,'E',"a","j"); 60 Point wp9 = new Point(46,45, 0,'N',20,26,15,'E',"b","j"); 61 Point wp10 = new Point(46,42, 0,'N',20,29,15,'E',"c","j"); 62 Point wp11 = new Point(46,39, 0,'N',20,29,15,'E',"d","j"); 63 Point wp12 = new Point(46,10,23,'N',20,30, 9,'E',"e","j"); 64 Point wp13 = new Point(45,50,23,'N',20,33, 9,'E',"f","j"); 65 Point wp14 = new Point(46,30,23,'N',20,52, 9,'E',"g","j"); 66 Point wp15 = new Point(46,25,23,'N',20,54, 0,'E',"h","j"); 67 Point wp16 = new Point(46,20,23,'N',20,46, 0,'E',"i","j"); 68 Point wp17 = new Point(46,10,23,'N',20,48, 0,'E',"j","j"); 69 Point wp18 = new Point(45,50,23,'N',20,35, 0,'E',"k","j"); */ 70 71 Point selectedWP; 72 73 74 ///////////////////////COMMANDS,MENUS,BUTTONS\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 75 Command DUMMY; 76 Command DELIM; 77 Command MAP_CMD; 78 79 Display d = Display.getDisplay(this); 80 81 List modes; 82 Command selectCmd; 83 Command mapviewCmd; 84 Command compassCmd; 85 86 87 88 Command opt; 89 Command mod; 90 91 List MVList; 92 Command Points; 93 Command routes; 94 Command gps; 95 Command friends; 96 Command ZoomIn; 97 Command ZoomOut; 98 Command exitCmd; 99 SimpleTextForm gpsTf;

lxxxvi

Page 87: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

100 Thread t1; 101 Thread t2; 102 103 static String resource=""; 104 boolean gpsON = false; 105 static String show = ""; 106 boolean first = false; 107 List friendList; 108 Command addNewFriend ; 109 Command onGPSc; 110 Command offGPSc; 111 List gpsList; 112 int gpsHash = 0; 113 114 int gpsThr = 0; 115 int frndThr = 0; 116 int currentlyShowed = 0; 117 Hashtable thrHash = new Hashtable(); 118 Vector listOfFriends = new Vector(); 119 SimpleTextForm friendForm; 120 Command stopFollow; 121 Command deleteFriends; 122 boolean followFriends = false; 123 124 List oneFriend; 125 Command stopFollowOne; 126 Command deleteFriend; 127 128 Thread4Friend tff; 129 Vector whiteList; 130 String friend; 131 132 boolean syncFollow = false; 133 long globalTimeStamp = 0; 134 boolean synchronizationDone = false; 135 136 List WPselected; 137 Command setAsCurrent; 138 Command setDest1; 139 Command edit; 140 Command delete; 141 Command measDist; 142 Command setLine; 143 Command resetLine; 144 145 146 List WPnotSel; 147 Command setCurrent; 148 Command setDest2; 149 Command addWP; 150

lxxxvii

Page 88: Defect prevention techniques

Zarko Acimovic

151 CommaHyphenString chs = new CommaHyphenString(); 152 TextForm tf1; // form for adding new Point on selected spot 153 TextForm tf2; // form for editing of selected Point 154 TextForm tf33; // form for adding waypoint with user entered data for (lat,lon) 155 TextForm previous; 156 TextFormImage tf11; //form for adding new Point with images for selected categories 157 TextFormImage tf22; 158 Command SAVE_CMD; 159 Command CONT_CMD; 160 Command BACK_CMD; 161 Alert a = new Alert("Warning","Please Select Point!",null,AlertType.INFO); 162 163 List WPList; //List of Points 164 Command addNewWP; 165 Command sortWP; 166 Command sortNameWP; 167 boolean showID = false; 168 Command showIDcom; 169 List previousList; 170 171 172 TextForm tfAdd; //form for adding Point with complete info about coordinates 173 174 List sorted; 175 176 177 List routeMain; 178 Command createNewRoute; 179 Command showRoutes; 180 Command delRoute; 181 182 List routeNew; 183 Command addPoint; 184 Command routeFin; 185 186 List routeList; 187 List routeOptions; 188 Command allRoutes; 189 Command hideRoutes; 190 191 List delRouteList; 192 Command delAllRoutes; 193 String nameR = ""; 194 195 PVector newRouteVector; 196 SimpleTextForm tf3; ///form for defining name of route 197 String[] categories;

lxxxviii

Page 89: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

198 boolean routeSetting = false; 199 200 String[] pathToImage; 201 /** 202 * @see MIDlet#startApp() 203 */ 204 protected void startApp() throws MIDletStateChangeException { 205 206 mb = mbf.getMapBackground(); 207 mob = new MapObjects(mb); 208 209 vwpF.addElement(wp1); 210 vwpF.addElement(wp2); 211 //vwpF.addElement(wp3); 212 vwpF.addElement(wp4); 213 vwpF.addElement(wp5); 214 vwpF.addElement(wp6); 215 vwpF.addElement(wp7); 216 vwpF.addElement(wp8); 217 vwpF.addElement(wp9); 218 vwpF.addElement(wp10); 219 vwpF.addElement(wp11); 220 vwpF.addElement(wp12); 221 vwpF.addElement(wp13); 222 vwpF.addElement(wp14); 223 vwpF.addElement(wp15); 224 225 226 227 mob.setFreeWaypointsV(vwpF); 228 229 selP = new SelectorPoint(mb,mob); 230 231 oul = new Outlook(mb,mob,selP); 232 233 ic = new ImageCanvas3(oul); 234 235 236 //////////////////////////COMMANDS,MENUS,BUTTONS\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 237 238 DUMMY = new Command(" ",Command.SCREEN,1); 239 DELIM = new Command("------------------",Command.SCREEN,1); 240 MAP_CMD = new Command("View on Map",Command.BACK,1); 241 BACK_CMD = new Command("Back to Previous Screen",Command.BACK,1); 242 243 mod = new Command("Mode",Command.SCREEN,1); 244 modes = new List("",List.IMPLICIT); 245 selectCmd = new Command("Selection",Command.SCREEN,1); 246 mapviewCmd = new Command("Mapview",Command.SCREEN,1);

lxxxix

Page 90: Defect prevention techniques

Zarko Acimovic

247 compassCmd = new Command("Compass",Command.SCREEN,1); 248 exitCmd = new Command("Exit",Command.SCREEN,1); 249 modes.append("PLEASE SELECT NEW MODE FROM MENU...",null); 250 modes.addCommand(DUMMY); 251 modes.addCommand(mapviewCmd); 252 modes.addCommand(selectCmd); 253 modes.addCommand(compassCmd); 254 modes.addCommand(exitCmd); 255 modes.setCommandListener(this); 256 257 opt = new Command("Option",Command.SCREEN,1); 258 259 260 261 // Map View options 262 MVList = new List("",List.IMPLICIT); 263 Points = new Command("Waypoints",Command.SCREEN,1); 264 routes = new Command("Routes",Command.SCREEN,1); 265 gps = new Command("GPS",Command.SCREEN,1); 266 267 friends = new Command("Friends",Command.SCREEN,1); 268 ZoomIn = new Command("Zoom In",Command.SCREEN,1); 269 ZoomOut = new Command("Zoom Out",Command.SCREEN,1); 270 //Exit = new Command("Exit",Command.EXIT,1); 271 272 MVList.addCommand(DUMMY); 273 MVList.addCommand(Points); 274 MVList.addCommand(routes); 275 MVList.addCommand(gps); 276 MVList.addCommand(friends); 277 MVList.addCommand(ZoomIn); 278 MVList.addCommand(ZoomOut); 279 MVList.addCommand(BACK_CMD); 280 MVList.setCommandListener(this); 281 282 CONT_CMD = new Command("Continue",Command.SCREEN,1); 283 gpsTf = new SimpleTextForm(false); 284 gpsTf.addCommand(CONT_CMD); 285 gpsTf.setCommandListener(this); 286 287 288 289 290 // If Point is selected 291 WPselected = new List("",List.IMPLICIT); 292 setAsCurrent = new Command("Set as Current",Command.SCREEN,1); 293 setDest1 = new Command("Set as Destination",Command.SCREEN,1); 294 edit = new Command("Edit",Command.SCREEN,1); 295 delete = new Command("Delete",Command.SCREEN,1);

xc

Page 91: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

296 measDist = new Command("Measure Distance",Command.SCREEN,1); 297 298 299 WPselected.addCommand(DUMMY); 300 WPselected.addCommand(MAP_CMD); 301 WPselected.addCommand(setAsCurrent); 302 WPselected.addCommand(setDest1); 303 WPselected.addCommand(edit); 304 WPselected.addCommand(delete); 305 WPselected.addCommand(measDist); 306 WPselected.addCommand(BACK_CMD); 307 WPselected.setCommandListener(this); 308 309 310 311 // If Point is not selected 312 WPnotSel = new List("",List.IMPLICIT); 313 setCurrent = new Command("Set Current",Command.SCREEN,1); 314 setDest2 = new Command("Set Destination",Command.SCREEN,1); 315 addWP = new Command("Add Waypoint",Command.SCREEN,1); 316 317 WPnotSel.addCommand(DUMMY); 318 WPnotSel.addCommand(setCurrent); 319 WPnotSel.addCommand(setDest2); 320 WPnotSel.addCommand(addWP); 321 WPnotSel.addCommand(measDist); 322 //WPnotSel.addCommand(MAP_CMD); 323 WPnotSel.addCommand(BACK_CMD); 324 WPnotSel.setCommandListener(this); 325 326 WPList = new List("",List.IMPLICIT); 327 addNewWP = new Command("Add Waypoint",Command.SCREEN,1); 328 sortWP = new Command("Sort Waypoints by Distance",Command.SCREEN,1); 329 sortNameWP = new Command("Sort Waypoints by Name",Command.SCREEN,1); 330 showIDcom = new Command("Show/Hide ID",Command.SCREEN,1); 331 332 tfAdd = new TextForm(chs.getCategories(this.getAppProperty("Categories")),false); 333 334 tfAdd.addCommand(CONT_CMD); 335 tfAdd.setCommandListener(this); 336 337 sorted = new List("",List.IMPLICIT); 338 sorted.setCommandListener(this); 339 340 341 ic.addCommand(opt);

xci

Page 92: Defect prevention techniques

Zarko Acimovic

342 ic.addCommand(mod); 343 ic.setCommandListener(this); 344 345 346 tf1 = new TextForm(chs.getCategories(this.getAppProperty("Categories")),false);///form for adding new Point on selected spot 347 tf2 = new TextForm(chs.getCategories(this.getAppProperty("Categories")),false);/// form for editing of selected Point 348 tf33 = new TextForm(chs.getCategories(this.getAppProperty("Categories")),true);/// form for editing of selected Point 349 350 SAVE_CMD = new Command("Save",Command.SCREEN,1); 351 352 tf1.addCommand(CONT_CMD); 353 tf1.addCommand(BACK_CMD); 354 tf1.setCommandListener(this); 355 tf2.addCommand(CONT_CMD); 356 tf2.addCommand(BACK_CMD); 357 tf2.setCommandListener(this); 358 tf33.addCommand(CONT_CMD); 359 tf33.addCommand(BACK_CMD); 360 tf33.setCommandListener(this); 361 362 whiteList = new Vector(); 363 364 d.setCurrent(ic); 365 } 366 367 368 public void commandAction(Command c, Displayable s){ 369 370 if (c==MAP_CMD) d.setCurrent(ic); 371 if (s==ic && c==mod){ 372 d.setCurrent(modes); 373 } 374 if (s==modes && c==selectCmd){ 375 oul.setSelect(); 376 ic.repaint(); 377 d.setCurrent(ic); 378 selP.resetBig(); 379 selP.resetColor(); 380 } 381 if (s==modes && c==mapviewCmd){ 382 selP.resetColor(); 383 selP.resetBig(); 384 oul.resetSelect(); 385 d.setCurrent(ic); 386 }

xcii

Page 93: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

387 388 if (s==modes && c==compassCmd){ 389 oul.resetSelect(); 390 cc = new CompassCanvas(mob); 391 cc.addCommand(MAP_CMD); 392 cc.setCommandListener(this); 393 d.setCurrent(cc); 394 } 395 396 if (s==modes && c==exitCmd){ 397 try{ 398 destroyApp(false); 399 }catch(Exception e){} 400 notifyDestroyed(); 401 return; 402 } 403 404 if(s==cc && c==MAP_CMD){ 405 cc.setEnd(); 406 ic = new ImageCanvas3(oul); 407 ic.addCommand(opt); 408 ic.addCommand(mod); 409 ic.setCommandListener(this); 410 d.setCurrent(ic); 411 } 412 413 if (s==ic && c==opt && routeSetting==false){ 414 if(oul.getSelect()==true) { 415 selectedWP = selP.getSelectedWP(); 416 if(selectedWP.getName()=="selector") d.setCurrent(WPnotSel); 417 if(selectedWP.getName()!="selector") { 418 d.setCurrent(WPselected); 419 previousList=null; 420 } 421 } 422 if(oul.getSelect()==false) d.setCurrent(MVList); 423 } 424 425 426 // IF Point NOT SELECTED 427 if(s==WPnotSel && c==setCurrent){ 428 Point wp = selP.getSelector(); 429 wp.setName("current"); 430 mob.setCurrentPosition(wp); 431 d.setCurrent(ic); 432 } 433 if(s==WPnotSel && c==setDest2){ 434 Point wp = selP.getSelector(); 435 wp.setName("dest"); 436 mob.setDestinationPosition(wp);

xciii

Page 94: Defect prevention techniques

Zarko Acimovic

437 d.setCurrent(ic); 438 } 439 440 // ADD Point ON SELECTED SPOT 441 if(s==WPnotSel && c==addWP){ 442 tf1.setName("default"); //form for adding new Point on selected spot 443 //tf1.setType("Type will be set according to category"); 444 tf1.setLat(selP.getSelector().getLat()); 445 tf1.setLon(selP.getSelector().getLon()); 446 d.setCurrent(tf1); 447 } 448 449 if (s.equals(tf1) && c == CONT_CMD){ 450 String name = tf1.getName(); 451 int sel = tf1.getSelected(); 452 453 // chs is instance of CommaHypenString class 454 // which helps us process hyphens and commas in 455 //.properties file 456 String[] category = chs.getCategories(this.getAppProperty("Categories")); 457 String[] categoryHyphen = chs.getCategoriesHyphen(this.getAppProperty("Categories")); 458 459 // elements of a selected category: as simle strings and as hyphen-strings 460 String catMatches = this.getAppProperty(categoryHyphen[sel]); 461 String[] arCatMatches = chs.getStringsOnly(catMatches); 462 String[] arCatHyphMatches = chs.getWithLowLine(catMatches); 463 464 // images that correspond to category elements 465 String[] imageStr = new String[arCatMatches.length]; 466 Image[] img = new Image[arCatMatches.length]; 467 for(int i=0; i<arCatMatches.length; i++){ 468 imageStr[i] = this.getAppProperty(""+arCatHyphMatches[i]+""); 469 imageStr[i] = this.compact(imageStr[i]); 470 } 471 472 pathToImage = new String[arCatMatches.length]; 473 for (int i=0; i<arCatMatches.length; i++){ 474 try{ 475 String str = categoryHyphen[sel]+"/"+imageStr[i];

xciv

Page 95: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

476 str = compact(str); //getting rid off blanco spots 477 pathToImage[i] = str; 478 img[i] = Image.createImage(str); 479 } catch(Exception e){} 480 } 481 482 tf11 = new TextFormImage("",arCatMatches,img); 483 tf11.setNameCHGR("Please select type"); 484 tf11.setName(name); 485 //tf11.setType("Please select type"); 486 tf11.addCommand(BACK_CMD); 487 tf11.addCommand(SAVE_CMD); 488 tf11.setCommandListener(this); 489 d.setCurrent(tf11); 490 } 491 492 if(s==tf1 && c==BACK_CMD){ 493 d.setCurrent(WPnotSel); 494 } 495 496 if(s==tf11 && c==BACK_CMD){ 497 d.setCurrent(tf1); 498 } 499 500 if(s==tf11 && c==SAVE_CMD){ 501 Point wp = selP.getSelector(); 502 wp.setName(tf11.getName()); 503 int sel = tf11.getSelected(); 504 String cmpct = compact(pathToImage[sel]); 505 wp.setImage(cmpct); 506 mob.addFreeWaypoint(wp); 507 d.setCurrent(ic); 508 } 509 510 if(s==WPselected && c==setAsCurrent){ 511 mob.setCurrentPosition(selectedWP); 512 d.setCurrent(ic); 513 } 514 515 if(s==WPselected && c==setDest1){ 516 mob.setDestinationPosition(selectedWP); 517 d.setCurrent(ic); 518 } 519 520 //Edit of Point 521 if(s==WPselected && c==edit){ 522 tf2.setName(selectedWP.getName()); 523 tf2.setType(selectedWP.getType()); 524 tf2.setLat(selectedWP.getLat()); 525 tf2.setLon(selectedWP.getLon());

xcv

Page 96: Defect prevention techniques

Zarko Acimovic

526 d.setCurrent(tf2); 527 } 528 529 530 //Editing of waypoint OR inserting waypoint from text form 531 if ( (s.equals(tf2)||s.equals(tf33)) && c == CONT_CMD){ 532 String name =""; 533 int sel = 0; 534 535 if(s.equals(tf2)){ 536 name = tf2.getName(); 537 sel = tf2.getSelected(); 538 previous = tf2; 539 } 540 541 if(s.equals(tf33)){ 542 name = tf33.getName(); 543 sel = tf33.getSelected(); 544 previous = tf33; 545 } 546 547 548 // chs is instance of CommaHypenString class 549 // which helps us process hyphens and commas in 550 //.properties file 551 String[] category = chs.getCategories(this.getAppProperty("Categories")); 552 String[] categoryHyphen = chs.getCategoriesHyphen(this.getAppProperty("Categories")); 553 554 // elements of a selected category: as simle strings and as hyphen-strings 555 String catMatches = this.getAppProperty(categoryHyphen[sel]); 556 String[] arCatMatches = chs.getStringsOnly(catMatches); 557 String[] arCatHyphMatches = chs.getWithLowLine(catMatches); 558 559 // images that correspond to category elements 560 String[] imageStr = new String[arCatMatches.length]; 561 Image[] img = new Image[arCatMatches.length]; 562 for(int i=0; i<arCatMatches.length; i++){ 563 imageStr[i] = this.getAppProperty(""+arCatHyphMatches[i]+""); 564 imageStr[i] = this.compact(imageStr[i]); 565 } 566 567 pathToImage = new String[arCatMatches.length]; 568 for (int i=0; i<arCatMatches.length; i++){

xcvi

Page 97: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

569 try{ 570 String str = categoryHyphen[sel]+"/"+imageStr[i]; 571 str = compact(str); //getting rid off blanco spots 572 pathToImage[i] = str; 573 img[i] = Image.createImage(str); 574 } catch(Exception e){} 575 } 576 577 tf22 = new TextFormImage("",arCatMatches,img); 578 tf22.setNameCHGR("Please select type"); 579 tf22.setName(name); 580 tf22.addCommand(BACK_CMD); 581 tf22.addCommand(SAVE_CMD); 582 tf22.setCommandListener(this); 583 d.setCurrent(tf22); 584 } 585 586 if(s==tf2 && c==BACK_CMD){ 587 d.setCurrent(WPselected); 588 } 589 590 if(s==tf22 && c==BACK_CMD){ 591 d.setCurrent(previous); 592 } 593 594 if(s==tf22 && c==SAVE_CMD){ 595 596 //Editing of waypoint 597 if(previous == tf2){ 598 Point wp = selP.getSelectedWP(); 599 if(wp.getLat()==0){ 600 wp = new Point(tf2.getLat(),tf2.getLon(),tf22.getName(),"","blanco",false); 601 } 602 wp.setName(tf22.getName()); 603 int sel = tf22.getSelected(); 604 String cmpct = compact(pathToImage[sel]); 605 wp.setImage(cmpct); 606 wp.setLat(tf2.getLat()); 607 wp.setLon(tf2.getLon()); 608 selP.deleteWP(); 609 mob.addFreeWaypoint(wp); 610 selP.setColor(); 611 d.setCurrent(ic); 612 } 613 614 // New waypoint from text form 615 if(previous==tf33){

xcvii

Page 98: Defect prevention techniques

Zarko Acimovic

616 Point wp = new Point(tf33.getLat(),tf33.getLon(),tf22.getName(),"","blanco",false); 617 wp.setName(tf22.getName()); 618 int sel = tf22.getSelected(); 619 String cmpct = compact(pathToImage[sel]); 620 wp.setImage(cmpct); 621 wp.setLat(tf33.getLat()); 622 wp.setLon(tf33.getLon()); 623 mob.addFreeWaypoint(wp); 624 d.setCurrent(ic); 625 } 626 } 627 628 629 // Delete Point 630 if(s==WPselected && c==delete){ 631 int k = selP.deleteWP(); 632 if(k==-1){ 633 a.setTimeout(3000); 634 a.setString("More than one Point selected"); 635 d.setCurrent(a); 636 } else { 637 selP.resetBig(); 638 d.setCurrent(ic); 639 } 640 } 641 642 if(s==WPselected && c==BACK_CMD){ 643 if(previousList==null) d.setCurrent(ic); 644 if(previousList!=null) d.setCurrent(previousList); 645 } 646 647 648 // Measuring distance between current position and selected WAYPOINT 649 if(s==WPselected && c==measDist){ 650 if(mob.getCurrentPosition().getName().equals("dummy")){ 651 a.setTimeout(3000); 652 a.setString("Current position is not set"); 653 d.setCurrent(a); 654 655 } else { 656 a.setTimeout(3000); 657 selectedWP = selP.getSelectedWP(); 658 long k = mob.measureDistance(selectedWP); 659 a.setString("Distance is "+k+" m"); 660 d.setCurrent(a); 661 } 662

xcviii

Page 99: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

663 } 664 665 666 // Measuring distance between current position and selected LOCATION 667 if(s==WPnotSel && c==measDist){ 668 selectedWP = selP.getSelector(); 669 long k = mob.measureDistance(selectedWP); 670 if(mob.currentSet()==false){ 671 a.setTimeout(3000); 672 a.setString("Current position is not set"); 673 d.setCurrent(a); 674 675 } else { 676 a.setTimeout(3000); 677 a.setString("Distance is "+k+" m"); 678 d.setCurrent(a); 679 } 680 } 681 682 if(s==WPnotSel && c==BACK_CMD) d.setCurrent(ic); 683 684 685 686 687 688 // -----------------Showing up all Points and some operations--------------- 689 if(s==MVList && c==Points){ 690 setWPList(); 691 692 for(int i=0; i<mob.freeWaypoints.size(); i++){ 693 Point wp = (Point)mob.freeWaypoints.elementAt(i); 694 String name = ""; 695 if(showID==true){ 696 name = wp.getName()+"_"+wp.getID(); 697 } else { 698 name = wp.getName(); 699 } 700 Command cc = new Command(name,Command.SCREEN,1); 701 WPList.addCommand(cc); 702 } 703 d.setCurrent(WPList); 704 } 705 706 if(s==MVList && c==BACK_CMD){ 707 d.setCurrent(ic); 708 }

xcix

Page 100: Defect prevention techniques

Zarko Acimovic

709 710 if(s==MVList && c==ZoomIn){ 711 oul.ZoomIn(); 712 d.setCurrent(ic); 713 } 714 715 if(s==MVList && c==ZoomOut){ 716 oul.ZoomOut(); 717 d.setCurrent(ic); 718 } 719 720 721 // displaying of IDs of icons 722 if(s==WPList && c==showIDcom){ 723 if(showID==true) {showID=false; } else {showID=true;} 724 725 setWPList(); 726 727 for(int i=0; i<mob.freeWaypoints.size(); i++){ 728 Point wp = (Point)mob.freeWaypoints.elementAt(i); 729 String name = ""; 730 if(showID==true){ 731 name = wp.getName()+"_"+wp.getID(); 732 } else { 733 name = wp.getName(); 734 } 735 Command cc = new Command(name,Command.SCREEN,1); 736 WPList.addCommand(cc); 737 } 738 d.setCurrent(WPList); 739 } 740 741 742 // Adding new Point with all attributes such as 743 // LATITUDE and LONGITUDE 744 // We deal with tf33 same as with tf2 (tf2 is used for 745 // inserting new data for selected location 746 // Here default values for coordinates are those of center of the map 747 748 if(s==WPList && c==addNewWP){ 749 tf33.setName("Center of Map");//44.80345511,20.42949821 750 tf33.setType(""); 751 tf33.setLat("44.80345511"); 752 tf33.setLon("20.42949821"); 753 d.setCurrent(tf33);

c

Page 101: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

754 } 755 756 757 758 if(s==tf33 && c==BACK_CMD){ 759 d.setCurrent(WPList); 760 } 761 762 //sorting waypoints by distance 763 if(s==WPList && c==sortWP){ 764 setWPList(); 765 766 Vector sor = mob.freeWaypoints.sortAscending(mob.getCurrentPosition()); 767 for(int i=0; i<sor.size(); i++){ 768 Point wp = (Point)sor.elementAt(i); 769 String name = ""; 770 if(showID==true){ 771 name = wp.getName()+" "+wp.getID(); 772 } else { 773 name = wp.getName(); 774 } 775 Command cc = new Command(name,Command.SCREEN,1); 776 WPList.addCommand(cc); 777 } 778 d.setCurrent(WPList); 779 } 780 781 //sorting waypoints by name 782 if(s==WPList && c==sortNameWP){ 783 setWPList(); 784 String[] sor = mob.freeWaypoints.sortByName(); 785 for(int i=0; i<sor.length; i++){ 786 Command cc = new Command(sor[i],Command.SCREEN,1); 787 WPList.addCommand(cc); 788 } 789 d.setCurrent(WPList); 790 } 791 792 793 if(s==WPList && c==MAP_CMD){ 794 d.setCurrent(ic); 795 } 796 797 if(s==WPList && c==BACK_CMD){ 798 d.setCurrent(MVList); 799 } 800 801 //Displaying selected waypoint

ci

Page 102: Defect prevention techniques

Zarko Acimovic

802 if(s==WPList && c!=sortWP && c!=addNewWP && c!=MAP_CMD && c!=sortNameWP && c!=DUMMY && c!=BACK_CMD){ 803 String name = c.getLabel(); 804 mb.param=true; 805 selP.selectWP(name); 806 oul.setSelect(); 807 oul.setWPselection(); 808 d.setCurrent(WPselected); 809 previousList = WPList; 810 } 811 812 813 814 // -------------- ROUTES -------------------------------- 815 816 // Main Menu for Routes 817 if(s==MVList && c==routes){ 818 routeMain = new List("",List.IMPLICIT); 819 createNewRoute = new Command("New Route",Command.SCREEN,1); 820 routeMain.addCommand(DUMMY); 821 routeMain.addCommand(createNewRoute); 822 routeMain.addCommand(BACK_CMD); 823 routeMain.addCommand(DELIM); 824 routeMain.setCommandListener(this); 825 for(int i=0; i<mob.getRoutes().size(); i++){ 826 PVector route = (PVector)mob.getRoutes().elementAt(i); 827 String name = route.getName(); 828 Command cr = new Command(name,Command.SCREEN,1); 829 routeMain.addCommand(cr); 830 } 831 d.setCurrent(routeMain); 832 } 833 834 if(s==routeMain && c==BACK_CMD){ 835 d.setCurrent(MVList); 836 } 837 838 //Creating a New Route 839 if(s==routeMain && c==createNewRoute){ 840 tf3 = new SimpleTextForm(false); 841 tf3.addCommand(SAVE_CMD); 842 tf3.setCommandListener(this); 843 d.setCurrent(tf3); 844 } 845 846 847 if(s==tf3 && c==SAVE_CMD){ 848 newRouteVector = new PVector("",true);

cii

Page 103: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

849 newRouteVector.setName(tf3.getName()); 850 newRouteVector.setVisible(); 851 mob.addRoute(newRouteVector); 852 853 routeNew = new List("",List.IMPLICIT); 854 addPoint = new Command("Add Waypoint",Command.SCREEN,1); 855 routeFin = new Command("Route Finished",Command.SCREEN,1); 856 routeNew.addCommand(addPoint); 857 routeNew.addCommand(routeFin); 858 routeNew.setCommandListener(this); 859 860 d.setCurrent(routeNew); 861 } 862 863 864 // Selection of specific route 865 if(s==routeMain && c!=createNewRoute && c!=DUMMY && c!=BACK_CMD && c!=DELIM){ 866 nameR = c.getLabel(); 867 routeOptions = new List("",List.IMPLICIT); 868 showRoutes = new Command("Show/Hide Route",Command.SCREEN,1); 869 delRoute = new Command("Delete Route",Command.SCREEN,1); 870 routeOptions.addCommand(DUMMY); 871 routeOptions.addCommand(MAP_CMD); 872 routeOptions.addCommand(showRoutes); 873 routeOptions.addCommand(delRoute); 874 routeOptions.addCommand(BACK_CMD); 875 routeOptions.setCommandListener(this); 876 d.setCurrent(routeOptions); 877 } 878 879 //Viewing selected route 880 if(s==routeOptions && c==showRoutes){ 881 Vector allR = (Vector) mob.getRoutes(); 882 for(int i=0; i<allR.size(); i++){ 883 PVector rt = (PVector)allR.elementAt(i); 884 if(rt.getName()==nameR) { 885 if(rt.size()!=0){ 886 if(rt.getVisible()==true){ 887 rt.resetVisible(); 888 d.setCurrent(ic); 889 }else{ 890 rt.setVisible(); 891 Point wp = (Point) rt.elementAt(0); 892 String name = wp.getName();

ciii

Page 104: Defect prevention techniques

Zarko Acimovic

893 selP.selectWP(name); 894 oul.setSelect(); 895 selP.resetColor(); 896 selP.resetBig(); 897 d.setCurrent(ic); 898 } 899 } 900 if(rt.size()==0){ 901 a.setTitle("Warning"); 902 a.setString("Route has no points to show"); 903 a.setTimeout(5000); 904 d.setCurrent(a); 905 } 906 907 } 908 if(rt.getName()!=nameR) rt.resetVisible(); 909 } 910 } 911 912 913 //Deletion of selected route 914 if(s==routeOptions && c==delRoute){ 915 Vector v = mob.getRoutes(); 916 for(int i=0; i<v.size(); i++){ 917 PVector wpv = (PVector)v.elementAt(i); 918 if(wpv.getName()==nameR){ 919 mob.removeRoute(nameR); 920 i=1000; 921 } 922 } 923 d.setCurrent(ic); 924 } 925 926 927 //Mapview 928 if(s==routeOptions && c==MAP_CMD){ 929 Vector v = mob.getRoutes(); 930 for(int i=0; i<v.size(); i++){ 931 PVector wpv = (PVector)v.elementAt(i); 932 if(wpv.getName()==nameR){ 933 Point p = (Point) wpv.elementAt(0); 934 selP.selectWP(p.getName()); 935 oul.setSelect(); 936 oul.setWPselection(); 937 i=1000; 938 } 939 } 940 d.setCurrent(ic); 941 }

civ

Page 105: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

942 943 //Back on routeMain 944 if(s==routeOptions && c==BACK_CMD){ 945 d.setCurrent(routeMain); 946 } 947 948 949 950 951 952 //Adding new point in current route 953 if(s==routeNew && c==addPoint){ 954 if(oul.getSelect()==true){ 955 mob.removeRoute(newRouteVector); 956 Point wp = selP.getSelector(); 957 wp.setTypeID(newRouteVector.getID()); 958 wp.setName(newRouteVector.getName()); 959 wp.setImage("route"); 960 newRouteVector.addElement(wp); 961 mob.addRoute(newRouteVector); 962 d.setCurrent(ic); 963 } 964 965 if(oul.getSelect()==false){ 966 oul.setSelect(); 967 oul.setRoute(); 968 routeSetting = true; 969 d.setCurrent(ic); 970 } 971 972 } 973 974 if(s==ic && routeSetting==true && c==opt){ 975 d.setCurrent(routeNew); 976 } 977 978 if(s==routeNew && c==routeFin){ 979 oul.resetSelect(); 980 routeSetting = false; 981 d.setCurrent(ic); 982 } 983 984 985 986 987 988 989 //--------------------------------GPS ON/OFF------------------------------ 990 991 if(s==MVList && c==gps){

cv

Page 106: Defect prevention techniques

Zarko Acimovic

992 gpsList = new List("",List.IMPLICIT); 993 onGPSc = new Command("On",Command.SCREEN,1); 994 offGPSc = new Command("Off",Command.SCREEN,1); 995 gpsList.addCommand(onGPSc); 996 gpsList.addCommand(offGPSc); 997 gpsList.setCommandListener(this); 998 d.setCurrent(gpsList); 999 } 1000 1001 if(s==gpsList && c==onGPSc){ 1002 if(gpsON==false){ 1003 gpsON=true; 1004 followFriends = false; 1005 //Specifying GPS coordinates resource 1006 gpsTf.setLabel("Please select source of GPS coordinates, usually it's GPS.txt"); 1007 gpsTf.setName("GPS.txt"); 1008 gpsTf.setType("GPS.txt"); 1009 d.setCurrent(gpsTf); //GPS textform 1010 } else { 1011 d.setCurrent(ic); 1012 } 1013 } 1014 1015 if(s==gpsList && c==offGPSc){ 1016 gpsON=false; 1017 d.setCurrent(ic); 1018 } 1019 1020 1021 1022 if(s==gpsTf && c==CONT_CMD){ 1023 resource = gpsTf.getName(); 1024 1025 syncFollow = true; 1026 synchronizationDone=false; 1027 1028 t1=new Thread(this); 1029 currentlyShowed = t1.hashCode(); 1030 gpsHash = t1.hashCode(); 1031 t1.start(); 1032 d.setCurrent(ic); 1033 1034 } 1035 1036 // --------------------------- HANDLING FRIENDS' ISSUES ------------------- 1037 1038 if(s==MVList && c==friends){ 1039 friendList = new List("",List.IMPLICIT);

cvi

Page 107: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

1040 addNewFriend = new Command("Add New Friend", Command.SCREEN,1); 1041 stopFollow = new Command("Stop Follow Friends", Command.SCREEN,1); 1042 deleteFriends = new Command("Delete Friends", Command.SCREEN,1); 1043 friendList.addCommand(DUMMY); 1044 friendList.addCommand(addNewFriend); 1045 friendList.addCommand(stopFollow); 1046 friendList.addCommand(deleteFriends); 1047 friendList.addCommand(BACK_CMD); 1048 friendList.addCommand(DELIM); 1049 if(listOfFriends.size()>0){ 1050 for (int i=0; i<listOfFriends.size(); i++){ 1051 Friend f = (Friend)listOfFriends.elementAt(i); 1052 Command cc = new Command(f.getName(),Command.SCREEN,1); 1053 friendList.addCommand(cc); 1054 } 1055 } 1056 friendList.setCommandListener(this); 1057 d.setCurrent(friendList); 1058 } 1059 1060 if(s==friendList && c==addNewFriend){ 1061 friendForm = new SimpleTextForm(false); 1062 friendForm.setLabel("Friend"); 1063 friendForm.setLabel2("Source of coordinates"); 1064 friendForm.setName("Mika"); 1065 friendForm.setType("Mika.txt"); 1066 1067 friendForm.addCommand(CONT_CMD); 1068 friendForm.setCommandListener(this); 1069 1070 d.setCurrent(friendForm); 1071 } 1072 1073 if(s==friendForm && c==CONT_CMD){ 1074 tff = new Thread4Friend(whiteList,friendForm.getName(),mob,ic,mb,oul); 1075 Integer hID = new Integer(tff.getID()); 1076 whiteList.addElement(hID); 1077 1078 tff.start(); 1079 Friend f = new Friend(friendForm.getName(),friendForm.getType(),tff.getID(),tff); 1080 listOfFriends.addElement(f); 1081 d.setCurrent(ic); 1082 } 1083

cvii

Page 108: Defect prevention techniques

Zarko Acimovic

1084 if(s==friendList && c==stopFollow){ 1085 whiteList.removeAllElements(); 1086 mob.deleteAllFriends(); 1087 ic.repaint(); 1088 d.setCurrent(ic); 1089 } 1090 1091 if(s==friendList && c==deleteFriends){ 1092 mob.deleteAllFriends(); 1093 listOfFriends.removeAllElements(); 1094 friendList = new List("",List.IMPLICIT); 1095 addNewFriend = new Command("Add New Friend", Command.SCREEN,1); 1096 stopFollow = new Command("Stop Follow Friends", Command.SCREEN,1); 1097 deleteFriends = new Command("Delete Friends", Command.SCREEN,1); 1098 friendList.addCommand(DUMMY); 1099 friendList.addCommand(addNewFriend); 1100 friendList.addCommand(stopFollow); 1101 friendList.addCommand(deleteFriends); 1102 //friendList.addCommand(MAP_CMD); 1103 friendList.addCommand(BACK_CMD); 1104 friendList.addCommand(DELIM); 1105 if(listOfFriends.size()>0){ 1106 for (int i=0; i<listOfFriends.size(); i++){ 1107 Friend f = (Friend)listOfFriends.elementAt(i); 1108 Command cc = new Command(f.getName(),Command.SCREEN,1); 1109 friendList.addCommand(cc); 1110 } 1111 } 1112 friendList.setCommandListener(this); 1113 d.setCurrent(friendList); 1114 d.setCurrent(friendList); 1115 } 1116 1117 if(s==friendList && c!=addNewFriend && c!=stopFollow && c!=deleteFriends && c!=MAP_CMD && c!=BACK_CMD && c!=DELIM){ 1118 friend = c.getLabel(); 1119 friend = compact(friend); 1120 oneFriend = new List("",List.IMPLICIT); 1121 stopFollowOne = new Command("Stop Follow", Command.SCREEN,1); 1122 deleteFriend = new Command("Delete", Command.SCREEN,1); 1123 oneFriend.addCommand(DUMMY); 1124 oneFriend.addCommand(MAP_CMD); 1125 oneFriend.addCommand(stopFollowOne); 1126 oneFriend.addCommand(deleteFriend);

cviii

Page 109: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

1127 oneFriend.addCommand(BACK_CMD); 1128 oneFriend.setCommandListener(this); 1129 1130 d.setCurrent(oneFriend); 1131 } 1132 1133 if(s==friendList && c==BACK_CMD){ 1134 d.setCurrent(MVList); 1135 } 1136 1137 if(s==oneFriend && c==MAP_CMD){ 1138 for(int i=0; i<listOfFriends.size(); i++){ 1139 Friend f = (Friend)listOfFriends.elementAt(i); 1140 if(f.getName().equals(friend)) { 1141 1142 if(f.getThread()==false){ 1143 tff = new Thread4Friend(whiteList,f.getName(),mob,ic,mb,oul); 1144 Integer hID = new Integer(tff.getID()); 1145 whiteList.addElement(hID); 1146 f.setID(tff.getID()); 1147 f.setThread(tff); 1148 tff.setFirst(); 1149 tff.start(); 1150 } else { 1151 f.setFirst(); 1152 } 1153 } 1154 } 1155 d.setCurrent(ic); 1156 } 1157 1158 if(s==oneFriend && c==BACK_CMD){ 1159 d.setCurrent(friendList); 1160 } 1161 1162 if(s==oneFriend && c==stopFollowOne){ 1163 for(int i=0; i<listOfFriends.size(); i++){ 1164 Friend f = (Friend)listOfFriends.elementAt(i); 1165 if(f.getName().equals(friend)) { 1166 whiteList.removeElement(new Integer(f.getHash())); 1167 mob.deleteFriend(f.getHash()); 1168 f.setThread(null); 1169 } 1170 } 1171 d.setCurrent(ic); 1172 }

cix

Page 110: Defect prevention techniques

Zarko Acimovic

1173 1174 if(s==oneFriend && c==deleteFriend){ 1175 for(int i=0; i<listOfFriends.size(); i++){ 1176 Friend f = (Friend)listOfFriends.elementAt(i); 1177 if(f.getName().equals(friend)) { 1178 whiteList.removeElement(new Integer(f.getHash())); 1179 mob.deleteFriend(f.getHash()); 1180 listOfFriends.removeElementAt(i); 1181 } 1182 } 1183 d.setCurrent(ic); 1184 } 1185 1186 } 1187 1188 1189 //----------------------This part of code deals with GPS--------------------- 1190 public void run(){ 1191 while(followFriends==true || gpsON==true){ 1192 String s = this.getResourceAsString(resource); 1193 int nextIndex = 6; 1194 int index = s.indexOf('\n'); 1195 1196 nextIndex = s.indexOf('\n',index+1); 1197 1198 int lastIndex = s.lastIndexOf('\n'); 1199 1200 int begin = -2; 1201 int end = index; 1202 1203 String c1 = ""; 1204 String c2 = ""; 1205 String timeStamp = ""; 1206 long currentTS = 0; 1207 1208 while(index<lastIndex && gpsON==true){ 1209 Thread t = Thread.currentThread(); 1210 if(t.hashCode()==currentlyShowed){ 1211 /** 1212 if(synchronizationDone==false && syncFollow==true){ 1213 do{ //Synchronization 1214 String temp = s.substring(begin+2,end); 1215 temp = compact(temp); 1216 int comma = temp.indexOf(',');

cx

Page 111: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

1217 c1 = temp.substring(0,comma); 1218 int nextComma = temp.indexOf(',',comma+1); 1219 c2 = temp.substring(comma+1,nextComma); 1220 timeStamp = temp.substring(nextComma+1,temp.length()); 1221 currentTS = Long.parseLong(timeStamp); 1222 begin = index-1; 1223 end = nextIndex; 1224 index = nextIndex; 1225 nextIndex = s.indexOf('\n',nextIndex+1); 1226 }while(currentTS<this.getTimeStamp()); 1227 synchronizationDone = true; 1228 }*/ 1229 1230 Point wp = null; 1231 if(!c1.equals("")){ 1232 wp = new Point(c2,c1,resource,"","blanco",true); 1233 } 1234 if(syncFollow==true) { 1235 this.setTimeStamp(currentTS); 1236 } 1237 1238 String temp = s.substring(begin+2,end); 1239 temp = compact(temp); 1240 if(temp.equals("")){ //na kraju ce temp da bude prazno 1241 index = lastIndex+1; 1242 } else { 1243 temp = compact(temp); 1244 int comma = temp.indexOf(','); 1245 c1 = temp.substring(0,comma); 1246 int nextComma = temp.indexOf(',',comma+1); 1247 c2 = temp.substring(comma+1,nextComma); 1248 timeStamp = temp.substring(nextComma+1,temp.length()); 1249 currentTS = Long.parseLong(timeStamp); 1250

cxi

Page 112: Defect prevention techniques

Zarko Acimovic

1251 begin = index-1; 1252 end = nextIndex; 1253 index = nextIndex; 1254 nextIndex = s.indexOf('\n',nextIndex+1); 1255 } 1256 1257 try{ 1258 Thread.sleep(1000); 1259 }catch(Exception e){} 1260 1261 if(wp!=null){ 1262 mob.setDrawablePoints(); 1263 if(gpsON==true){ 1264 mob.setCurrentPosition(wp); 1265 if((mob.getCurrentPosition().getX()>170 || mob.getCurrentPosition().getY()>160 || 1266 mob.getCurrentPosition().getX()<10 || mob.getCurrentPosition().getY()<10) && oul.getSelect()==false ) 1267 mb.setBackground(wp); 1268 ic.repaint(); 1269 1270 } 1271 } 1272 } 1273 } 1274 } 1275 1276 } 1277 1278 /** 1279 * @see MIDlet#pauseApp() 1280 */ 1281 protected void pauseApp() { 1282 } 1283 1284 /** 1285 * @see MIDlet#destroyApp(boolean) 1286 */ 1287 protected void destroyApp(boolean flag) throws MIDletStateChangeException { 1288 } 1289 1290 1291 /** Blanco characters are possible to occur in names of pictures; 1292 * Integer representations of blanko characters are 9 and 32 1293 * Also, characters with integer representation between 0 and 33

cxii

Page 113: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

1294 * can not be printed out in WSDD console, so I excluded them too 1295 */ 1296 public String compact(String s){ 1297 int k = s.length(); 1298 char[] d = s.toCharArray(); 1299 String ret = ""; 1300 for(int i=0; i<d.length; i++){ 1301 int temp = (int)d[i]; 1302 if(temp>32) ret+=d[i]; 1303 } 1304 int kk = ret.length(); 1305 return ret; 1306 } 1307 1308 public String compactFine(String s){ 1309 int k = s.length(); 1310 char[] d = s.toCharArray(); 1311 String ret = ""; 1312 for(int i=0; i<d.length; i++){ 1313 int temp = (int)d[i]; 1314 if(temp!=32 && temp!=9) ret+=d[i]; 1315 } 1316 int kk = ret.length(); 1317 return ret; 1318 } 1319 1320 public String getResourceAsString(String resource){ 1321 InputStream is = null; 1322 try{ 1323 is = this.getClass().getResourceAsStream(resource); 1324 }catch(Exception e) { 1325 a.setString("There is no such resource"); 1326 d.setCurrent(a); 1327 } 1328 1329 //conversion of resource into string 1330 String s = ""; 1331 char m =' '; 1332 1333 try{ 1334 m = (char)is.read(); 1335 }catch(Exception e){} 1336 1337 while(m!=65535){ 1338 s+=m; 1339 try{ 1340 m = (char)is.read(); 1341 }catch(Exception e){} 1342 } 1343 try{ 1344 is.close();

cxiii

Page 114: Defect prevention techniques

Zarko Acimovic

1345 }catch(Exception e){} 1346 1347 1348 s=compactFine(s); 1349 return s; 1350 } 1351 1352 public long getTimeStamp(){ 1353 return globalTimeStamp; 1354 } 1355 1356 public void setTimeStamp(long tms){ 1357 globalTimeStamp = tms; 1358 } 1359 1360 public void setWPList(){ 1361 WPList = new List("",List.IMPLICIT); 1362 WPList.addCommand(DUMMY); 1363 WPList.addCommand(addNewWP); 1364 WPList.addCommand(sortWP); 1365 WPList.addCommand(sortNameWP); 1366 WPList.addCommand(showIDcom); 1367 WPList.addCommand(BACK_CMD); 1368 WPList.addCommand(DELIM); 1369 WPList.setCommandListener(this); 1370 1371 } 1372 } 1373 1374 1375

cxiv

Page 115: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

MathFP.java

cxv

All classes and interfaces must belong to a named package 11 PMD Marker

11 PMD Marker

The class 'MathFP' has a Cyclomatic Complexity of 3 (Highest = 12). 11 PMD Marker

This class has too many methods, consider refactoring it. 11 PMD Marker

Weighted Methods per Class is 105 11 Metrics Marker

Avoid variables with short names like by 16 PMD Marker

Parameter 'by' is not assigned and could be declared final 16 PMD Marker

Parameter 'num' is not assigned and could be declared final 16 PMD Marker

Avoid variables with short names like l 35 PMD Marker

Parameter 'l' is not assigned and could be declared final 35 PMD Marker

A method should have only one exit point, and that should be the last statement in the method 37 PMD Marker

Avoid using if...else statements without curly braces 37 PMD Marker

Avoid using if...else statements without curly braces 39 PMD Marker

Avoid variables with short names like l 47 PMD Marker

Parameter 'l' is not assigned and could be declared final 47 PMD Marker

A method should have only one exit point, and that should be the last statement in the method 49 PMD Marker

Avoid using if...else statements without curly braces 49 PMD Marker

Avoid using if...else statements without curly braces 51 PMD Marker

Avoid variables with short names like e 62 PMD Marker

Avoid variables with short names like PI 63 PMD Marker

The field name indicates a constant but its modifiers do not 63 PMD Marker

The field name indicates a constant but its modifiers do not 64 PMD Marker

Lines of Code in Method is 19 68 Metrics Marker

Parameter 'i' is not assigned and could be declared final 68 PMD Marker

Avoid using if statements without curly braces 69 PMD Marker

A method should have only one exit point, and that should be the last statement in the method 70 PMD Marker

A method should have only one exit point, and that should be the last statement in the method 94 PMD Marker

Avoid using if...else statements without curly braces 94 PMD Marker

Local variable 'l1' could be declared final 112 PMD Marker

Avoid using if statements without curly braces 113 PMD Marker

Cyclomatic Complexity is 7 121 Metrics Marker

Lines of Code in Method is 22 121 Metrics Marker

Number of Statements is 31 121 Metrics Marker

Avoid using if statements without curly braces 123 PMD Marker

Avoid using for statements without curly braces 128 PMD Marker

MathFP.toFP(String) concatenates strings using + in a loop 128 FindBugs

Prefer StringBuffer over += for concatenating strings 128 PMD Marker

Avoid using if statements without curly braces 129 PMD Marker

Avoid using if statements without curly braces 135 PMD Marker

Local variable 'l1' could be declared final 137 PMD Marker

All methods are static. Consider using Singleton instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning.

Page 116: Defect prevention techniques

Zarko Acimovic

MathFP.java

1 /** 2 * MathFP implements fix point as a replacement for floating point 3 */ 4 5 6 7 // Processed by NMI's Java Code Viewer 4.8.1 © 1997-2000 B. Lemaire 8 // Website: http://njcv.htmlplanet.com E-mail: [email protected] 9 // Copy registered to Evaluation Copy 10 11 public class MathFP { 12 13 /** Modulo (% operator) implementaition missing in MathFP 2.0.6 14 * @author BMa 15 */

cxvi

Cyclomatic Complexity is 9 199 Metrics Marker

Lines of Code in Method is 29 199 Metrics Marker

Number of Statements is 26 199 Metrics Marker

The method 'mul' has a Cyclomatic Complexity of 12. 199 PMD Marker

The method mul() has an NPath complexity of 320 199 PMD Marker

A method should have only one exit point, and that should be the last statement in the method 204 PMD Marker

Cyclomatic Complexity is 8 229 Metrics Marker

Lines of Code in Method is 21 229 Metrics Marker

The method 'div' has a Cyclomatic Complexity of 11. 229 PMD Marker

Cyclomatic Complexity is 5 266 Metrics Marker

The String literal "Bad Input" appears 4 times in this file; the first occurrence is on 268 268 PMD Marker

Avoid using for statements without curly braces 272 PMD Marker

Lines of Code in Method is 16 286 Metrics Marker

Number of Statements is 29 286 Metrics Marker

Consider simply returning the value vs storing it in local variable 'l5' 300 PMD Marker

Cyclomatic Complexity is 8 336 Metrics Marker

Lines of Code in Method is 31 336 Metrics Marker

Number of Statements is 33 336 Metrics Marker

The method 'exp' has a Cyclomatic Complexity of 10. 336 PMD Marker

Avoid using for statements without curly braces 343 PMD Marker

Cyclomatic Complexity is 8 368 Metrics Marker

Lines of Code in Method is 28 368 Metrics Marker

Number of Statements is 28 368 Metrics Marker

Avoid unused local variables such as 'l2'. 372 PMD Marker

The local variable l2 is never read 372 Java Problem

Avoid if (x != y) ..; else ..; 390 PMD Marker

Cyclomatic Complexity is 5 397 Metrics Marker

Lines of Code in Method is 18 397 Metrics Marker

Page 117: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

16 public static long mod(long num, long by) { 17 //System.out.println("mod: "+MathFP.toString(num)+" by: "+MathFP.toString(by)); 18 long frac = MathFP.div(num, by); 19 //System.out.println("MathFP.div(num, by): "+MathFP.toString(MathFP.div(num, by))); 20 //long frac = MathFP.round(frac, 0); does not work properly??? 21 //System.out.println("MathFP.round(MathFP.div(num, by), 0): "+MathFP.toString(MathFP.round(MathFP.div(num, by), 0))); 22 frac = MathFP.toFP(MathFP.toLong(frac)); 23 //System.out.println("MathFP.better(MathFP.div(num, by), 0): "+MathFP.toString(frac)); 24 //System.out.println("MathFP.mul(by, frac): "+MathFP.toString(MathFP.mul(by, frac))); 25 //System.out.println("MathFP.mod: "+MathFP.toString(num - MathFP.mul(by, frac))); 26 return num - MathFP.mul(by, frac); 27 } 28 29 30 //private static long sinLimit=toFP("0.0055"); 31 32 /** Fix of bad sin() in MathFP 2.0.6 - X is closer to real sin(X) than calculated value for small X 33 * @author BMa 34 */ 35 public static long sin(long l) { 36 if (abs(l) > toFP("0.0055")) 37 return sinBad(l); 38 else 39 return l; 40 } 41 42 //private static long asinLimit=toFP("0.019"); 43 44 /** Fix of bad asin() in MathFP 2.0.6 - X is closer to real asin(X) than calculated value for small X 45 * @author BMa 46 */ 47 public static long asin(long l) { 48 if (abs(l) > toFP("0.019")) 49 return asinBad(l); 50 else 51 return l; 52 } 53 54 55 private static int _fbits = 24; 56 private static int _digits = 8; 57 private static long _one; 58 private static long _fmask = 0xffffffL;

cxvii

Page 118: Defect prevention techniques

Zarko Acimovic

59 private static long _dmul = 0x5f5e100L; 60 private static long _flt = 0L; 61 private static long _pi; 62 private static long e[]; 63 public static long PI; 64 public static long E; 65 public static final long MAX_VALUE = 0x7fffffffffffffffL; 66 public static final long MIN_VALUE = 0x8000000000000001L; 67 68 public static int setPrecision(int i) { 69 if(i > 24 || i < 0) 70 return _digits; 71 _fbits = i; 72 _one = 1L << i; 73 _flt = 24 - i; 74 _digits = 0; 75 _dmul = 1L; 76 _fmask = _one - 1L; 77 PI = _pi >> (int)_flt; 78 E = e[1] >> (int)_flt; 79 for(long l = _one; l != 0L;) { 80 l /= 10L; 81 _digits++; 82 _dmul *= 10L; 83 } 84 85 return _digits; 86 } 87 88 public static int getPrecision() { 89 return _fbits; 90 } 91 92 public static long toLong(long l) { 93 if(l < 0L) 94 return -(round(-l, 0) >> _fbits); 95 else 96 return round(l, 0) >> _fbits; 97 } 98 99 public static long toLongZare(long i) { 100 if(i >= 0) 101 i += 2048; 102 else 103 i -= 2048; 104 return i >> 12; 105 } 106 107 public static long toFP(long l) { 108 return l << _fbits; 109 }

cxviii

Page 119: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

110 111 public static long convert(long l, int i) { 112 long l1 = l >= 0L ? 1L : -1L; 113 if(abs(i) < 25L) 114 if(_fbits < i) 115 l = l + l1 * (1L << (i - _fbits >> 1)) >> i - _fbits; 116 else 117 l <<= _fbits - i; 118 return l; 119 } 120 121 public static long toFP(String s) { 122 int i = 0; 123 if(s.charAt(0) == '-') 124 i = 1; 125 String s1 = "-1"; 126 int j = s.indexOf(46); 127 if(j >= 0) { 128 for(s1 = s.substring(j + 1, s.length()); s1.length() < _digits; s1 = s1 + "0"); 129 if(s1.length() > _digits) 130 s1 = s1.substring(0, _digits); 131 } else { 132 j = s.length(); 133 } 134 long l = 0L; 135 if(i != j) 136 l = Long.parseLong(s.substring(i, j)); 137 long l1 = Long.parseLong(s1) + 1L; 138 long l2 = (l << _fbits) + (l1 << _fbits) / _dmul; 139 if(i == 1) 140 l2 = -l2; 141 return l2; 142 } 143 144 public static String toString(long l) { 145 boolean flag = false; 146 if(l < 0L) { 147 flag = true; 148 l = -l; 149 } 150 long l1 = l >> _fbits; 151 long l2 = _dmul * (l & _fmask) >> _fbits; 152 String s; 153 for(s = Long.toString(l2); s.length() < _digits; s = "0" + s); 154 return (flag ? "-" : "") + Long.toString(l1) + "." + s; 155 } 156 157 public static String toString(long l, int i) { 158 if(i > _digits) 159 i = _digits;

cxix

Page 120: Defect prevention techniques

Zarko Acimovic

160 String s = toString(round(l, i)); 161 return s.substring(0, (s.length() - _digits) + i); 162 } 163 164 public static long getWholePart(String s){ 165 166 int end = s.indexOf('.'); 167 s = s.substring(0,end); 168 long wh = toFP(s); 169 return wh; 170 } 171 /** 172 public static long getWholePart(long l){ 173 String s = toString(l); 174 int end = s.indexOf('.'); 175 s = s.substring(0,end); 176 long wh = toFP(s); 177 return wh; 178 }*/ 179 180 public static long max(long l, long l1) { 181 return l >= l1 ? l : l1; 182 } 183 184 public static long min(long l, long l1) { 185 return l1 >= l ? l : l1; 186 } 187 188 public static long round(long l, int i) { 189 long l1 = 10L; 190 for(int j = 0; j < i; j++) 191 l1 *= 10L; 192 193 l1 = div(toFP(5L), toFP(l1)); 194 if(l < 0L) 195 l1 = -l1; 196 return l + l1; 197 } 198 199 public static long mul(long l, long l1) { 200 boolean flag = false; 201 int i = _fbits; 202 long l2 = _fmask; 203 if((l & l2) == 0L) 204 return (l >> i) * l1; 205 if((l1 & l2) == 0L) 206 return l * (l1 >> i); 207 if(l < 0L && l1 > 0L || l > 0L && l1 < 0L) 208 flag = true; 209 if(l < 0L) 210 l = -l;

cxx

Page 121: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

211 if(l1 < 0L) 212 l1 = -l1; 213 for(; max(l, l1) >= 1L << 63 - i; i--) { 214 l >>= 1; 215 l1 >>= 1; 216 l2 >>= 1; 217 } 218 219 long l3 = (l >> i) * (l1 >> i) << i; 220 long l4 = (l & l2) * (l1 & l2) >> i; 221 l4 += (l & ~l2) * (l1 & l2) >> i; 222 l3 = l3 + l4 + ((l & l2) * (l1 & ~l2) >> i) << _fbits - i; 223 if(l3 < 0L) 224 throw new ArithmeticException("Overflow"); 225 else 226 return flag ? -l3 : l3; 227 } 228 229 public static long div(long l, long l1) { 230 boolean flag = false; 231 int i = _fbits; 232 if(l1 == _one) 233 return l; 234 if((l1 & _fmask) == 0L) 235 return l / (l1 >> i); 236 if(l < 0L && l1 > 0L || l > 0L && l1 < 0L) 237 flag = true; 238 if(l < 0L) 239 l = -l; 240 if(l1 < 0L) 241 l1 = -l1; 242 for(; max(l, l1) >= 1L << 63 - i; i--) { 243 l >>= 1; 244 l1 >>= 1; 245 } 246 247 long l2 = (l << i) / l1 << _fbits - i; 248 return flag ? -l2 : l2; 249 } 250 251 public static long add(long l, long l1) { 252 return l + l1; 253 } 254 255 public static long sub(long l, long l1) { 256 return l - l1; 257 } 258 259 public static long abs(long l) { 260 if(l < 0L) 261 return -l;

cxxi

Page 122: Defect prevention techniques

Zarko Acimovic

262 else 263 return l; 264 } 265 266 public static long sqrt(long l, int i) { 267 if(l < 0L) 268 throw new ArithmeticException("Bad Input"); 269 if(l == 0L) 270 return 0L; 271 long l1 = l + _one >> 1; 272 for(int j = 0; j < i; j++) 273 l1 = l1 + div(l, l1) >> 1; 274 275 if(l1 < 0L) 276 throw new ArithmeticException("Overflow"); 277 else 278 return l1; 279 } 280 281 public static long sqrt(long l) { 282 return sqrt(l, 24); 283 } 284 285 //public static long sin(long l) { 286 private static long sinBad(long l) { 287 long l1 = mul(l, div(toFP(180L), PI)); 288 l1 %= toFP(360L); 289 if(l1 < 0L) 290 l1 = toFP(360L) + l1; 291 long l2 = l1; 292 if(l1 >= toFP(90L) && l1 < toFP(270L)) 293 l2 = toFP(180L) - l1; 294 else 295 if(l1 >= toFP(270L) && l1 < toFP(360L)) 296 l2 = -(toFP(360L) - l1); 297 long l3 = l2 / 90L; 298 long l4 = mul(l3, l3); 299 long l5 = mul(mul(mul(mul(0xfffffffffffee21aL >> (int)_flt, l4) + (0x14594dL >> (int)_flt), l4) - (0xa55b13L >> (int)_flt), l4) + (long)(0x1921f9c >> (int)_flt), l3); 300 return l5; 301 } 302 303 //public static long asin(long l) { 304 private static long asinBad(long l) { 305 if(abs(l) > _one) { 306 throw new ArithmeticException("Bad Input"); 307 } else { 308 boolean flag = l < 0L; 309 l = abs(l);

cxxii

Page 123: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

310 long l1 = mul(mul(mul(mul(0x236cf >> (int)_flt, l) - (long)(0x92748 >> (int)_flt), l) + (long)(0x15acb4 >> (int)_flt), l) - (long)(0x36d0dd >> (int)_flt), l) + (long)(0x1921f27 >> (int)_flt); 311 long l2 = PI / 2L - mul(sqrt(_one - l), l1); 312 return flag ? -l2 : l2; 313 } 314 } 315 316 public static long cos(long l) { 317 return sin(PI / 2L - l); 318 } 319 320 public static long acos(long l) { 321 return PI / 2L - asin(l); 322 } 323 324 public static long tan(long l) { 325 return div(sin(l), cos(l)); 326 } 327 328 public static long cot(long l) { 329 return div(cos(l), sin(l)); 330 } 331 332 public static long atan(long l) { 333 return asin(div(l, sqrt(_one + mul(l, l)))); 334 } 335 336 public static long exp(long l) { 337 if(l == 0L) 338 return _one; 339 boolean flag = l < 0L; 340 l = abs(l); 341 int i = (int)(l >> _fbits); 342 long l1 = _one; 343 for(int j = 0; j < i / 4; j++) 344 l1 = mul(l1, e[4] >> (int)_flt); 345 346 if(i % 4 > 0) 347 l1 = mul(l1, e[i % 4] >> (int)_flt); 348 l &= _fmask; 349 if(l > 0L) { 350 long l2 = _one; 351 long l3 = 0L; 352 long l4 = 1L; 353 for(int k = 0; k < 16; k++) { 354 l3 += l2 / l4; 355 l2 = mul(l2, l); 356 l4 *= k + 1; 357 if(l4 > l2 || l2 <= 0L || l4 <= 0L) 358 break;

cxxiii

Page 124: Defect prevention techniques

Zarko Acimovic

359 } 360 361 l1 = mul(l1, l3); 362 } 363 if(flag) 364 l1 = div(_one, l1); 365 return l1; 366 } 367 368 public static long log(long l) { 369 if(l <= 0L) 370 throw new ArithmeticException("Bad Input"); 371 long l1 = 0L; 372 long l2 = 0L; 373 int i; 374 for(i = 0; l >= _one << 1; i++) 375 l >>= 1; 376 377 long l4 = (long)i * (long)(0xb17218 >> (int)_flt); 378 long l5 = 0L; 379 if(l < _one) 380 return -log(div(_one, l)); 381 l -= _one; 382 for(int j = 1; j < 20; j++) { 383 long l3; 384 if(l1 == 0L) 385 l3 = l; 386 else 387 l3 = mul(l1, l); 388 if(l3 == 0L) 389 break; 390 l5 += ((j % 2 != 0 ? 1L : -1L) * l3) / (long)j; 391 l1 = l3; 392 } 393 394 return l4 + l5; 395 } 396 397 public static long pow(long l, long l1) { 398 boolean flag = l1 < 0L; 399 long l2 = _one; 400 l1 = abs(l1); 401 for(int i = (int)l1 >> _fbits; i-- > 0;) 402 l2 = mul(l2, l); 403 404 if(l2 < 0L) 405 throw new ArithmeticException("Overflow"); 406 if(l != 0L) 407 l2 = mul(l2, exp(mul(log(l), l1 & _fmask))); 408 else 409 l2 = 0L;

cxxiv

Page 125: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

410 if(flag) 411 return div(_one, l2); 412 else 413 return l2; 414 } 415 416 public static long atan2(long l, long l1) { 417 long l2 = 0L; 418 if(l1 > 0L) 419 l2 = atan(div(l, l1)); 420 else 421 if(l1 < 0L) { 422 l2 = (l1 >= 0L ? PI : -PI) - atan(abs(div(l, l1))); 423 } else { 424 if(l1 == 0L && l == 0L) 425 throw new ArithmeticException("Bad Input"); 426 l2 = (l >= 0L ? PI : -PI) / 2L; 427 } 428 return l2; 429 } 430 431 static { 432 _one = 0x1000000L; 433 _pi = 0x3243f6aL; 434 e = (new long[] { 435 _one, 0x2b7e151L, 0x763992eL, 0x1415e5bfL, 0x3699205cL 436 }); 437 PI = _pi; 438 E = e[1]; 439 } 440 }

cxxv

Page 126: Defect prevention techniques

Zarko Acimovic

Outlook.java

cxxvi

All classes and interfaces must belong to a named package 10 PMD Marker

Lack of Cohesion in Methods (Henderson-Sellers) is 82% 10 Metrics Marker

Lack of Cohesion in Methods (Pairwise Field Irrelation) is 66% 10 Metrics Marker

Lack of Cohesion in Methods (Total Correlation) is 353% 10 Metrics Marker

The class 'Outlook' has a Cyclomatic Complexity of 2 (Highest = 10). 10 PMD Marker

Avoid variables with short names like mb 11 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

Unused field: Outlook.mbf 13 FindBugs

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

Use explicit scoping instead of the default package private level 15 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 16 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 17 PMD Marker

Avoid variables with short names like mb 22 PMD Marker

Avoid variables with short names like sp 22 PMD Marker

Parameter 'mb' is not assigned and could be declared final 22 PMD Marker

Parameter 'mob' is not assigned and could be declared final 22 PMD Marker

Parameter 'sp' is not assigned and could be declared final 22 PMD Marker

Avoid variables with short names like g 29 PMD Marker

Cyclomatic Complexity is 6 29 Metrics Marker

Lines of Code in Method is 33 29 Metrics Marker

Number of Statements is 21 29 Metrics Marker

Parameter 'g' is not assigned and could be declared final 29 PMD Marker

The method 'drawOutlook' has a Cyclomatic Complexity of 10. 29 PMD Marker

Avoid unnecessary comparisons in boolean expressions 30 PMD Marker

Avoid unnecessary comparisons in boolean expressions 37 PMD Marker

Avoid unnecessary comparisons in boolean expressions 37 PMD Marker

Avoid unnecessary comparisons in boolean expressions 37 PMD Marker

Avoid unnecessary comparisons in boolean expressions 42 PMD Marker

Avoid using if statements without curly braces 57 PMD Marker

Avoid using if statements without curly braces 59 PMD Marker

Local variable 'zoom' could be declared final 64 PMD Marker

The method name Outlook.ZoomIn() doesn't start with a lower case letter 64 FindBugs

Avoid using if statements without curly braces 65 PMD Marker

Local variable 'zoom' could be declared final 69 PMD Marker

Page 127: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

1 /** 2 * 3 * Outlook coordinates work MapBackground, MapObjects and SelectorPoint 4 * 5 */ 6 //import java.util.*; 7 //import java.io.*; 8 import javax.microedition.lcdui.*; 9 10 public class Outlook { 11 MapBackground mb; 12 MapObjects mob; 13 MapBackgroundFactory mbf; 14 SelectorPoint selP; 15 boolean select = false; 16 boolean route = false; 17 boolean startup = false; 18 boolean first = false; 19 Point center = new Point("44.83168","20.445","","","blanco",false); 20 boolean WPselection = false; 21 22 Outlook(MapBackground mb, MapObjects mob, SelectorPoint sp) { 23 24 this.mb = mb; 25 this.mob = mob; 26 this.selP = sp; 27 } 28 29 public void drawOutlook(Graphics g){ 30 if(startup==false) { 31 mb.setBackground(center); 32 startup = true; 33 } 34 35 mb.drawMapBackground(g); 36 37 if(first==true && mob.currentSet()==false && WPselection==false){ 38 selP.selP = new Point(mb.getNewEdge(),false); 39 first=false; 40 } 41 42 if(first==true && mob.currentSet()==true && WPselection==false){ 43 selP.selectWP(mob.getCurrentPosition().getName()); 44 mb.drawMapBackground(g); 45 first=false; 46 } 47 48 /**

cxxvii

Page 128: Defect prevention techniques

Zarko Acimovic

49 if(route==false){ 50 mob.drawMOB(g,route); 51 if(select==true) selP.drawSelP(g); 52 } else { 53 if(select==true) selP.drawSelP(g); 54 mob.drawMOB(g,route); 55 }*/ 56 57 if(select==true) selP.drawSelP(g); 58 mob.drawMOB(g,route); 59 if(select==true) selP.drawCaption(g); 60 61 } 62 63 public void ZoomIn(){ 64 boolean zoom = mb.ZoomIn(); 65 if(zoom==true) selP.Zoom(); 66 } 67 68 public void ZoomOut(){ 69 boolean zoom = mb.ZoomOut(); 70 if(zoom==true) selP.Zoom(); 71 } 72 73 /** Sets map due to Pan transformation 74 */ 75 public void setMap(char side){ 76 if(select == false) mb.setMap(side); 77 if(select == true) selP.setSelectorScreen(side); 78 } 79 80 public void setCanvasWH(int cW,int cH){ 81 mb.setCanvasWH(cW,cH); 82 } 83 84 public void setSelect(){ 85 select = true; 86 first = true; 87 //selP.resetBig(); 88 } 89 90 public void setWPselection(){ 91 WPselection = true; 92 } 93 94 public void resetSelect(){ 95 select = false; 96 WPselection = false; 97 } 98 99 public boolean getSelect(){

cxxviii

Page 129: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

100 return select; 101 } 102 103 public void setRoute(){ 104 route = true; 105 } 106 107 public void resetRoute(){ 108 route = false; 109 } 110 111 112 }

cxxix

Page 130: Defect prevention techniques

Zarko Acimovic

Point.java

cxxx

All classes and interfaces must belong to a named package 10 PMD Marker

Lack of Cohesion in Methods (Chidamber & Kemerer) is 309 10 Metrics Marker

Lack of Cohesion in Methods (Henderson-Sellers) is 91% 10 Metrics Marker

Lack of Cohesion in Methods (Pairwise Field Irrelation) is 80% 10 Metrics Marker

Lack of Cohesion in Methods (Total Correlation) is 474% 10 Metrics Marker

Number of Fields is 21 10 Metrics Marker

The class 'Point' has a Cyclomatic Complexity of 2 (Highest = 13). 10 PMD Marker

Too many fields 10 PMD Marker

Weighted Methods per Class is 60 10 Metrics Marker

Avoid variables with short names like ID 25 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 25 PMD Marker

The field name indicates a constant but its modifiers do not 25 PMD Marker

Possible unsafe assignment to a non-final static field in a constructor. 30 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 44 PMD Marker

Private field 'degLat' could be made final; it is only initialized in the declaration or constructor. 44 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 48 PMD Marker

Private field 'minLat' could be made final; it is only initialized in the declaration or constructor. 48 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 52 PMD Marker

Private field 'secLat' could be made final; it is only initialized in the declaration or constructor. 52 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 63 PMD Marker

Private field 'degLon' could be made final; it is only initialized in the declaration or constructor. 63 PMD Marker

Private field 'minLon' could be made final; it is only initialized in the declaration or constructor. 67 PMD Marker

Use explicit scoping instead of the default package private level 79 PMD Marker

Use explicit scoping instead of the default package private level 83 PMD Marker

Use explicit scoping instead of the default package private level 87 PMD Marker

Use explicit scoping instead of the default package private level 91 PMD Marker

Avoid variables with short names like x 99 PMD Marker

Avoid variables with short names like y 103 PMD Marker

Unread field: Point.dm1 108 FindBugs

Use explicit scoping instead of the default package private level 108 PMD Marker

Unread field: Point.dm2 112 FindBugs

Avoid variables with short names like rr 116 PMD Marker

Unread field: Point.rr 116 FindBugs

Lines of Code in Method is 36 123 Metrics Marker

Number of Parameters is 9 123 Metrics Marker

Number of Statements is 36 123 Metrics Marker

Parameter 'dlat' is not assigned and could be declared final 126 PMD Marker

Parameter 'mlat' is not assigned and could be declared final 126 PMD Marker

Parameter 'slat' is not assigned and could be declared final 126 PMD Marker

Parameter 'dlon' is not assigned and could be declared final 127 PMD Marker

Parameter 'mlon' is not assigned and could be declared final 127 PMD Marker

Page 131: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

Point.java

1 /** 2 * Class Point represents geographical object 3 */ 4 5 6 //import java.util.*; 7 //import java.io.*; 8 import javax.microedition.lcdui.*; 9 10 public class Point { 11 12

cxxxi

Number of Parameters is 5 162 Metrics Marker

Number of Statements is 58 162 Metrics Marker

Local variable 'latS' could be declared final 174 PMD Marker

Local variable 'lonS' could be declared final 175 PMD Marker

Avoid unnecessary comparisons in boolean expressions 200 PMD Marker

Write to static field Point.cnt from instance method new Point(long, long, String, String, boolean) 202 FindBugs

Lines of Code in Method is 29 211 Metrics Marker

Avoid unnecessary comparisons in boolean expressions 232 PMD Marker

Write to static field Point.cnt from instance method new Point(Point, boolean) 234 FindBugs

Lines of Code in Method is 45 241 Metrics Marker

Number of Parameters is 6 241 Metrics Marker

Number of Statements is 57 241 Metrics Marker

Avoid unnecessary comparisons in boolean expressions 277 PMD Marker

279 FindBugs

Local variable 'c1' could be declared final 334 PMD Marker

Local variable 'c2' could be declared final 335 PMD Marker

Lines of Code in Method is 21 474 Metrics Marker

Lines of Code in Method is 41 496 Metrics Marker

Number of Statements is 29 496 Metrics Marker

Avoid unnecessary if..then..else statements when returning a boolean 529 PMD Marker

A method should have only one exit point, and that should be the last statement in the method 531 PMD Marker

Consider simply returning the value vs storing it in local variable 'xx' 559 PMD Marker

Consider simply returning the value vs storing it in local variable 'yy' 565 PMD Marker

Cyclomatic Complexity is 12 660 Metrics Marker

Lines of Code in Method is 39 660 Metrics Marker

Number of Parameters is 5 660 Metrics Marker

Number of Statements is 76 660 Metrics Marker

The method 'drawPoint' has a Cyclomatic Complexity of 13. 660 PMD Marker

The method drawPoint() has an NPath complexity of 1032 660 PMD Marker

Avoid using if statements without curly braces 668 PMD Marker

Avoid using if statements without curly braces 671 PMD Marker

Write to static field Point.cnt from instance method new Point(String, String, String, String, String, boolean)

Page 132: Defect prevention techniques

Zarko Acimovic

13 /** type of Waypoint 14 * -2 - destination Point 15 * -1 - current Point 16 * 0 - free Point 17 * n - route Point 18 */ 19 private int typeID = 0; 20 21 22 /** Point ID 23 * 24 */ 25 private int ID = 0; 26 27 28 /** Counter 29 */ 30 private static int cnt = 0; 31 32 33 /** Float-point representation of latitude 34 */ 35 private long lat; 36 37 /** Float-point representation of longitude 38 */ 39 private long lon; 40 41 42 /** Degrees of latitude in Integer 43 */ 44 private long degLat; 45 46 /** Minutes of latitude in Integer 47 */ 48 private long minLat; 49 50 /** Seconds of latitude in Integer 51 */ 52 private long secLat; 53 54 /** Side of the world, South or North 55 */ 56 //private char sideNS; 57 58 59 60 61 /** Degrees of longitude in Integer 62 */ 63 private long degLon;

cxxxii

Page 133: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

64 65 /** Minutes of longitude in Integer 66 */ 67 private long minLon; 68 69 /** Seconds of longitude in Integer 70 */ 71 private long secLon; 72 73 /** Side of the world, West or East 74 */ 75 //private char sideWE; 76 77 /** Total number of latitude seconds 78 */ 79 long totLatSec; 80 81 /** Total number of longitude seconds 82 */ 83 long totLonSec; 84 85 /** Name of the Point 86 */ 87 String name = "default"; 88 89 /** Type of the Point 90 */ 91 String type = "default"; 92 93 /** Distance between this point and point which asks sorting 94 */ 95 private long distance; 96 97 /** x coordinate of Point on Canvas 98 */ 99 private long x = 5; 100 101 /** y coordinate of Point on Canvas 102 */ 103 private long y = 5; 104 105 106 /** Help variable 107 */ 108 long dm1=0; 109 110 /** Help variable 111 */ 112 long dm2=0; 113 114 /** Help variable

cxxxiii

Page 134: Defect prevention techniques

Zarko Acimovic

115 */ 116 long rr=1000; 117 118 /** String that describes image 119 */ 120 String imgString = "blanco"; 121 122 123 /** Regular constructor 124 * @author Zarko Acimovic 125 */ 126 Point(long dlat, long mlat, long slat, //char side1, 127 long dlon, long mlon, long slon, //char side2, 128 String n, String t,boolean setNewID){ 129 130 degLat=MathFP.toFP(dlat); 131 minLat=MathFP.toFP(mlat); 132 secLat=MathFP.toFP(slat); 133 //sideNS=side1; 134 135 136 degLon=MathFP.toFP(dlon); 137 minLon=MathFP.toFP(mlon); 138 secLon=MathFP.toFP(slon); 139 //sideWE=side2; 140 141 name=n; 142 type=t; 143 144 long sixty=MathFP.toFP("60"); 145 146 lat = MathFP.add(degLat,MathFP.div(MathFP.add(minLat,MathFP.div(secLat,sixty)),sixty)); 147 lon = MathFP.add(degLon,MathFP.div(MathFP.add(minLon,MathFP.div(secLon,sixty)),sixty)); 148 149 totLatSec = MathFP.mul(lat,MathFP.toFP("3600")); 150 totLonSec = MathFP.mul(lon,MathFP.toFP("3600")); 151 152 if(setNewID==true){ 153 ID = cnt; 154 cnt++; 155 } 156 typeID = 0; //default type 157 //System.out.println("cnt="+cnt); 158 } 159 160 161 162 Point(long totLatSec, 163 //char s1,

cxxxiv

Page 135: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

164 long totLonSec, 165 //char s2, 166 String ss1, String ss2, boolean setNewID){ 167 lat = MathFP.div(totLatSec, MathFP.toFP("3600")); 168 lon = MathFP.div(totLonSec, MathFP.toFP("3600")); 169 this.name = ss1; 170 this.type = ss2; 171 //this.sideNS = s1; 172 //this.sideWE = s2; 173 174 String latS = MathFP.toString(lat); 175 String lonS = MathFP.toString(lon); 176 177 this.degLat = MathFP.getWholePart(latS); 178 long temp = MathFP.sub(this.lat,this.degLat); 179 temp = MathFP.mul(temp,MathFP.toFP("60")); 180 this.minLat = MathFP.getWholePart(MathFP.toString(temp)); 181 182 temp = MathFP.sub(this.lat,this.degLat); 183 temp = MathFP.mul(temp,MathFP.toFP("60")); 184 temp = MathFP.sub(temp,minLat); 185 this.secLat = MathFP.mul(temp,MathFP.toFP("60")); 186 187 this.degLon = MathFP.getWholePart(lonS); 188 temp = MathFP.sub(this.lon,this.degLon); 189 temp = MathFP.mul(temp,MathFP.toFP("60")); 190 this.minLon = MathFP.getWholePart(MathFP.toString(temp)); 191 192 temp = MathFP.sub(this.lon,this.degLon); 193 temp = MathFP.mul(temp,MathFP.toFP("60")); 194 temp = MathFP.sub(temp,minLon); 195 this.secLon = MathFP.mul(temp,MathFP.toFP("60")); 196 197 this.totLatSec = totLatSec; 198 this.totLonSec = totLonSec; 199 200 if(setNewID==true){ 201 ID = cnt; 202 cnt++; 203 } 204 typeID = 0; //default type 205 //System.out.println("cnt="+cnt); 206 207 } 208 209 210 211 Point(Point wp, boolean setNewID) { 212 degLat=wp.degLat; 213 minLat=wp.minLat; 214 secLat=wp.secLat;

cxxxv

Page 136: Defect prevention techniques

Zarko Acimovic

215 //sideNS=wp.sideNS; 216 217 218 degLon=wp.degLon; 219 minLon=wp.minLon; 220 secLon=wp.secLon; 221 //sideWE=wp.sideWE; 222 223 name=wp.name; 224 type=wp.type; 225 226 this.lat = wp.lat; 227 this.lon = wp.lon; 228 this.totLatSec = wp.totLatSec; 229 this.totLonSec = wp.totLonSec; 230 231 232 if (setNewID==true){ 233 ID = cnt; 234 cnt++; 235 } 236 typeID = 0; //default type 237 //System.out.println("cnt="+cnt); 238 imgString = wp.getImage(); 239 } 240 241 Point (String lat, 242 //char sideNS, 243 String lon, 244 //char sideWE, 245 String name, String type, String img, boolean setNewID){ 246 //this.sideNS = sideNS; 247 //this.sideWE = sideWE; 248 this.name = name; 249 this.type = type; 250 this.lat = MathFP.toFP(lat); 251 this.lon = MathFP.toFP(lon); 252 253 this.degLat = MathFP.getWholePart(lat); 254 long temp = MathFP.sub(this.lat,this.degLat); 255 temp = MathFP.mul(temp,MathFP.toFP("60")); 256 this.minLat = MathFP.getWholePart(MathFP.toString(temp)); 257 258 temp = MathFP.sub(this.lat,this.degLat); 259 temp = MathFP.mul(temp,MathFP.toFP("60")); 260 temp = MathFP.sub(temp,minLat); 261 this.secLat = MathFP.mul(temp,MathFP.toFP("60")); 262 263 this.degLon = MathFP.getWholePart(lon); 264 temp = MathFP.sub(this.lon,this.degLon); 265 temp = MathFP.mul(temp,MathFP.toFP("60"));

cxxxvi

Page 137: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

266 this.minLon = MathFP.getWholePart(MathFP.toString(temp)); 267 268 temp = MathFP.sub(this.lon,this.degLon); 269 temp = MathFP.mul(temp,MathFP.toFP("60")); 270 temp = MathFP.sub(temp,minLon); 271 this.secLon = MathFP.mul(temp,MathFP.toFP("60")); 272 273 this.totLatSec = MathFP.mul(this.lat,MathFP.toFP("3600")); 274 this.totLonSec = MathFP.mul(this.lon,MathFP.toFP("3600")); 275 276 277 if (setNewID==true) { 278 ID = cnt; 279 cnt++; 280 } 281 typeID = 0; //default type 282 //System.out.println("cnt="+cnt); 283 imgString = img; 284 285 } 286 287 288 289 /** 290 Point(String lat, String lon, String name, String type, String image, boolean setNewID){ 291 this.name = name; 292 this.type = type; 293 this.lat = MathFP.toFP(lat); 294 this.lon = MathFP.toFP(lon); 295 296 this.degLat = MathFP.getWholePart(lat); 297 long temp = MathFP.sub(this.lat,this.degLat); 298 temp = MathFP.mul(temp,MathFP.toFP("60")); 299 this.minLat = MathFP.getWholePart(MathFP.toString(temp)); 300 301 temp = MathFP.sub(this.lat,this.degLat); 302 temp = MathFP.mul(temp,MathFP.toFP("60")); 303 temp = MathFP.sub(temp,minLat); 304 this.secLat = MathFP.mul(temp,MathFP.toFP("60")); 305 306 this.degLon = MathFP.getWholePart(lon); 307 temp = MathFP.sub(this.lon,this.degLon); 308 temp = MathFP.mul(temp,MathFP.toFP("60")); 309 this.minLon = MathFP.getWholePart(MathFP.toString(temp)); 310 311 temp = MathFP.sub(this.lon,this.degLon); 312 temp = MathFP.mul(temp,MathFP.toFP("60")); 313 temp = MathFP.sub(temp,minLon); 314 this.secLon = MathFP.mul(temp,MathFP.toFP("60")); 315

cxxxvii

Page 138: Defect prevention techniques

Zarko Acimovic

316 this.totLatSec = MathFP.mul(this.lat,MathFP.toFP("3600")); 317 this.totLonSec = MathFP.mul(this.lon,MathFP.toFP("3600")); 318 319 320 if (setNewID==true) { 321 ID = cnt; 322 cnt++; 323 } 324 typeID = 0; //default type 325 326 }*/ 327 328 /** Calculates distance between two Points; 329 * 330 * @version advanced 331 * @return long 332 */ 333 public long measureDistance(Point wp){ 334 Coordinates c1 = new Coordinates(this.lat,this.lon); 335 Coordinates c2 = new Coordinates(wp.lat, wp.lon); 336 return MathFP.toLong(c1.distance(c2)); 337 } 338 339 /** Sets distance 340 */ 341 public void setDistance (long dist){ 342 distance = dist; 343 } 344 345 /** Gets distance 346 * @return long 347 */ 348 public long getDistance (){ 349 return distance; 350 } 351 352 /** Returns type of Point 353 * @return String 354 */ 355 public String getType() { return type; } 356 357 /** Sets type of Point 358 * @return String 359 */ 360 public void setType(String type) { this.type = type; } 361 362 /** Returns name of Point 363 * @return String 364 */ 365 public String getName() { return name; } 366

cxxxviii

Page 139: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

367 /** Sets type of Point 368 * @return String 369 */ 370 public void setName(String name) { this.name = name; } 371 372 /** Returns side of the world as String 373 * @return String 374 * 375 */ 376 //public char getNS(){ 377 // return sideNS; 378 //} 379 380 /** Returns side of the world as String 381 * @return String 382 * 383 */ 384 //public char getWE(){ 385 // return sideWE; 386 //} 387 388 /** Returns degrees of latitiude 389 * 390 * @author Zarko Acimovic 391 * @version initial 392 */ 393 public long getDLat(){ 394 return degLat; 395 } 396 397 /** Returns minutes of latitiude 398 * 399 * @author Zarko Acimovic 400 * @version initial 401 */ 402 public long getMLat(){ 403 return minLat; 404 } 405 406 /** Returns seconds of latitiude 407 * 408 * @author Zarko Acimovic 409 * @version initial 410 */ 411 public long getSLat(){ 412 return secLat; 413 } 414 415 /** Returns degrees of longitude 416 * 417 * @author Zarko Acimovic

cxxxix

Page 140: Defect prevention techniques

Zarko Acimovic

418 * @version initial 419 */ 420 public long getDLon(){ 421 return degLon; 422 } 423 424 /** Returns minutes of longitude 425 * 426 * @author Zarko Acimovic 427 * @version initial 428 */ 429 public long getMLon(){ 430 return minLon; 431 } 432 433 /** Returns seconds of longitude 434 * 435 * @author Zarko Acimovic 436 * @version initial 437 * @return int 438 */ 439 public long getSLon(){ 440 return secLon; 441 } 442 443 /** Returns latitude as floating point 444 * 445 * @author Zarko Acimovic 446 * @version initial 447 * @return Float-Point 448 */ 449 public long getLat(){ 450 return lat; 451 } 452 453 /** Returns longitude as floating point 454 * 455 * @author Zarko Acimovic 456 * @version initial 457 * @return Float-Point 458 */ 459 public long getLon(){ 460 return lon; 461 } 462 463 /** Prints Point 464 * @author Zarko Acimovic 465 * @version initial 466 * @return String 467 */ 468 public String toString(){

cxl

Page 141: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

469 return "ID="+getID()+"\n"+"Longitude: "+MathFP.toString(this.lon)+" "+MathFP.toString(this.degLon)+","+MathFP.toString(this.minLon)+","+MathFP.toString(this.secLon)+","+" x="+this.getX()+ 470 "\nLatitude: "+MathFP.toString(this.lat)+" "+MathFP.toString(this.degLat)+","+MathFP.toString(this.minLat)+","+MathFP.toString(this.secLat)+","+" y="+this.getY()+" "+this.getName()+"\n" 471 +this.getImage(); 472 } 473 474 /** Sets x and y coordinates on Canvas relative to wp 475 * Usually wp is newEdge 476 * @author Zarko Acimovic 477 * @version initial 478 */ 479 public void setXY (Point wp, long pixLon, long pixLat){ 480 //System.out.println("----this------------------"+this); 481 //System.out.println("-------newEdge---------------"+wp); 482 ///System.out.println("this.getLat()="+MathFP.toString(this.getLat())); 483 //System.out.println("this.getLon()="+MathFP.toString(this.getLon())); 484 ///System.out.println("wp.getLat()="+MathFP.toString(wp.getLat())); 485 ///System.out.println("wp.getLon()="+MathFP.toString(wp.getLon())); 486 //System.out.println("pixLat="+MathFP.toString(pixLat)); 487 ///System.out.println("pixLon="+MathFP.toString(pixLon)); 488 489 y = MathFP.div(MathFP.mul(MathFP.sub(wp.getLat(),this.getLat()),MathFP.toFP("3600")),pixLat); 490 y = MathFP.toLong(y); 491 492 x = MathFP.div(MathFP.mul(MathFP.sub(this.getLon(),wp.getLon()),MathFP.toFP("3600")),pixLon); 493 x = MathFP.toLong(x); 494 } 495 496 /** Checks if this Point is beetwen wp1 and wp2 497 * 498 * @version initial 499 * @return boolean 500 */ 501 public boolean check(Point wp1, Point wp2){ 502 503 long lim1Lat = wp1.getLat(); 504 long lim1Lon = wp1.getLon(); 505 long lim2Lat = wp2.getLat(); 506 long lim2Lon = wp2.getLon();

cxli

Page 142: Defect prevention techniques

Zarko Acimovic

507 508 long bigLat; 509 long miniLat; 510 long bigLon; 511 long miniLon; 512 513 if (lim1Lat>lim2Lat){ 514 bigLat=lim1Lat; 515 miniLat=lim2Lat; 516 } else { 517 bigLat=lim2Lat; 518 miniLat=lim1Lat; 519 } 520 521 if (lim1Lon>lim2Lon){ 522 bigLon=lim1Lon; 523 miniLon=lim2Lon; 524 } else { 525 bigLon=lim2Lon; 526 miniLon=lim1Lon; 527 } 528 529 if (miniLat<this.getLat() && this.getLat()<bigLat && 530 miniLon<this.getLon() && this.getLon()<bigLon){ 531 return true; 532 } else { 533 return false; 534 } 535 536 } 537 538 539 540 /** Returns x-position of Point on Canvas 541 * 542 * @author Zarko Acimovic 543 * @version initial 544 * @return long 545 */ 546 public long getX() {return x; } 547 548 /** Returns y-position of Point on Canvas 549 * 550 * @author Zarko Acimovic 551 * @version initial 552 * @return long 553 */ 554 public long getY() {return y; } 555 556 public int getXX() { 557 Long l = new Long(x);

cxlii

Page 143: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

558 int xx = Integer.parseInt(l.toString()); 559 return xx; 560 } 561 562 public int getYY() { 563 Long l = new Long(y); 564 int yy = Integer.parseInt(l.toString()); 565 return yy; 566 } 567 568 /** Adds inc on x 569 */ 570 public void addX(long inc ){ 571 this.x+=inc; 572 } 573 574 /** Substracts dec from x 575 */ 576 public void subX(long dec){ 577 this.x-=dec; 578 } 579 580 /** Adds inc on y 581 */ 582 public void addY(long inc){ 583 this.y+=inc; 584 } 585 586 /** Substracts dec from y 587 */ 588 public void subY(long dec){ 589 this.y-=dec; 590 } 591 592 593 /** Returns total number of lat-seconds for Point 594 * 595 * @author Zarko Acimovic 596 * @version initial 597 * @return long 598 */ 599 public long getLatSec() { 600 return totLatSec; 601 } 602 603 /** Returns total number of lon-seconds for Point 604 * 605 * @author Zarko Acimovic 606 * @version initial 607 * @return long 608 */

cxliii

Page 144: Defect prevention techniques

Zarko Acimovic

609 public long getLonSec() { 610 return totLonSec; 611 } 612 613 /** Sets x-position of Point on screen 614 */ 615 public void setX(long x){ 616 this.x=x; 617 } 618 619 /** Sets y-position of Point on screen 620 */ 621 public void setY(long y){ 622 this.y=y; 623 } 624 625 /** Sets ID of Point 626 * 0 - simple Point 627 * 1 - current Point 628 * 2 - destination Point 629 */ 630 public void setTypeID(int i){ 631 typeID = i; 632 } 633 634 /** Returns ID of Point 635 * 0 - simple Point 636 * 1 - current Point 637 * 2 - destination Point 638 */ 639 public int getTypeID(){ 640 return typeID; 641 } 642 643 public int getID(){ 644 return ID; 645 } 646 647 648 /** String that represents image 649 */ 650 public void setImage(String s){ 651 imgString = s; 652 } 653 654 /** Returns name of the image 655 */ 656 public String getImage(){ 657 return imgString; 658 } 659

cxliv

Page 145: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

660 public void drawPoint(Graphics g, Point newEdge, long pixLat, long pixLon, long zoomLv){ 661 662 this.setXY(newEdge,pixLon,pixLat); 663 if(this.getImage().equals("route")){ 664 g.fillRect(this.getXX()-3,this.getYY()-3,6,6); 665 } 666 if(this.getImage().equals("blanco")){ 667 g.fillRect(this.getXX()-3,this.getYY()-3,6,6); 668 if (this.getName().equals("current")) 669 g.drawString(this.getName(),this.getXX()-25,this.getYY()+5,0); 670 671 if (this.getName().equals("dest")) 672 g.drawString(this.getName(),this.getXX()-18,this.getYY()+11,0); 673 674 if (this.getName().equals("GPS.txt")) 675 g.drawString(this.getName(),this.getXX()-18,this.getYY()+11,0); 676 677 if (this.getName().equals("Mika.txt")) 678 g.drawString(this.getName(),this.getXX()-18,this.getYY()+11,0); 679 680 if (this.getName().equals("GPS")) 681 g.drawString(this.getName(),this.getXX()-18,this.getYY()+11,0); 682 683 if (this.getName().equals("Mika")) 684 g.drawString(this.getName(),this.getXX()-18,this.getYY()+11,0); 685 686 if (this.getName().equals("Str8")) 687 g.drawString(this.getName(),this.getXX()-18,this.getYY()+11,0); 688 } 689 690 if(!this.getImage().equals("blanco") && !this.getImage().equals("route")){ 691 Image img = null; 692 try{ 693 img = Image.createImage(this.getImage()); 694 }catch(Exception e){} 695 g.drawImage(img,this.getXX()-3,this.getYY()-3,0); 696 //g.drawString(this.getName(),this.getXX()-15,this.getYY()+11,0); 697 } 698 } 699 700 public void setLat(String s){

cxlv

Page 146: Defect prevention techniques

Zarko Acimovic

701 lat = MathFP.toFP(s); 702 } 703 704 public void setLon(String s){ 705 lon = MathFP.toFP(s); 706 } 707 708 }

cxlvi

Page 147: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

PVector.java

cxlvii

All classes and interfaces must belong to a named package 11 PMD Marker

Lack of Cohesion in Methods (Henderson-Sellers) is 75% 11 Metrics Marker

Lack of Cohesion in Methods (Pairwise Field Irrelation) is 100% 11 Metrics Marker

Lack of Cohesion in Methods (Total Correlation) is 114% 11 Metrics Marker

Weighted Methods per Class is 45 11 Metrics Marker

Avoid variables with short names like ID 17 PMD Marker

The field name indicates a constant but its modifiers do not 17 PMD Marker

Possible unsafe assignment to a non-final static field in a constructor. 18 PMD Marker

Use explicit scoping instead of the default package private level 22 PMD Marker

Parameter 'name' is not assigned and could be declared final 26 PMD Marker

Parameter 'route' is not assigned and could be declared final 26 PMD Marker

Avoid unnecessary comparisons in boolean expressions 29 PMD Marker

Write to static field PVector.cnt from instance method new PVector(String, boolean) 31 FindBugs

Avoid using implementation types like 'Vector'; use the interface instead 37 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 37 PMD Marker

Avoid variables with short names like v 37 PMD Marker

Consider replacing this Vector with the newer java.util.List 37 PMD Marker

Parameter 'route' is not assigned and could be declared final 37 PMD Marker

Parameter 'v' is not assigned and could be declared final 37 PMD Marker

Avoid unnecessary comparisons in boolean expressions 40 PMD Marker

Write to static field PVector.cnt from instance method new PVector(Vector, boolean) 42 FindBugs

Lines of Code in Method is 25 53 Metrics Marker

Number of Statements is 23 53 Metrics Marker

Avoid using implementation types like 'Vector'; use the interface instead 60 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 60 PMD Marker

Avoid variables with short names like wp 60 PMD Marker

Consider replacing this Vector with the newer java.util.List 60 PMD Marker

Parameter 'wp' is not assigned and could be declared final 60 PMD Marker

Local variable 'size' could be declared final 61 PMD Marker

Local variable 'whs' could be declared final 64 PMD Marker

Avoid variables with short names like ht 68 PMD Marker

Consider replacing this Hashtable with the newer java.util.Map 68 PMD Marker

Local variable 'ht' could be declared final 68 PMD Marker

Avoid instantiating new objects inside loops 70 PMD Marker

Avoid variables with short names like hp 72 PMD Marker

Local variable 'hp' could be declared final 72 PMD Marker

Consider replacing this Vector with the newer java.util.List 74 PMD Marker

Local variable 'sorted' could be declared final 74 PMD Marker

Use ArrayList instead of Vector 74 PMD Marker

Avoid instantiating new objects inside loops 75 PMD Marker

Page 148: Defect prevention techniques

Zarko Acimovic

PVector.java

cxlviii

Dead store to temp1 in PVector.sortDescending(Point) 107 FindBugs

The local variable temp1 is never read 107 Java Problem

Use ArrayList instead of Vector 107 PMD Marker

Use ArrayList instead of Vector 108 PMD Marker

Dead store to temp1 in PVector.sortDescending(Point) 109 FindBugs

Avoid using for statements without curly braces 110 PMD Marker

Cyclomatic Complexity is 5 114 Metrics Marker

Lines of Code in Method is 26 114 Metrics Marker

Number of Statements is 26 114 Metrics Marker

Avoid using implementation types like 'Vector'; use the interface instead 120 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 120 PMD Marker

Consider replacing this Hashtable with the newer java.util.Map 127 PMD Marker

Avoid instantiating new objects inside loops 129 PMD Marker

Use ArrayList instead of Vector 133 PMD Marker

Avoid instantiating new objects inside loops 135 PMD Marker

Avoid using if statements without curly braces 136 PMD Marker

Prefer StringBuffer over += for concatenating strings 150 PMD Marker

PVector.toString() concatenates strings using + in a loop 150 FindBugs

Cyclomatic Complexity is 5 155 Metrics Marker

Lines of Code in Method is 46 155 Metrics Marker

Number of Statements is 35 155 Metrics Marker

Avoid using implementation types like 'Vector'; use the interface instead 162 PMD Marker

Avoid using implementation types like 'Vector'; use the interface instead 162 PMD Marker

Use ArrayList instead of Vector 163 PMD Marker

Lines of Code in Method is 30 212 Metrics Marker

Number of Statements is 28 212 Metrics Marker

Avoid instantiating new objects inside loops 228 PMD Marker

Substitute calls to size() == 0 (or size() != 0) with calls to isEmpty() 232 PMD Marker

A method should have only one exit point, and that should be the last statement in the method 233 PMD Marker

Document empty method 248 PMD Marker

A getX() method which returns a boolean should be named isX() 289 PMD Marker

Cyclomatic Complexity is 6 293 Metrics Marker

Lines of Code in Method is 28 293 Metrics Marker

Number of Levels is 5 293 Metrics Marker

Page 149: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

1 /** 2 * 3 * PVector enables drawing and sorting of points by name and distance 4 */ 5 6 7 import java.util.*; 8 //import java.io.*; 9 import javax.microedition.lcdui.*; 10 11 public class PVector extends Vector { 12 13 /** ID of WP Vector 14 * 0 - simple Vector 15 * 1 - route 16 */ 17 private int ID = 0; 18 private static int cnt = 0; 19 20 private String name =""; 21 22 boolean visible = false; 23 24 25 26 PVector(String name,boolean route){ 27 super(); 28 29 if (route==true) { 30 this.name = name; 31 cnt++; 32 ID = cnt; 33 } else { 34 ID = 0; 35 } 36 } 37 PVector(Vector v, boolean route){ 38 super(); 39 40 if (route==true) { 41 ID = cnt; 42 cnt++; 43 } else { 44 ID = 0; 45 } 46 47 for (int i=0; i<v.size(); i++){ 48 this.addElement(v.elementAt(i)); 49 } 50 }

cxlix

Page 150: Defect prevention techniques

Zarko Acimovic

51 52 53 /** Returns vector of Points sorted by distance 54 * from Point wp in ascending order 55 * 56 * @version initial 57 * @return Vector 58 */ 59 60 public Vector sortAscending(Point wp){ 61 int size = this.size(); 62 long[] distances = new long [size]; 63 for (int i=0; i<size; i++) { 64 Point whs = (Point)this.elementAt(i); //from warehouse 65 distances[i]=whs.measureDistance(wp); 66 whs.setDistance(distances[i]); 67 } 68 Hashtable ht = new Hashtable(); 69 for (int i=0; i<size; i++){ 70 ht.put(new Long(distances[i]),this.elementAt(i)); 71 } 72 HeapSorter hp = new HeapSorter(); 73 hp.heapsort(distances); 74 Vector sorted = new Vector(); 75 for (int i=0;i<size;i++) sorted.addElement(ht.get(new Long(distances[i]))); 76 return sorted; 77 } 78 79 public String[] sortByName(){ 80 //System.out.println("wwwwww"); 81 //int size = this.size(); 82 //long[] firstChars = new long[size]; 83 //Hashtable ht = new Hashtable(); 84 String names[] = new String[this.size()]; 85 for(int i=0; i<this.size(); i++){ 86 Point whs = (Point) this.elementAt(i); 87 //firstChars[i] = (long) whs.getName().charAt(0); 88 //ht.put(new Long(firstChars[i]),this.elementAt(i)); 89 names[i]=whs.getName(); 90 } 91 HeapSorter hp = new HeapSorter(); 92 hp.heapsort(names); 93 //Vector sorted = new Vector(); 94 //for (int i=0;i<size;i++) sorted.addElement(ht.get(new Long(firstChars[i]))); 95 //System.out.println("wwwwww\n"+sorted); 96 return names; 97 }

cl

Page 151: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

98 99 /** Returns vector of Points sorted by distance 100 * from WayPint wp in descending order 101 * 102 * @version initial 103 * @return Vector 104 */ 105 public Vector sortDescending(Point wp){ 106 int size = this.size(); 107 Vector temp1 = new Vector(); 108 Vector temp2 = new Vector(); 109 temp1 = this.sortAscending(wp); 110 for (int i=0; i<size;i++ ) temp2.addElement(temp2.elementAt(size-i)); 111 return temp2; 112 } 113 114 /** Return vector of specific Points of type 'type' 115 * sorted by distance in ascending order from Point wp 116 * 117 * @version initial 118 * @return Vector 119 */ 120 public Vector sortAscending (Point wp, String type){ 121 int size = this.size(); 122 long[] distances = new long [size]; 123 for (int i=0; i<size; i++){ 124 Point whs = (Point)this.elementAt(i); //from warehouse 125 distances[i]=wp.measureDistance(whs); 126 } 127 Hashtable ht = new Hashtable(); 128 for (int i=0; i<size; i++){ 129 ht.put(new Long(distances[i]),this.elementAt(i)); 130 } 131 HeapSorter hp = new HeapSorter(); 132 hp.heapsort(distances); 133 Vector sorted = new Vector(); 134 for (int i=0;i<size;i++) { 135 Point wpnt = (Point)ht.get(new Long(distances[i])); 136 if (wp.getType().equals(type)) sorted.addElement(wpnt); 137 } 138 return sorted; 139 } 140 141 /** Prints array of Points 142 * @version initial 143 * @return String 144 */ 145 public String toString(){

cli

Page 152: Defect prevention techniques

Zarko Acimovic

146 String str=""; 147 int size = this.size(); 148 for (int i=0; i<size; i++){ 149 Point wp =(Point)this.elementAt(i); 150 str += wp.toString(); 151 } 152 return str; 153 } 154 155 /**Returns all Points in rectangle 156 * defined by wp1 and wp2 as points 157 * of diagonal 158 * 159 * @version initial 160 * @return Vector 161 */ 162 public Vector getPoints(Point wp1, Point wp2){ 163 Vector v = new Vector(); 164 165 long lim1Lat = wp1.getLat(); 166 long lim1Lon = wp1.getLon(); 167 long lim2Lat = wp2.getLat(); 168 long lim2Lon = wp2.getLon(); 169 170 long bigLat; 171 long miniLat; 172 long bigLon; 173 long miniLon; 174 175 if (lim1Lat>lim2Lat){ 176 bigLat=lim1Lat; 177 miniLat=lim2Lat; 178 } else { 179 bigLat=lim2Lat; 180 miniLat=lim1Lat; 181 } 182 183 if (lim1Lon>lim2Lon){ 184 bigLon=lim1Lon; 185 miniLon=lim2Lon; 186 } else { 187 bigLon=lim2Lon; 188 miniLon=lim1Lon; 189 } 190 191 for (int i=0; i<this.size();i++){ 192 Point wp = (Point)this.elementAt(i); 193 if (miniLat<wp.getLat() && wp.getLat()<bigLat && 194 miniLon<wp.getLon() && wp.getLon()<bigLon){ 195 v.addElement(wp); 196 }

clii

Page 153: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

197 } 198 //System.out.println("Vektor je\n"+v); 199 return v; 200 } 201 202 /** Merges two vectors 203 * 204 * @version initial 205 */ 206 public void mergeWith(Vector v){ 207 for (int i=0; i<v.size(); i++ ){ 208 this.addElement(v.elementAt(i)); 209 } 210 } 211 212 /** Deletes Point 213 * 214 * @author Zarko Acimovic 215 * @version initial 216 */ 217 public int deleteWP1(Point wp, int pixLat, int pixLon){ 218 //System.out.println("Unutar DELETE"); 219 //System.out.println(this.size()); 220 Vector toDelete = new Vector(); 221 long pixLat1 = MathFP.toLong(pixLat); 222 long pixLon1 = MathFP.toLong(pixLon); 223 224 for (int i=0; i<this.size(); i++){ 225 Point wp2 = (Point)this.elementAt(i); 226 if ( Math.abs(wp2.getLatSec()-wp.getLatSec())<5*pixLat1 && 227 Math.abs(wp2.getLonSec()-wp.getLonSec())<5*pixLon1 ){ 228 toDelete.addElement(new Integer(i)); 229 } 230 } 231 232 if(toDelete.size()>1 || toDelete.size()==0) { 233 return -1; 234 } 235 else { 236 Integer k = (Integer)toDelete.elementAt(0); 237 int c = k.intValue(); 238 this.removeElementAt(c); 239 return c; 240 } 241 } 242 243 /** Edits Point 244 * 245 * @author Zarko Acimovic

cliii

Page 154: Defect prevention techniques

Zarko Acimovic

246 * @version not yet implemented 247 */ 248 public void editWP(Point wp){ 249 } 250 251 252 /** Sets ID of WPVector 253 * 0 - simple WPVector 254 * n - route 255 * 256 */ 257 public void setID(int i){ 258 ID = i; 259 } 260 261 /** Returns ID of WPVector 262 * 0 - simple WPVector 263 * 1 - route 264 */ 265 public int getID(){ 266 return ID; 267 } 268 269 /** Returns name WPVector 270 */ 271 public String getName(){ 272 return name; 273 } 274 275 /** Returns name WPVector 276 */ 277 public void setName(String s){ 278 name = s; 279 } 280 281 public void setVisible(){ 282 visible = true; 283 } 284 285 public void resetVisible(){ 286 visible = false; 287 } 288 289 public boolean getVisible(){ 290 return visible; 291 } 292 293 public void drawVector(Graphics g, boolean route, Point newEdge, long pixLon, long pixLat, long zoomL){ 294 /////System.out.println("route="+route); 295 /////System.out.println("routeVisible="+this.getVisible());

cliv

Page 155: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

296 if(route==true){ 297 if(this.getVisible()==true){ 298 if(this.size()==1){ 299 Point wp1 = (Point) this.elementAt(0); 300 wp1.drawPoint(g,newEdge,pixLat,pixLon,zoomL); 301 } else { 302 for(int j=0; j<this.size()-1; j++){ 303 Point wp1 = (Point) this.elementAt(j); 304 Point wp2 = (Point) this.elementAt(j+1); 305 //wp1.setXY(newEdge,pixLon,pixLat); 306 //wp2.setXY(newEdge,pixLon,pixLat); 307 wp1.drawPoint(g,newEdge,pixLat,pixLon,zoomL); 308 wp2.drawPoint(g,newEdge,pixLat,pixLon,zoomL); 309 g.drawLine(wp1.getXX(),wp1.getYY(),wp2.getXX(),wp2.getYY()); 310 } 311 } 312 } 313 } else { 314 for(int i=0; i<this.size(); i++){ 315 Point wp = (Point) this.elementAt(i); 316 wp.drawPoint(g,newEdge,pixLat,pixLon,zoomL); 317 } 318 } 319 320 } 321 322 323 };

clv

Page 156: Defect prevention techniques

Zarko Acimovic

SelectorPoint.java

clvi

All classes and interfaces must belong to a named package 8 PMD Marker

Lack of Cohesion in Methods (Henderson-Sellers) is 75% 8 Metrics Marker

Lack of Cohesion in Methods (Pairwise Field Irrelation) is 78% 8 Metrics Marker

Lack of Cohesion in Methods (Total Correlation) is 333% 8 Metrics Marker

The class 'SelectorPoint' has a Cyclomatic Complexity of 4 (Highest = 19). 8 PMD Marker

Weighted Methods per Class is 72 8 Metrics Marker

Avoid variables with short names like mb 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

Found non-transient, non-static member. Please mark as transient or provide accessors. 10 PMD Marker

Use explicit scoping instead of the default package private level 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

Avoid variables with short names like m 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 n 13 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

Avoid variables with short names like s 14 PMD Marker

Avoid variables with short names like mb 18 PMD Marker

Parameter 'mb' is not assigned and could be declared final 18 PMD Marker

Parameter 'mob' is not assigned and could be declared final 18 PMD Marker

Cyclomatic Complexity is 15 25 Metrics Marker

Lines of Code in Method is 75 25 Metrics Marker

Number of Statements is 82 25 Metrics Marker

Parameter 's' is not assigned and could be declared final 27 PMD Marker

The method 'setSelectorScreen' has a Cyclomatic Complexity of 19. 27 PMD Marker

The method setSelectorScreen() has an NPath complexity of 11025 27 PMD Marker

Avoid using if statements without curly braces 31 PMD Marker

Avoid using if statements without curly braces 49 PMD Marker

Avoid using if statements without curly braces 61 PMD Marker

Avoid using if statements without curly braces 74 PMD Marker

Local variable 'WP' could be declared final 87 PMD Marker

Avoid unnecessary comparisons in boolean expressions 89 PMD Marker

The String literal "selector" appears 4 times in this file; the first occurrence is on 89 89 PMD Marker

Avoid unnecessary comparisons in boolean expressions 93 PMD Marker

Feature Envy is 5 103 Metrics Marker

Lines of Code in Method is 22 103 Metrics Marker

Parameter 'edge' is not assigned and could be declared final 108 PMD Marker

Page 157: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

SelectorPoint.java

clvii

Cyclomatic Complexity is 15 169 Metrics Marker

Lines of Code in Method is 73 169 Metrics Marker

Number of Levels is 5 169 Metrics Marker

Number of Statements is 89 169 Metrics Marker

The method 'selectWP' has a Cyclomatic Complexity of 18. 172 PMD Marker

The method selectWP() has an NPath complexity of 7290 172 PMD Marker

Avoid unused local variables such as 'idS'. 177 PMD Marker

The local variable idS is never read 177 Java Problem

Avoid using if statements without curly braces 183 PMD Marker

Consider replacing this Vector with the newer java.util.List 214 PMD Marker

Avoid unnecessary comparisons in boolean expressions 237 PMD Marker

Avoid unnecessary comparisons in boolean expressions 238 PMD Marker

Cyclomatic Complexity is 13 243 Metrics Marker

Lines of Code in Method is 73 243 Metrics Marker

Number of Statements is 99 243 Metrics Marker

The method 'deleteWP' has a Cyclomatic Complexity of 17. 251 PMD Marker

The method deleteWP() has an NPath complexity of 5760 251 PMD Marker

Consider replacing this Vector with the newer java.util.List 256 PMD Marker

Use ArrayList instead of Vector 256 PMD Marker

Avoid instantiating new objects inside loops 261 PMD Marker

Consider replacing this Vector with the newer java.util.List 265 PMD Marker

Use ArrayList instead of Vector 265 PMD Marker

Consider replacing this Vector with the newer java.util.List 266 PMD Marker

Avoid instantiating new objects inside loops 272 PMD Marker

Avoid unused local variables such as 'drt'. 277 PMD Marker

The local variable drt is never read 277 Java Problem

Substitute calls to size() == 0 (or size() != 0) with calls to isEmpty() 278 PMD Marker

Cyclomatic Complexity is 5 318 Metrics Marker

Feature Envy is 6 318 Metrics Marker

Lines of Code in Method is 26 318 Metrics Marker

Number of Statements is 54 318 Metrics Marker

The method name SelectorPoint.Zoom() doesn't start with a lower case letter 321 FindBugs

Lines of Code in Method is 95 346 Metrics Marker

Number of Statements is 22 346 Metrics Marker

Avoid unused local variables such as 'length'. 414 PMD Marker

The local variable length is never read 414 Java Problem

Page 158: Defect prevention techniques

Zarko Acimovic

1 /** 2 * SelectorPoint controls selection and identification of geographical object 3 */ 4 import java.util.*; 5 //import java.io.*; 6 import javax.microedition.lcdui.*; 7 8 public class SelectorPoint{ 9 MapBackground mb; 10 MapObjects mob; 11 Point selP; 12 int m = 255; 13 int n = 200; 14 int s = 0; 15 boolean colorSet=false; 16 boolean big = false; 17 18 SelectorPoint(MapBackground mb, MapObjects mob){ 19 20 this.selP = mob.getCurrentPosition(); 21 this.mb = mb; 22 this.mob = mob; 23 } 24 25 /** Sets selector point on Screen due to user's left/right , up/down commands 26 */ 27 public void setSelectorScreen(char s){ 28 29 30 if(s=='r'){ 31 if (selP.getX()>0 && selP.getX()<mb.getCanvasWidth()) selP.addX(5); 32 if (selP.getX()>mb.getCanvasWidth()-5) { 33 // calculation of (deg,min,sec) for Selector before panning 34 //dakle ja pre panovanja izracunam svetske koordinate selektora, 35 //da bi znao gde je on stvarno, pa kad panujem mapu (a samim 36 //tim i promenim njen newEdge onda odredjujem i relativni polozaj 37 //selektorske tacke u odnosu na taj newEdge (jasno je da pri panovanju mape 38 //nije doslo do promene svetskih koordinata selektora) 39 this.setSelectorWorld(mb.getNewEdge(), mb.getPixLon(),mb.getPixLat()); 40 //Paning

clviii

Page 159: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

41 mb.setMap(s); 42 mob.setDrawablePoints(); 43 //calculation of new Selector position on panned map 44 selP.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 45 46 } 47 } 48 if(s=='l'){ 49 if (selP.getX()>6) selP.subX(5); 50 if (selP.getX()<=6) { 51 // calculation of (deg,min,sec) for Selector before panning 52 this.setSelectorWorld(mb.getNewEdge(), mb.getPixLon(),mb.getPixLat()); 53 //Paning 54 mb.setMap(s); 55 mob.setDrawablePoints(); 56 //calculation of new Selector position on panned map 57 selP.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 58 } 59 } 60 if(s=='d'){ 61 if (selP.getY()>0 && selP.getY()<mb.getCanvasHeight()-5) selP.addY(5); 62 if (selP.getY()>=(mb.getCanvasHeight()-5)) { 63 //calculation of (deg,min,sec) for Selector before panning 64 this.setSelectorWorld(mb.getNewEdge(), mb.getPixLon(),mb.getPixLat()); 65 //Paning 66 mb.setMap(s); 67 mob.setDrawablePoints(); 68 //calculation of new Selector position on panned map 69 selP.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 70 71 } 72 } 73 if(s=='u'){ 74 if (selP.getY()>6) selP.subY(5); 75 if (selP.getY()<=6) { 76 //calculation of (deg,min,sec) for Selector before panning 77 this.setSelectorWorld(mb.getNewEdge(), mb.getPixLon(),mb.getPixLat()); 78 //Paning

clix

Page 160: Defect prevention techniques

Zarko Acimovic

79 mb.setMap(s); 80 mob.setDrawablePoints(); 81 //calculation of new Selector position on panned map 82 selP.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 83 84 } 85 } 86 87 Point WP = this.getSelectedWP(); 88 89 if (!WP.getName().equals("selector") && colorSet==false) { 90 setColor(); 91 setBig(); 92 } 93 if (WP.getName().equals("selector") && colorSet==true) { 94 resetColor(); 95 resetBig(); 96 } 97 //if (!WP.getImage().equals("blanco") && !WP.getImage().equals("route") && big==false) setBig(); 98 //if ((WP.getImage().equals("blanco")||WP.getImage().equals("route")) && big==true) resetBig(); 99 } 100 101 102 103 /** When selector is moved we only update its (x,y) 'descriptors', 104 * so when map has to be panned we need to find out (lat,lon) pair 105 * for selector on old screen and adjust its position (x',y') on new screen 106 * in a way that (lat,lon) is unchanged 107 */ 108 public void setSelectorWorld(Point edge, long pixLon, long pixLat){ 109 110 // pamtim trenutno x i y 111 long tx = selP.getX(); 112 long ty = selP.getY(); 113 114 // azuriram svetske kordinate 115 long dLatSec = MathFP.mul(pixLat,MathFP.toFP(selP.getY())); 116 long dLonSec = MathFP.mul(pixLon,MathFP.toFP(selP.getX())); 117 118 selP = new Point(MathFP.sub(edge.getLatSec(),dLatSec), 119 MathFP.add(edge.getLonSec(),dLonSec),"","",false); 120 121 // vracam trenutno x i y 122 selP.setX(tx); 123 selP.setY(ty);

clx

Page 161: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

124 } 125 126 /** Returns copy of SELECTOR Point 127 * @return Point 128 */ 129 public Point getSelector(){ 130 this.setSelectorWorld(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 131 Point copy = new Point(selP,true); 132 133 copy.setName(""); 134 return copy; 135 } 136 137 /** Returns x-coordinate of selector 138 * @return long 139 */ 140 long getSelX(){ 141 return selP.getX(); 142 } 143 144 /** Returns y-coordinate of selector 145 * @return long 146 */ 147 long getSelY(){ 148 return selP.getY(); 149 } 150 151 /** Returns user selected Point 152 * @return Point 153 */ 154 public Point getSelectedWP(){ 155 Vector v = mob.getDrawablePoints(); 156 Point ret = new Point(0,0,"selector","s",false); 157 for(int i=0; i<v.size(); i++){ 158 Point fWhs = (Point) v.elementAt(i); 159 if( Math.abs(fWhs.getX()-selP.getX())<5 && 160 Math.abs(fWhs.getY()-selP.getY())<5 ) { 161 ret=fWhs; 162 i=1000; 163 } 164 } 165 return ret; 166 } 167 168 169 /** Returns user selected Point with name s 170 * @return Point 171 */ 172 public void selectWP(String s) { 173

clxi

Page 162: Defect prevention techniques

Zarko Acimovic

174 int len = s.length(); 175 int blanco = s.indexOf('_'); 176 if(blanco!=-1){ 177 String idS = s.substring(blanco+1,len); 178 s = s.substring(0,blanco); 179 s = compact(s); 180 } 181 182 int blank = s.indexOf(' '); 183 if(blank!=-1 && s.substring(blank+1,s.length()).equals("current")) s = s.substring(0,blank); 184 185 Point look4 = null; 186 PVector freeWPV = mob.getFreeWaypoints(); 187 188 int k=-2; 189 for(int i=0; i<freeWPV.size(); i++){ 190 Point wp = (Point) freeWPV.elementAt(i); 191 if(s.equals(wp.getName())){ 192 k=i; 193 look4 = (Point) freeWPV.elementAt(k); 194 i=1000; 195 } 196 } 197 198 if(k==-2){ 199 Point cP = mob.getCurrentPosition(); 200 if(s.equals(cP.getName())) { 201 look4=cP; 202 k=-3; 203 } 204 } 205 if(k==-2){ 206 Point dP = mob.getDestinationPosition(); 207 if(s.equals(dP.getName())) { 208 look4=dP; 209 k=-4; 210 } 211 } 212 213 if(k==-2){ 214 Vector routes = mob.getRoutes(); 215 for(int i=0; i<routes.size(); i++){ 216 PVector rt = (PVector) routes.elementAt(i); 217 for(int j=0; j<rt.size(); j++){ 218 Point wp = (Point)rt.elementAt(j); 219 System.out.println(wp); 220 if(wp.getName().equals(s)){ 221 k=j; 222 look4=(Point)rt.elementAt(j); 223 i=1000;

clxii

Page 163: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

224 j=1000; 225 } 226 } 227 } 228 } 229 230 this.selP = new Point(look4,false); 231 232 mb.setBackground(look4); 233 234 mob.setDrawablePoints(); 235 selP.setXY(mb.getNewEdge(),mb.getPixLon(), mb.getPixLat()); 236 237 if (!selP.getImage().equals("blanco") && big==false) setBig(); 238 if (selP.getImage().equals("blanco") && big==true) resetBig(); 239 240 this.setColor(); 241 } 242 243 /** Deletes selected Point 244 * Returns -4 if current Point is deleted 245 * Returns -3 if destination Point is deleted 246 * Returns -2 if free Point deleted 247 * Returns -1 if more then one Point is selected 248 * Returns 0 if none Point is selected 249 * Returns n if n-th Point in route deleted 250 */ 251 public int deleteWP(){ 252 int ret = 0; 253 254 this.setSelectorWorld(mb.getNewEdge(), mb.getPixLon(),mb.getPixLat()); 255 256 Vector temp1 = new Vector(); 257 PVector fWP = mob.getFreeWaypoints(); 258 for (int i=0; i<fWP.size(); i++){ 259 Point fwp = (Point)fWP.elementAt(i); 260 if( Math.abs(selP.getX()-fwp.getX())<5 && Math.abs(selP.getY()-fwp.getY())<5 ){ 261 temp1.addElement(new Integer(i)); 262 } 263 } 264 265 Vector temp2 = new Vector(); 266 Vector Routes = mob.getRoutes(); 267 for (int j=0; j<Routes.size(); j++){ 268 PVector vR = (PVector) Routes.elementAt(j); 269 for (int k=0; k<vR.size(); k++){ 270 Point wpR = (Point)vR.elementAt(k); 271 if( Math.abs(selP.getX()-wpR.getX())<5 && Math.abs(selP.getY()-wpR.getY())<5 ) {

clxiii

Page 164: Defect prevention techniques

Zarko Acimovic

272 temp2.addElement(new DelRoute(k,wpR.getTypeID())); 273 } 274 } 275 } 276 277 DelRoute drt = null; 278 if(temp2.size()>0){ 279 drt = (DelRoute) temp2.elementAt(0); 280 } 281 282 if ( (temp1.size()+temp2.size())> 1 ) ret=-1; 283 if ( (temp1.size()+temp2.size())==0 ) ret=0; 284 if ( temp1.size()==1 ) { 285 Integer k = (Integer) temp1.elementAt(0); 286 int d = k.intValue(); 287 fWP.removeElementAt(d); 288 ret=-2; 289 } 290 if( temp2.size()==1 ){ 291 DelRoute dr = (DelRoute) temp2.elementAt(0); 292 PVector vR = (PVector) Routes.elementAt(dr.getRouteID()-1); 293 vR.removeElementAt(dr.getIndex()); 294 ret=dr.getIndex(); 295 } 296 297 Point cp = mob.getCurrentPosition(); 298 if( Math.abs(selP.getX()-cp.getX())<5 && 299 Math.abs(selP.getY()-cp.getY())<5 ) { 300 mob.resetCurrentPosition(); 301 ret= -4; 302 } 303 304 Point dp = mob.getDestinationPosition(); 305 306 if( Math.abs(selP.getX()-dp.getX())<5 && 307 Math.abs(selP.getY()-dp.getY())<5 ) { 308 mob.resetDestinationPosition(); 309 ret= -3; 310 } 311 312 resetColor(); 313 314 return ret; 315 } 316 317 318 /** Action that must be taken with Selector when Zoom In/Out 319 */ 320 public void Zoom(){

clxiv

Page 165: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

321 this.setSelectorWorld(mb.getPreviousEdge(), mb.getPreviousPixLon(),mb.getPreviousPixLat()); 322 selP.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 323 while (selP.getX()>mb.getCanvasWidth()) { 324 this.setSelectorWorld(mb.getNewEdge(), mb.getPixLon(),mb.getPixLat()); 325 mb.setMap('r'); 326 selP.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 327 } 328 while (selP.getY()>mb.getCanvasHeight()) { 329 this.setSelectorWorld(mb.getNewEdge(), mb.getPixLon(),mb.getPixLat()); 330 mb.setMap('d'); 331 selP.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 332 } 333 while (selP.getX()<0){ 334 this.setSelectorWorld(mb.getNewEdge(), mb.getPixLon(),mb.getPixLat()); 335 mb.setMap('l'); 336 selP.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 337 } 338 while (selP.getY()<0) { 339 this.setSelectorWorld(mb.getNewEdge(), mb.getPixLon(),mb.getPixLat()); 340 mb.setMap('u'); 341 selP.setXY(mb.getNewEdge(),mb.getPixLon(),mb.getPixLat()); 342 } 343 } 344 345 346 /** Draws selector point 347 * 348 public void drawSelPOld(Graphics g){ 349 long zl = mb.getZoomLevel()+1; 350 Long zzl = new Long(zl); 351 int zoomL = Integer.parseInt(zzl.toString()); 352 g.setColor(0,0,0); 353 g.drawRect(selP.getXX()-6,selP.getYY()-3,12,6); 354 g.setColor(m,n,s); 355 g.fillRect(selP.getXX()-3,selP.getYY()-6,6,12); 356 g.setColor(0,0,0); 357 } 358 359 /** Draws selector point 360 * 361 public void drawSelPOld1(Graphics g){ 362 long zl = mb.getZoomLevel()+1; 363 Long zzl = new Long(zl); 364 int zoomL = Integer.parseInt(zzl.toString()); 365 g.setColor(m,n,s); 366 g.fillRect(selP.getXX()-8,selP.getYY()-4,16,8);

clxv

Page 166: Defect prevention techniques

Zarko Acimovic

367 g.fillRect(selP.getXX()-4,selP.getYY()-8,8,16); 368 g.setColor(0,0,0); 369 g.drawRect(selP.getXX()-8,selP.getYY()-4,16,8); 370 g.drawRect(selP.getXX()-4,selP.getYY()-8,8,16); 371 g.setColor(m,n,s); 372 g.fillRect(selP.getXX()-7,selP.getYY()-3,15,7); 373 g.fillRect(selP.getXX()-3,selP.getYY()-7,7,15); 374 375 g.setColor(0,0,0); 376 377 378 } 379 380 /** Draws selector point 381 * 382 public void drawSelPobsolete(Graphics g){ 383 //long zl = mb.getZoomLevel()+1; 384 //Long zzl = new Long(zl); 385 //int zoomL = Integer.parseInt(zzl.toString()); 386 if(big==false){ 387 g.setColor(m,n,s); 388 g.fillRect(selP.getXX()-8,selP.getYY()-4,15,7); 389 g.fillRect(selP.getXX()-4,selP.getYY()-8,7,5); 390 g.setColor(0,0,0); 391 g.drawRect(selP.getXX()-8,selP.getYY()-4,15,7); 392 g.drawRect(selP.getXX()-4,selP.getYY()-8,7,15); 393 g.setColor(m,n,s); 394 g.fillRect(selP.getXX()-7,selP.getYY()-3,14,6); 395 g.fillRect(selP.getXX()-3,selP.getYY()-7,6,14); 396 } else { 397 g.setColor(m,n,s); 398 g.fillRect(selP.getXX()-13,selP.getYY()-5,33,16); 399 g.fillRect(selP.getXX()-5,selP.getYY()-13,16,22);///umesto 16,32 sad je 16,25 400 g.setColor(0,0,0); 401 g.drawRect(selP.getXX()-13,selP.getYY()-5,33,16); 402 g.drawRect(selP.getXX()-5,selP.getYY()-13,16,22);///umesto 16,32 sad je 16,25 403 g.setColor(m,n,s); 404 g.fillRect(selP.getXX()-12,selP.getYY()-4,32,15); 405 g.fillRect(selP.getXX()-4,selP.getYY()-12,15,22); 406 407 //g.drawString(selP.getName(),selP.getXX()-15,selP.getYY()+11,0); 408 } 409 g.setColor(0,0,0); 410 if (!this.getSelectedWP().getName().equals("selector")) g.drawString(this.getSelectedWP().getName(),this.getSelectedWP().getXX()-15,this.getSelectedWP().getYY()+11,0); 411 }*/ 412

clxvi

Page 167: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

413 public void drawSelP(Graphics g){ 414 int length=0; 415 416 //g.setColor(m,n,s); 417 g.setColor(255,180,0); 418 g.fillRect(selP.getXX()-8,selP.getYY()-4,15,7); 419 g.fillRect(selP.getXX()-4,selP.getYY()-8,7,5); 420 g.setColor(0,0,0); 421 g.drawRect(selP.getXX()-8,selP.getYY()-4,15,7); 422 g.drawRect(selP.getXX()-4,selP.getYY()-8,7,15); 423 //g.setColor(m,n,s); 424 g.setColor(255,180,0); 425 g.fillRect(selP.getXX()-7,selP.getYY()-3,14,6); 426 g.fillRect(selP.getXX()-3,selP.getYY()-7,6,14); 427 /** 428 if(big==true){ 429 g.setColor(m,n,s); 430 //g.drawRect(selP.getXX()-4,selP.getYY()-4,15,15); 431 //g.drawRect(selP.getXX()-5,selP.getYY()-5,17,17); 432 //g.drawRect(selP.getXX()-6,selP.getYY()-6,19,19); 433 String name = this.getSelectedWP().getName(); 434 length = name.length(); 435 g.fillRect(selP.getXX()-4*length-2,selP.getYY()+12,8*length+2,14); 436 } 437 g.setColor(0,0,0); 438 if (!this.getSelectedWP().getName().equals("selector")) g.drawString(this.getSelectedWP().getName(),selP.getXX()-4*length,selP.getYY()+13,0); 439 */ 440 } 441 442 public void drawCaption(Graphics g){ 443 int length=0; 444 if(big==true){ 445 g.setColor(m,n,s); 446 //g.drawRect(selP.getXX()-4,selP.getYY()-4,15,15); 447 //g.drawRect(selP.getXX()-5,selP.getYY()-5,17,17); 448 //g.drawRect(selP.getXX()-6,selP.getYY()-6,19,19); 449 String name = this.getSelectedWP().getName(); 450 length = name.length(); 451 g.fillRect(selP.getXX()-4*length-2,selP.getYY()+12,8*length+2,14); 452 //if (!this.getSelectedWP().getName().equals("selector")) g.drawString(this.getSelectedWP().getName(),selP.getXX()-4*length,selP.getYY()+13,0); 453 g.setColor(0,0,0); 454 if (!this.getSelectedWP().getName().equals("selector")) g.drawString(this.getSelectedWP().getName(),selP.getXX()-4*length,selP.getYY()+13,0); 455 }

clxvii

Page 168: Defect prevention techniques

Zarko Acimovic

456 457 } 458 459 460 461 /** Sets current position 462 */ 463 public void setCurrent(MapObjects mob){ 464 Point wp = this.getSelectedWP(); 465 mob.setCurrentPosition(wp); 466 } 467 468 /** Sets destination position 469 */ 470 public void setDest(MapObjects mob){ 471 Point wp = this.getSelectedWP(); 472 mob.setDestinationPosition(wp); 473 } 474 475 public void setColorOld(){ 476 s = 0; 477 colorSet=true; 478 } 479 480 public void setColor(){ 481 m=255; 482 n=255; 483 s=0; 484 colorSet=true; 485 } 486 487 public void resetColorOld(){ 488 s = 255; 489 colorSet=false; 490 } 491 492 public void resetColor(){ 493 m=255; 494 n=180; 495 s=0; 496 colorSet=false; 497 } 498 499 public void setBig(){ 500 big=true; 501 } 502 503 public void resetBig(){ 504 big=false; 505 } 506

clxviii

Page 169: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

507 /** Blanco characters are possible to occur in names of pictures; 508 * Integer representations of blanko characters are 9 and 32 509 * Also, characters with integer representation between 0 and 33 510 * can not be printed out in WSDD console, so I excluded them too 511 */ 512 public String compact(String s){ 513 int k = s.length(); 514 char[] d = s.toCharArray(); 515 String ret = ""; 516 for(int i=0; i<d.length; i++){ 517 int temp = (int)d[i]; 518 if(temp>32) ret+=d[i]; 519 } 520 int kk = ret.length(); 521 if (kk!=k) System.out.println("Bugger is: "+s); 522 return ret; 523 } 524 525 526 527 }

SimpleTextForm.java

clxix

All classes and interfaces must belong to a named package 15 PMD Marker

Lack of Cohesion in Methods (Henderson-Sellers) is 75% 15 Metrics Marker

Lack of Cohesion in Methods (Pairwise Field Irrelation) is 74% 15 Metrics Marker

Lack of Cohesion in Methods (Total Correlation) is 154% 15 Metrics Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 19 PMD Marker

Use explicit scoping instead of the default package private level 19 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 23 PMD Marker

Use explicit scoping instead of the default package private level 23 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 25 PMD Marker

Use explicit scoping instead of the default package private level 25 PMD Marker

Found non-transient, non-static member. Please mark as transient or provide accessors. 27 PMD Marker

Use explicit scoping instead of the default package private level 27 PMD Marker

Parameter 'createChgr' is not assigned and could be declared final 33 PMD Marker

Avoid unnecessary comparisons in boolean expressions 39 PMD Marker

Avoid variables with short names like s 63 PMD Marker

Parameter 's' is not assigned and could be declared final 63 PMD Marker

Avoid variables with short names like s 67 PMD Marker

Parameter 's' is not assigned and could be declared final 67 PMD Marker

Avoid variables with short names like s 71 PMD Marker

Page 170: Defect prevention techniques

Zarko Acimovic

1 /** 2 * Simple text form 3 */ 4 5 6 import javax.microedition.lcdui.*; 7 8 //import javax.microedition.midlet.*; 9 10 11 //import java.io.*; 12 //import java.util.*; 13 14 15 public class SimpleTextForm extends Form{ 16 17 /** Name of waypoint 18 */ 19 TextField nameWP; 20 21 /** Type of waypoint 22 */ 23 TextField typeWP; 24 25 String[] str = new String[2]; 26 27 ChoiceGroup chgr; 28 29 30 31 /** Creates new form 32 */ 33 SimpleTextForm(boolean createChgr){ 34 super("Data Input"); 35 nameWP = new TextField("Name","",8,0); 36 typeWP = new TextField("Type","",8,0); 37 this.append(nameWP); 38 this.append(typeWP); 39 if(createChgr==true){ 40 str[0] = "Sysnchronized Following"; 41 str[1] = "Out of Sync"; 42 chgr = new ChoiceGroup("",1,str,null); 43 this.append(chgr); 44 } 45 } 46 47 /** Returns the name of waypoint 48 * @return String 49 */

clxx

Page 171: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

50 public String getName(){ 51 return nameWP.getString(); 52 } 53 54 /** Returns the type of waypoint 55 * @return String 56 */ 57 public String getType(){ 58 return typeWP.getString(); 59 } 60 61 /** Sets the name of waypoint 62 */ 63 public void setName(String s){ 64 nameWP.setString(s); 65 } 66 67 public void setLabel(String s){ 68 nameWP.setLabel(s); 69 } 70 71 public void setLabel2(String s){ 72 typeWP.setLabel(s); 73 } 74 75 /** Sets the type of waypoint 76 */ 77 public void setType(String s){ 78 typeWP.setString(s); 79 } 80 81 public int getSelected(){ 82 return chgr.getSelectedIndex(); 83 } 84 }

clxxi

Page 172: Defect prevention techniques

Zarko Acimovic

TextForm.java

clxxii

All classes and interfaces must belong to a named package 15 PMD MarkerLack of Cohesion in Methods (Henderson-Sellers) is 80% 15 Metrics MarkerLack of Cohesion in Methods (Pairwise Field Irrelation) is 81% 15 Metrics MarkerLack of Cohesion in Methods (Total Correlation) is 165% 15 Metrics MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 19 PMD MarkerUse explicit scoping instead of the default package private level 19 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 23 PMD MarkerUse explicit scoping instead of the default package private level 23 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 27 PMD MarkerUse explicit scoping instead of the default package private level 27 PMD MarkerUse explicit scoping instead of the default package private level 29 PMD MarkerUse explicit scoping instead of the default package private level 30 PMD MarkerLines of Code in Method is 30 33 Metrics MarkerAvoid unused constructor parameters such as 'first'. 35 PMD MarkerAvoid variables with short names like s 35 PMD MarkerParameter 's' is not assigned and could be declared final 35 PMD MarkerThe user-supplied array 's' is stored directly. 35 PMD MarkerThe user-supplied array 's' is stored directly. 35 PMD MarkerAvoid assignments in operands 41 PMD MarkerDead store to first in new TextForm(String[], boolean) 41 FindBugsnew TextForm(String[], boolean) assigns boolean literal in boolean expression 41 FindBugsThe parameter first to new TextForm(String[], boolean) is dead upon entry but overwritten 41 FindBugsAvoid variables with short names like s 80 PMD MarkerParameter 's' is not assigned and could be declared final 80 PMD MarkerAvoid variables with short names like s 86 PMD MarkerParameter 's' is not assigned and could be declared final 86 PMD MarkerAvoid variables with short names like s 94 PMD MarkerParameter 's' is not assigned and could be declared final 94 PMD MarkerAvoid variables with short names like s 98 PMD MarkerParameter 's' is not assigned and could be declared final 98 PMD Marker

Page 173: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

1 /** 2 * Text form 3 */ 4 5 6 import javax.microedition.lcdui.*; 7 8 //import javax.microedition.midlet.*; 9 10 11 //import java.io.*; 12 //import java.util.*; 13 14 15 public class TextForm extends Form{ 16 17 /** Name of waypoint 18 */ 19 TextField nameWP; 20 21 /** Type of waypoint 22 */ 23 TextField typeWP; 24 25 /** ChoiceGroup of categories 26 */ 27 ChoiceGroup chgr; 28 29 TextField lat; 30 TextField lon; 31 32 33 /** Creates new form 34 */ 35 TextForm(String[] s, boolean first){ 36 super("Data Input"); 37 nameWP = new TextField("Name","",50,0); 38 typeWP = new TextField("Type","",50,0); 39 this.append(nameWP); 40 41 if(first = false){ 42 //this.append(typeWP); 43 this.append(""); 44 chgr = new ChoiceGroup("Category",1,s,null); 45 this.append(chgr); 46 47 lat = new TextField("Latitude","",50,0); 48 lon = new TextField("Longitude","",50,0); 49 this.append(lat); 50 this.append(lon); 51 }else{

clxxiii

Page 174: Defect prevention techniques

Zarko Acimovic

52 lat = new TextField("Latitude","",50,0); 53 lon = new TextField("Longitude","",50,0); 54 this.append(lat); 55 this.append(lon); 56 57 this.append(""); 58 chgr = new ChoiceGroup("Category:",1,s,null); 59 this.append(chgr); 60 } 61 62 } 63 64 /** Returns the name of waypoint 65 * @return String 66 */ 67 public String getName(){ 68 return nameWP.getString(); 69 } 70 71 /** Returns the type of waypoint 72 * @return String 73 */ 74 public String getType(){ 75 return typeWP.getString(); 76 } 77 78 /** Sets the name of waypoint 79 */ 80 public void setName(String s){ 81 nameWP.setString(s); 82 } 83 84 /** Sets the type of waypoint 85 */ 86 public void setType(String s){ 87 typeWP.setString(s); 88 } 89 90 public int getSelected(){ 91 return chgr.getSelectedIndex(); 92 } 93 94 public void setLat(long s){ 95 lat.setString(MathFP.toString(s)); 96 } 97 98 public void setLon(long s){ 99 lon.setString(MathFP.toString(s)); 100 } 101 102 public void setLat(String s){

clxxiv

Page 175: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

103 lat.setString(s); 104 } 105 106 public void setLon(String s){ 107 lon.setString(s); 108 } 109 110 public String getLat(){ 111 return lat.getString(); 112 } 113 114 public String getLon(){ 115 return lon.getString(); 116 } 117 }

TextFromFriend.java

clxxv

All classes and interfaces must belong to a named package 15 PMD MarkerLack of Cohesion in Methods (Pairwise Field Irrelation) is 83% 15 Metrics MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 19 PMD MarkerUse explicit scoping instead of the default package private level 19 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 23 PMD MarkerUse explicit scoping instead of the default package private level 23 PMD MarkerAvoid variables with short names like s 53 PMD MarkerParameter 's' is not assigned and could be declared final 53 PMD MarkerAvoid variables with short names like s 57 PMD MarkerParameter 's' is not assigned and could be declared final 57 PMD MarkerAvoid variables with short names like s 63 PMD MarkerParameter 's' is not assigned and could be declared final 63 PMD Marker

Page 176: Defect prevention techniques

Zarko Acimovic

1 /** 2 * Text form 3 */ 4 5 6 import javax.microedition.lcdui.*; 7 8 //import javax.microedition.midlet.*; 9 10 11 //import java.io.*; 12 //import java.util.*; 13 14 15 public class TextFormFriend extends Form{ 16 17 /** Name of waypoint 18 */ 19 TextField nameWP; 20 21 /** Type of waypoint 22 */ 23 TextField typeWP; 24 25 26 27 /** Creates new form 28 */ 29 TextFormFriend(){ 30 super("Data Input"); 31 nameWP = new TextField("Name","",8,0); 32 typeWP = new TextField("Type","",8,0); 33 this.append(nameWP); 34 this.append(typeWP); 35 } 36 37 /** Returns the name of waypoint 38 * @return String 39 */ 40 public String getName(){ 41 return nameWP.getString(); 42 } 43 44 /** Returns the type of waypoint 45 * @return String 46 */ 47 public String getType(){ 48 return typeWP.getString(); 49 } 50 51 /** Sets the name of waypoint

clxxvi

Page 177: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

52 */ 53 public void setName(String s){ 54 nameWP.setString(s); 55 } 56 57 public void setLabel(String s){ 58 nameWP.setLabel(s); 59 } 60 61 /** Sets the type of waypoint 62 */ 63 public void setType(String s){ 64 typeWP.setString(s); 65 } 66 }

TextFormImage.java

clxxvii

All classes and interfaces must belong to a named package 15 PMD MarkerLack of Cohesion in Methods (Henderson-Sellers) is 72% 15 Metrics MarkerLack of Cohesion in Methods (Pairwise Field Irrelation) is 93% 15 Metrics MarkerLack of Cohesion in Methods (Total Correlation) is 88% 15 Metrics MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 19 PMD MarkerUse explicit scoping instead of the default package private level 19 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 27 PMD MarkerUse explicit scoping instead of the default package private level 27 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 34 PMD MarkerUse explicit scoping instead of the default package private level 34 PMD MarkerAvoid variables with short names like s 39 PMD MarkerParameter 'img' is not assigned and could be declared final 39 PMD MarkerParameter 'nameChg' is not assigned and could be declared final 39 PMD MarkerParameter 's' is not assigned and could be declared final 39 PMD MarkerRead of unwritten field typeWP in TextFormImage.getType() 59 FindBugsUnwritten field: TextFormImage.typeWP 59 FindBugsAvoid variables with short names like s 64 PMD MarkerParameter 's' is not assigned and could be declared final 64 PMD MarkerAvoid variables with short names like s 70 PMD MarkerParameter 's' is not assigned and could be declared final 70 PMD MarkerRead of unwritten field typeWP in TextFormImage.setType(String) 71 FindBugsAvoid variables with short names like s 78 PMD MarkerAvoid variables with short names like s 82 PMD Marker

Page 178: Defect prevention techniques

Zarko Acimovic

1 /** 2 * Text form for ChoicGroup with images 3 */ 4 5 6 import javax.microedition.lcdui.*; 7 8 //import javax.microedition.midlet.*; 9 10 11 //import java.io.*; 12 //import java.util.*; 13 14 15 public class TextFormImage extends Form{ 16 17 /** Name of waypoint 18 */ 19 TextField nameWP; 20 21 /** Category of waypoit 22 */ 23 // TextField catWP; 24 25 /** Type of waypoint 26 */ 27 TextField typeWP; 28 29 /** ChoiceGroup of categories 30 */ 31 32 // TextField lat; 33 // TextField lon; 34 ChoiceGroup chgr; 35 36 37 /** Creates new form 38 */ 39 TextFormImage(String nameChg, String[] s, Image[] img){ 40 super("Data Input"); 41 nameWP = new TextField("Name","",50,0); 42 this.append(nameWP); 43 this.append(""); 44 chgr = new ChoiceGroup(nameChg,1,s,img); 45 this.append(chgr); 46 } 47 48 /** Returns the name of waypoint 49 * @return String 50 */ 51 public String getName(){

clxxviii

Page 179: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

52 return nameWP.getString(); 53 } 54 55 /** Returns the type of waypoint 56 * @return String 57 */ 58 public String getType(){ 59 return typeWP.getString(); 60 } 61 62 /** Sets the name of waypoint 63 */ 64 public void setName(String s){ 65 nameWP.setString(s); 66 } 67 68 /** Sets the type of waypoint 69 */ 70 public void setType(String s){ 71 typeWP.setString(s); 72 } 73 74 public int getSelected(){ 75 return chgr.getSelectedIndex(); 76 } 77 78 public void setNameCHGR(String s){ 79 chgr.setLabel(s); 80 } 81 82 public void setLat(long s){ 83 //lat.setString(MathFP.toString(s)); 84 } 85 86 public void setLon(long s){ 87 //lon.setString(MathFP.toString(s)); 88 } 89 }

clxxix

Page 180: Defect prevention techniques

Zarko Acimovic

TextFormWP.java

1 /** 2 * Text form for insertion of waypoint 3 */ 4 5 6 import javax.microedition.lcdui.*; 7 8 //import javax.microedition.midlet.*; 9 10 11 //import java.io.*; 12 //import java.util.*; 13 14

clxxx

All classes and interfaces must belong to a named package 15 PMD MarkerLack of Cohesion in Methods (Chidamber & Kemerer) is 50 15 Metrics MarkerLack of Cohesion in Methods (Henderson-Sellers) is 91% 15 Metrics MarkerLack of Cohesion in Methods (Pairwise Field Irrelation) is 67% 15 Metrics MarkerLack of Cohesion in Methods (Total Correlation) is 351% 15 Metrics MarkerNumber of Fields is 11 15 Metrics MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 19 PMD MarkerUse explicit scoping instead of the default package private level 19 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 23 PMD MarkerUse explicit scoping instead of the default package private level 23 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 27 PMD MarkerUse explicit scoping instead of the default package private level 27 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 31 PMD MarkerUse explicit scoping instead of the default package private level 31 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 35 PMD MarkerUse explicit scoping instead of the default package private level 35 PMD MarkerLines of Code in Method is 39 64 Metrics MarkerNumber of Statements is 23 64 Metrics MarkerAvoid variables with short names like s 66 PMD MarkerParameter 's' is not assigned and could be declared final 66 PMD MarkerThe user-supplied array 's' is stored directly. 66 PMD MarkerAvoid variables with short names like s 120 PMD MarkerParameter 's' is not assigned and could be declared final 120 PMD MarkerAvoid variables with short names like s 126 PMD MarkerParameter 's' is not assigned and could be declared final 126 PMD MarkerAvoid variables with short names like r 133 PMD MarkerLocal variable 'r' could be declared final 133 PMD MarkerConsider simply returning the value vs storing it in local variable 'r' 134 PMD MarkerAvoid variables with short names like r 140 PMD MarkerLocal variable 'r' could be declared final 140 PMD MarkerConsider simply returning the value vs storing it in local variable 'r' 141 PMD MarkerLocal variable 'r' could be declared final 147 PMD MarkerConsider simply returning the value vs storing it in local variable 'r' 148 PMD MarkerLocal variable 's' could be declared final 154 PMD MarkerLocal variable 'c' could be declared final 155 PMD MarkerConsider simply returning the value vs storing it in local variable 'k' 157 PMD MarkerConsider simply returning the value vs storing it in local variable 'r' 164 PMD Marker

Page 181: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

15 public class TextFormWP extends Form{ 16 17 /** Name of waypoint 18 */ 19 TextField nameWP; 20 21 /** Type of waypoint 22 */ 23 TextField typeWP; 24 25 /** Degrees of latitude 26 */ 27 TextField degLat; 28 29 /** Minutes of latitude 30 */ 31 TextField minLat; 32 33 /** Seconds of latitude 34 */ 35 TextField secLat; 36 37 /** Side NORTH / SOUTH 38 */ 39 TextField sideNS; 40 41 42 /** Degrees of longitude 43 */ 44 TextField degLon; 45 46 /** Minutes of longitude 47 */ 48 TextField minLon; 49 50 /** Seconds of longitude 51 */ 52 TextField secLon; 53 54 /** Side WEST / EAST 55 */ 56 TextField sideWE; 57 58 /** ChoiceGroup of categories 59 */ 60 ChoiceGroup chgr; 61 62 63 64 /** Creates new form 65 */

clxxxi

Page 182: Defect prevention techniques

Zarko Acimovic

66 TextFormWP(String[] s){ 67 super("Data Input"); 68 nameWP = new TextField("Name","",12,0); 69 this.append(nameWP); 70 typeWP = new TextField("Type","",12,0); 71 this.append(typeWP); 72 73 74 degLat = new TextField("Degrees of Latitude","",8,0); 75 this.append(degLat); 76 77 minLat = new TextField("Minutes of Latitude","",8,0); 78 this.append(minLat); 79 80 secLat = new TextField("Seconds of Latitude","",8,0); 81 this.append(secLat); 82 83 sideNS = new TextField("Side, North or South?","",8,0); 84 this.append(sideNS); 85 86 87 degLon = new TextField("Degrees of Longitude","",8,0); 88 this.append(degLon); 89 90 minLon = new TextField("Minutes of Longitude","",8,0); 91 this.append(minLon); 92 93 secLon = new TextField("Seconds of Longitude","",8,0); 94 this.append(secLon); 95 96 sideWE = new TextField("Side, West or East?","",8,0); 97 this.append(sideWE); 98 99 chgr = new ChoiceGroup("Categories",1,s,null); 100 this.append(chgr); 101 102 } 103 104 /** Returns the name of waypoint 105 * @return String 106 */ 107 public String getName(){ 108 return nameWP.getString(); 109 } 110 111 /** Returns the type of waypoint 112 * @return String 113 */ 114 public String getType(){ 115 return typeWP.getString(); 116 }

clxxxii

Page 183: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

117 118 /** Sets the name of waypoint 119 */ 120 public void setName(String s){ 121 nameWP.setString(s); 122 } 123 124 /** Sets the type of waypoint 125 */ 126 public void setType(String s){ 127 typeWP.setString(s); 128 } 129 130 /** Returns degrees of latitude 131 */ 132 public int getDegLat(){ 133 int r = Integer.parseInt(degLat.getString()); 134 return r; 135 } 136 137 /** Returns minutes of latitude 138 */ 139 public int getMinLat(){ 140 int r = Integer.parseInt(minLat.getString()); 141 return r; 142 } 143 144 /** Returns seconds of latitude 145 */ 146 public int getSecLat(){ 147 int r = Integer.parseInt(secLat.getString()); 148 return r; 149 } 150 151 /** Returns side, North or South 152 */ 153 public char getSideNS(){ 154 String s = sideNS.getString(); 155 char[] c = s.toCharArray(); 156 char k = c[0]; 157 return k; 158 } 159 160 /** Returns degrees of longitude 161 */ 162 public int getDegLon(){ 163 int r = Integer.parseInt(degLon.getString()); 164 return r; 165 } 166 167 /** Returns minutes of longitude

clxxxiii

Page 184: Defect prevention techniques

Zarko Acimovic

168 */ 169 public int getMinLon(){ 170 int r = Integer.parseInt(minLon.getString()); 171 return r; 172 } 173 174 /** Returns seconds of longitude 175 */ 176 public int getSecLon(){ 177 int r = Integer.parseInt(secLon.getString()); 178 return r; 179 } 180 181 /** Returns side, West or East 182 */ 183 public char getSideWE(){ 184 String s = sideWE.getString(); 185 char[] c = s.toCharArray(); 186 char k = c[0]; 187 return k; 188 } 189 }

clxxxiv

Page 185: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

Thread4Friend.java

clxxxv

All classes and interfaces must belong to a named package 15 PMD MarkerLack of Cohesion in Methods (Chidamber & Kemerer) is 50 15 Metrics MarkerLack of Cohesion in Methods (Henderson-Sellers) is 91% 15 Metrics MarkerLack of Cohesion in Methods (Pairwise Field Irrelation) is 67% 15 Metrics MarkerLack of Cohesion in Methods (Total Correlation) is 351% 15 Metrics MarkerNumber of Fields is 11 15 Metrics MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 19 PMD MarkerUse explicit scoping instead of the default package private level 19 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 23 PMD MarkerUse explicit scoping instead of the default package private level 23 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 27 PMD MarkerUse explicit scoping instead of the default package private level 27 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 31 PMD MarkerUse explicit scoping instead of the default package private level 31 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 35 PMD MarkerUse explicit scoping instead of the default package private level 35 PMD MarkerLines of Code in Method is 39 64 Metrics MarkerNumber of Statements is 23 64 Metrics MarkerAvoid variables with short names like s 66 PMD MarkerParameter 's' is not assigned and could be declared final 66 PMD MarkerThe user-supplied array 's' is stored directly. 66 PMD MarkerAvoid variables with short names like s 120 PMD MarkerParameter 's' is not assigned and could be declared final 120 PMD MarkerAvoid variables with short names like s 126 PMD MarkerParameter 's' is not assigned and could be declared final 126 PMD MarkerAvoid variables with short names like r 133 PMD MarkerLocal variable 'r' could be declared final 133 PMD MarkerConsider simply returning the value vs storing it in local variable 'r' 134 PMD MarkerAvoid variables with short names like r 140 PMD MarkerAll classes and interfaces must belong to a named package 13 PMD MarkerLack of Cohesion in Methods (Henderson-Sellers) is 91% 13 Metrics MarkerLack of Cohesion in Methods (Pairwise Field Irrelation) is 54% 13 Metrics MarkerLack of Cohesion in Methods (Total Correlation) is 420% 13 Metrics MarkerThe class 'Thread4Friend' has a Cyclomatic Complexity of 4 (Highest = 10). 13 PMD MarkerTo be compliant to J2EE, a webapp should not use any thread. 13 PMD MarkerAvoid variables with short names like t 14 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 14 PMD MarkerTo be compliant to J2EE, a webapp should not use any thread. 14 PMD MarkerUse explicit scoping instead of the default package private level 14 PMD MarkerAvoid using implementation types like 'Vector'; use the interface instead 15 PMD MarkerAvoid using implementation types like 'Vector'; use the interface instead 15 PMD MarkerConsider replacing this Vector with the newer java.util.List 15 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 MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 16 PMD MarkerUse explicit scoping instead of the default package private level 16 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 17 PMD Marker

Page 186: Defect prevention techniques

Zarko Acimovic

Thread4Friend.java

clxxxvi

Use explicit scoping instead of the default package private level 17 PMD MarkerAvoid variables with short names like ic 18 PMD MarkerFound non-transient, non-static member. Please mark as transient or provide accessors. 18 PMD MarkerUse explicit scoping instead of the default package private level 18 PMD MarkerAvoid variables with short names like mb 19 PMD MarkerAvoid using implementation types like 'Vector'; use the interface instead 24 PMD MarkerAvoid using implementation types like 'Vector'; use the interface instead 24 PMD MarkerAvoid variables with short names like ic 24 PMD MarkerAvoid variables with short names like mb 24 PMD MarkerConsider replacing this Vector with the newer java.util.List 24 PMD MarkerNumber of Parameters is 6 24 Metrics MarkerParameter 'ic' is not assigned and could be declared final 24 PMD MarkerParameter 'mb' is not assigned and could be declared final 24 PMD MarkerParameter 'mob' is not assigned and could be declared final 24 PMD MarkerParameter 'oul' is not assigned and could be declared final 24 PMD MarkerParameter 'resource' is not assigned and could be declared final 24 PMD MarkerUnread field: Thread4Friend.oul 25 FindBugsTo be compliant to J2EE, a webapp should not use any thread. 31 PMD MarkerCyclomatic Complexity is 8 45 Metrics MarkerLines of Code in Method is 66 45 Metrics MarkerNumber of Levels is 5 45 Metrics MarkerNumber of Locals in Scope is 17 45 Metrics MarkerNumber of Statements is 75 45 Metrics MarkerThe method 'run' has a Cyclomatic Complexity of 10. 45 PMD MarkerTo be compliant to J2EE, a webapp should not use any thread. 47 PMD MarkerAvoid instantiating new objects inside loops 52 PMD MarkerLocal variable 's' could be declared final 53 PMD MarkerLocal variable 'lastIndex' could be declared final 59 PMD MarkerAvoid unused local variables such as 'currentTS'. 67 PMD MarkerThe local variable currentTS is never read 67 Java ProblemAvoid instantiating new objects inside loops 71 PMD MarkerPosition literals first in String comparisons 75 PMD MarkerLocal variable 'comma' could be declared final 79 PMD MarkerLocal variable 'nextComma' could be declared final 81 PMD MarkerAssigning an Object to null is a code smell. Consider refactoring. 90 PMD MarkerPosition literals first in String comparisons 91 PMD MarkerAvoid instantiating new objects inside loops 92 PMD MarkerAvoid empty catch blocks 98 PMD MarkerThread4Friend.run() might ignore java.lang.Exception 98 FindBugsAvoid unnecessary comparisons in boolean expressions 102 PMD MarkerLines of Code in Method is 19 114 Metrics MarkerAvoid unused local variables such as 'k'. 120 PMD MarkerDead store to k in Thread4Friend.compact(String) 120 FindBugsLocal variable 'k' could be declared final 120 PMD MarkerThe local variable k is never read 120 Java ProblemAvoid using if statements without curly braces 126 PMD MarkerPrefer StringBuffer over += for concatenating strings 126 PMD Marker

Page 187: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

Thread4Friend.java

clxxxvii

Thread4Friend.compact(String) concatenates strings using + in a loop 126 FindBugsAvoid unused local variables such as 'kk'. 129 PMD MarkerDead store to kk in Thread4Friend.compact(String) 129 FindBugsThe local variable kk is never read 129 Java ProblemAvoid unused local variables such as 'k'. 135 PMD MarkerDead store to k in Thread4Friend.compactFine(String) 135 FindBugsThe local variable k is never read 135 Java ProblemAvoid using if statements without curly braces 141 PMD MarkerPrefer StringBuffer over += for concatenating strings 141 PMD MarkerThread4Friend.compactFine(String) concatenates strings using + in a loop 141 FindBugsAvoid unused local variables such as 'kk'. 144 PMD MarkerDead store to kk in Thread4Friend.compactFine(String) 144 FindBugsThe local variable kk is never read 144 Java ProblemCyclomatic Complexity is 6 149 Metrics MarkerLines of Code in Method is 31 149 Metrics MarkerNumber of Statements is 24 149 Metrics Marker

Avoid empty catch blocks 153 PMD Marker

Avoid empty catch blocks 164 PMD MarkerPrefer StringBuffer over += for concatenating strings 167 PMD MarkerThread4Friend.getResourceAsString(String) concatenates strings using + in a loop 167 FindBugs

Avoid empty catch blocks 170 PMD Marker

173 FindBugsAvoid empty catch blocks 174 PMD Marker

Possible null pointer dereference of is in Thread4Friend.getResourceAsString(String) on exception path

Page 188: Defect prevention techniques

Zarko Acimovic

1 /** 2 * 3 * Thread4Friend controls apperance of friend's position on screen 4 */ 5 //import javax.microedition.lcdui.*; 6 7 //import javax.microedition.midlet.*; 8 9 import java.util.*; 10 import java.io.*; 11 12 13 public class Thread4Friend implements Runnable{ 14 Thread t; 15 Vector whiteList; 16 String resource; 17 MapObjects mob; 18 ImageCanvas3 ic; 19 MapBackground mb; 20 Outlook oul; 21 int hashID; 22 boolean first = false; 23 24 Thread4Friend(Vector whiteList, String resource, MapObjects mob, ImageCanvas3 ic, MapBackground mb, Outlook oul){ 25 this.oul = oul; 26 this.mob = mob; 27 this.mb = mb; 28 this.ic = ic; 29 this.resource = resource; 30 this.whiteList = whiteList; 31 t = new Thread(this); 32 //t.start(); 33 hashID = t.hashCode(); 34 } 35 36 public void start(){ 37 38 t.start(); 39 } 40 41 public int getID(){ 42 return hashID; 43 } 44 45 public void run(){ 46 47 Thread current = Thread.currentThread(); 48 //System.out.println*

clxxxviii

Page 189: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

49 Integer friendID = new Integer(current.hashCode()); 50 while(whiteList.contains(friendID)){ 51 current = Thread.currentThread(); 52 friendID = new Integer(current.hashCode()); 53 String s = this.getResourceAsString(resource); 54 int nextIndex = 6; 55 int index = s.indexOf('\n'); 56 57 nextIndex = s.indexOf('\n',index+1); 58 59 int lastIndex = s.lastIndexOf('\n'); 60 61 int begin = -2; 62 int end = index; 63 64 String c1 = ""; 65 String c2 = ""; 66 String timeStamp = ""; 67 long currentTS = 0; 68 69 while(index<lastIndex && whiteList.contains(friendID)){ 70 current = Thread.currentThread(); 71 friendID = new Integer(current.hashCode()); 72 Point wp = null; 73 String temp = s.substring(begin+2,end); 74 temp = compact(temp); 75 if(temp.equals("")){ //na kraju ce temp da bude prazno 76 index = lastIndex+1; 77 } else { 78 temp = compact(temp); 79 int comma = temp.indexOf(','); 80 c1 = temp.substring(0,comma); 81 int nextComma = temp.indexOf(',',comma+1); 82 c2 = temp.substring(comma+1,nextComma); 83 timeStamp = temp.substring(nextComma+1,temp.length()); 84 currentTS = Long.parseLong(timeStamp); 85 begin = index-1; 86 end = nextIndex; 87 index = nextIndex; 88 nextIndex = s.indexOf('\n',nextIndex+1); 89 90 wp = null; 91 if(!c1.equals("")){

clxxxix

Page 190: Defect prevention techniques

Zarko Acimovic

92 wp = new Point(c2,c1,resource,"","",true); 93 wp.setImage("blanco"); 94 } 95 } 96 try{ 97 Thread.sleep(1000); 98 }catch(Exception e){} 99 if(wp!=null && whiteList.contains(friendID)){ 100 mob.setDrawablePoints(); 101 mob.updateFriend(friendID,wp); 102 if(first==false) { 103 mb.setBackground(wp); 104 first=true; 105 } 106 ic.repaint(); 107 } 108 } 109 } 110 } 111 112 113 114 /** Blanco characters are possible to occur in names of pictures; 115 * Integer representations of blanko characters are 9 and 32 116 * Also, characters with integer representation between 0 and 33 117 * can not be printed out in WSDD console, so I excluded them too 118 */ 119 public String compact(String s){ 120 int k = s.length(); 121 //System.out.println("Length of s is "+s.length()); 122 char[] d = s.toCharArray(); 123 String ret = ""; 124 for(int i=0; i<d.length; i++){ 125 int temp = (int)d[i]; 126 if(temp>32) ret+=d[i]; 127 } 128 //System.out.println("Length of ret is "+ret.length()); 129 int kk = ret.length(); 130 //if (kk!=k) System.out.println("Bugger is: "+s); 131 return ret; 132 } 133 134 public String compactFine(String s){ 135 int k = s.length(); 136 //System.out.println("Length of s is "+s.length()); 137 char[] d = s.toCharArray(); 138 String ret = ""; 139 for(int i=0; i<d.length; i++){ 140 int temp = (int)d[i];

cxc

Page 191: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

141 if(temp!=32 && temp!=9) ret+=d[i]; 142 } 143 //System.out.println("Length of ret is "+ret.length()); 144 int kk = ret.length(); 145 //if (kk!=k) System.out.println("Bugger is: "+s); 146 return ret; 147 } 148 149 public String getResourceAsString(String resource){ 150 InputStream is = null; 151 try{ 152 is = this.getClass().getResourceAsStream(resource); 153 }catch(Exception e) { 154 //a.setString("There is no such resource"); 155 //d.setCurrent(a); 156 } 157 158 //conversion of resource into string 159 String s = ""; 160 char m =' '; 161 162 try{ 163 m = (char)is.read(); 164 }catch(Exception e){} 165 166 while(m!=65535){ 167 s+=m; 168 try{ 169 m = (char)is.read(); 170 }catch(Exception e){} 171 } 172 try{ 173 is.close(); 174 }catch(Exception e){} 175 176 177 s=compactFine(s); 178 return s; 179 } 180 181 public void setFirst(){ 182 first = false; 183 } 184 185 }

cxci

Page 192: Defect prevention techniques

Zarko Acimovic

6 DESIGN DEFECTS DETECTED BY ARGOUML

15.3. Class Selection

15.3.1. Wrap DataType

15.3.2. Reduce Classes in namespace <namespace>

15.3.3. Clean Up Diagram

15.4. Naming

15.4.1. Resolve Association Name Conflict

15.4.2. Revise Attribute Names to Avoid Conflict

15.4.3. Change Names or Signatures in a model element

15.4.4. Duplicate End (Role) Names for an Association

15.4.5. Role name conflicts with member

15.4.6. Choose a Name (Classes and Interfaces)

15.4.7. Name conflict in a namespace

15.4.8. Choose a Unique Name for a model element (Classes and Interfaces)

15.4.9. Choose a Name (Attributes)

15.4.10. Choose a Name (Operations)

15.4.11. Choose a Name (States)

15.4.12. Choose a Unique Name for a (State related) model element

15.4.13. Revise Name to Avoid Confusion

15.4.14. Choose a Legal Name

15.4.15. Change a model element to a Non-Reserved Word

15.4.16. Choose a Better Operation Name

15.4.17. Choose a Better Attribute Name

15.4.18. Capitalize Class Name

cxcii

Page 193: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

15.4.19. Revise Package Name

15.5. Storage

15.5.1. Revise Attribute Names to Avoid Conflict

15.5.2. Add Instance Variables to a Class

15.5.3. Add a Constructor to a Class

15.5.4. Reduce Attributes on a Class

15.6. Planned Extensions

15.6.1. Operations in Interfaces must be public

15.6.2. Interfaces may only have operations

15.6.3. Remove Reference to Specific Subclass

15.7. State Machines

15.7.1. Reduce Transitions on <state>

15.7.2. Reduce States in machine <machine>

15.7.3. Add Transitions to <state>

15.7.4. Add Incoming Transitions to <model element>

15.7.5. Add Outgoing Transitions from <model element>

15.7.6. Remove Extra Initial States

15.7.7. Place an Initial State

15.7.8. Add Trigger or Guard to Transition

15.7.9. Change Join Transitions

15.7.10. Change Fork Transitions

15.7.11. Add Choice/Junction Transitions

15.7.12. Add Guard to Transition

15.7.13. Clean Up Diagram

15.7.14. Make Edge More Visible

15.7.15. Composite Association End with Multiplicity >1

15.8. Design Patterns

cxciii

Page 194: Defect prevention techniques

Zarko Acimovic

15.8.1. Consider using Singleton Pattern for <class>

15.8.2. Singleton Stereotype Violated in <class>

15.8.3. Nodes normally have no enclosers

15.8.4. NodeInstances normally have no enclosers

15.8.5. Components normally are inside nodes

15.8.6. ComponentInstances normally are inside nodes

15.8.7. Classes normally are inside components

15.8.8. Interfaces normally are inside components

15.8.9. Objects normally are inside components

15.8.10. LinkEnds have not the same locations

15.8.11. Set classifier (Deployment Diagram)

15.8.12. Missing return-actions

15.8.13. Missing call(send)-action

15.8.14. No Stimuli on these links

15.8.15. Set Classifier (Sequence Diagram)

15.8.16. Wrong position of these stimuli

15.9. Relationships

15.9.1. Circular Association

15.9.2. Make <association> Navigable

15.9.3. Remove Navigation from Interface via <association>

15.9.4. Add Associations to <model element>

15.9.5. Remove Reference to Specific Subclass

15.9.6. Reduce Associations on <model element>

15.9.7. Make Edge More Visible

15.10. Instantiation

15.11. Modularity

15.11.1. Classifier not in Namespace of its Association

15.11.2. Add Elements to Package <package>

cxciv

Page 195: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

15.12. Expected Usage

15.12.1. Clean Up Diagram

15.13. Methods

15.13.1. Change Names or Signatures in <model element>

15.13.2. Class Must be Abstract

15.13.3. Add Operations to <class>

15.13.4. Reduce Operations on <model element>

15.14. Code Generation

15.14.1. Change Multiple Inheritance to interfaces

15.15. Stereotypes

15.16. Inheritance

15.16.1. Revise Attribute Names to Avoid Conflict

15.16.2. Remove <class>'s Circular Inheritance

15.16.3. Class Must be Abstract

15.16.4. Remove final keyword or remove subclasses

15.16.5. Illegal Generalization

15.16.6. Remove Unneeded Realizes from <class>

15.16.7. Define Concrete (Sub)Class

15.16.8. Define Class to Implement <interface>

15.16.9. Change Multiple Inheritance to interfaces

15.16.10. Make Edge More Visible

15.17. Containment

15.17.1. Remove Circular Composition

15.17.2. Duplicate Parameter Name

15.17.3. Two Aggregate Ends (Roles) in Binary Association

15.17.4. Aggregate End (Role) in 3-way (or More) Association

15.17.5. Wrap DataType

cxcv

Page 196: Defect prevention techniques

Zarko Acimovic

9 EXAMPLES OF DESIGN DEFECTS IN ARGOUML

cxcvi

Page 197: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

cxcvii

Page 198: Defect prevention techniques

Zarko Acimovic

cxcviii

Page 199: Defect prevention techniques

Software Defects Prevention Techniques – Example Project

ABOUT THE AUTHOR

Zarko Acimovic was born in 1977 in Belgrade, SERBIA. He obtained his BSc in Computer Science at University of Belgrade, School of Electrical Engineering. Zarko Acimovic maintains Facebook page for promoting automated testing of software architecture and software design http://www.facebook.com/AutomatedTesting

cxcix