Showing posts with label Coding practice. Show all posts
Showing posts with label Coding practice. Show all posts

Tuesday, 29 March 2016

What is Refactoring ?


Refactoring is a process of changing a software system in such a way that it does not alter external behavior of code yet improves internal structure.
It's a disciplined way to clean up code that minimizes the chances of introducing bugs.

When you refactor, you are improving the design of code after it has been written.
Ideally, in a perfectly written computer program, with a perfectly designed computer language, with a perfect IDE, it should be possible to change any line / element of the program in isolation without having to make any supporting changes elsewhere.
The program should still function in a reasonable way. For example, you should be able to change the allowable bounds on a field variable in one line of code (which might result in it internally being promoted from int to long), without having to manually adjust any other code.
The basic principle is you should have to tell a computer any one fact, or decision in only one place.
For example, you should have to tell a program which colour scheme to use inprecisely one and only one place, and by "one place" I mean one line of code.

Some of the most useful refactorings are : 

Extract Method
I highlight a block of code that might be many line or just an expression. It then turns it into a method, figures out what the parameters need to be, and what type it returns. It then replaces the code with a call to the new method. It then finds similar code snippets and, with permission, also converts them to calls the new method.

Introduce constant
Converts literals to named constants. You have to give it some help to decide which instances to convert.

Change signature
Add, remove, rename, reorder the parameters of a method and automatically modify all invocations to the new rules.

Global rename
Most common refactoring. It drives the decision of what code belongs where. All IDEs renames with knowledge of Java syntax, so you don’t accidentally rename unrelated local variables with the same name. Lets you review which comments to rename. Lets you also rename similarly named variables and method in the same pop.

Pull up
Move a method or field from subclass to its superclass and make necessary adjustments.
It will let you control just how much of its attached baggage of fields and methods you move with it.

Push down
Move a method or field from a superclass to one of its subclasses.

Generify
Add generics to a class.

Friday, 25 March 2016

Open source Static code analyzers for Java



FindBugs
  • can analyze bytecode (.class files) as well as Java source files.
  • can detect a variety of common coding mistakes, including thread synchronization problems, misuse of API methods, etc.
  • Plugins : eclipse

PMD
  • scans Java source code to looks for potential problems like :
    • Unused local variables
    • Empty catch blocks
    • Unused parameters
    • Empty 'if' statements
    • Duplicate import statements
    • Unused private methods
    • Classes which could be Singletons
    • Short/long variable and method names
  • Plugins : eclipse

CheckStyle
  • help to write Java code that adheres to a coding standard 
  • automates the process of checking Java code
  • Ideal for projects that want to enforce a coding standard
  • Highly configurable and can be made to support almost any coding standard 
    • An example configuration file is supplied supporting the Sun Code Conventions.
    • Other sample configuration files are supplied for other well known conventions.
  • Plugins : eclipse, CruiseControl

Sonar
  • Continuous quality control tool
  • Continuous inspection engine
  • used to manage the technical debt (unittests, complexity, duplication, design, comments, coding standards and potential problems)
  • can be integrated in your existing continuous integration tools


QALab
  • consolidates data from Checkstyle, PMD, FindBugs and Simian and displays it in one consolidated view
  • keeps a track of the changes over time, thereby allowing you to see trends over time
  • You can check weather the number of violations has increased or decreased
    • on a per file basis, or 
    • for the entire project.
  • Also plots charts of this data
  • plugs into maven or ant

JDepend
  • checks package dependencies and cycle dependencies in order to manage and control them
  • checks and generates design quality metrics for each Java package 
  • allows you to automatically measure the quality of a design in terms of its extensibility, reusability, and maintainability
  • Plugin : eclipse

UCDetector - Unecessary Code Detector
  • Open Source eclipse plugIn tool
  • finds unnecessary (dead) java code 
  • Also tries to make code final, protected or private
  • finds cyclic dependencies between classes

Hammurapi
  • Open source code inspection tool
  • have 100 inspectors which inspect different aspects of code : Compliance with EJB specification, threading issues, coding standards, and much more.

Dependency Finder
  • extracts dependencies and OO metrics from Java class files produced by most Java compilers.

JDiff
  • A Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.
  • Very useful for describing exactly what has changed between two releases of a product.
    • Only the API of each version is compared.
    • does not compare what the source code does when executed

JarAnalyzer
  • A dependency management tool for .jar files
  • analyzes all .jar in a given directory and identify the dependencies between each
  • Output formats include xml, with a stylesheet included to transform it to html, and GraphViz DOT
    • produces a visual component diagram showing the relationships between .jar files
    • The XML output includes important design metrics such as Afferent and Efferent coupling, Abstractness, Instability, and Distance.
  • There is also an Ant task available that allows you to include JarAnalyzer as part of your build script.

Spoon
  • A Java program processor
  • provides a complete and fine-grained Java metamodel where any program element (classes, methods, fields, statements, expressions...) can be accessed both for reading and modification
  • ensures that your programs respect some programming conventions or guidelines, or for program transformation
  • uses a pure-Java template engine

JBoss Tattletale
  • A tool that can help you get an overview of the project
  • recursive scan a directory for JAR files and generate linked and formatted HTML reports

JCSC
  • A powerful tool to check source code against a highly definable coding standard and potential bad code
    • Naming conventions for class, interfaces, fields, parameter etc.
    • Structural layout of the type (class/interface) can be defined
      • Like, where to place fields, either before or after the methods and in which order.
      • The order can be defined through the visibility or by type (instance, class, constant). The same is applicable for methods.
      • Each of those rules is highly customizable.
  • Readability is enhanced by defining where to put white spaces in the code and when to use braces.
  • Correct JavaDoc can be enforced and various levels.
  • can finds weaknesses in the the code , potential bugs like : 
    • empty catch/finally block
    • switch without default
    • throwing of type 'Exception'
    • slow code etc.

Classycle
  • analyses the static class and package dependencies in Java applications or libraries
  • helps to find cyclic dependencies between classes or packages 
  • searches for unwanted class dependencies described in a dependency definition file 
    • Dependency checking helps to monitor whether certain architectural constrains are fulfilled or not.

XRadar
  • An open extensible code report tool 
  • produces HTML/SVG reports of the systems current state and the development over time 
  • uses DependencyFinder, JDepend, PMD, PMD-CPD, JavaNCSS, Cobertura, Checkstyle, XSource, JUnit, Java2HTML, ant and maven

Macker
  • A build-time architectural rule checking utility for Java developers
  • helps keep code clean and consistent
  • Flexible : You can define a rules file to suit a specific project's structure
    • Writing a rules file is part of the development process for each unique project

Condenser
  • finds and removes duplicated Java code
  • Locates duplicated code
    • Also automatically remove duplicated code (where it is safe to do so)

Dependometer
  • Static analysis of physical dependencies
  • validates dependencies against the logical architecture structuring the system into classes, packages, subsystems, vertical slices and layers and detects cycles between these structural elements
  • calculates a number of quality metrics on the different abstraction layers
  • reports any violations against the configured thresholds
  • Available for projects written in Java or C++

QJ-Pro
  • A comprehensive software inspection tool
  • Automatically inspect Java source code as developers write the programs
  • provides descriptive Java patterns explaining error prone code constructs and providing solutions for it.

JLint
  • checks Java code and find bugs, inconsistencies and synchronization problems by doing data flow analysis and building the lock graph

DoctorJ
  • analyzes Java code, in the following functional areas :
    • documentation verification
    • statistics generation
    • syntax analysis

Byecycle
  • An auto-arranging dependency analysis plugin for Eclipse
  • motivates to write good code

Java PathFinder (JPF)
  • verifes executable Java bytecode programs
  • JVM is used as an explicit state software model checker, systematically exploring all potential execution paths of a program to find violations of properties like deadlocks or unhandled exceptions
  • reports the entire execution path that leads to a defect
  • Well-suited to find hard-to-test concurrency defects in multithreaded program

Clirr
  • checks Java libraries for binary and source compatibility with older releases
  • You need to give it 2 sets of jar files and it dumps out a list of changes in the public API.
  • It's Ant task can be configured to break the build if it detects incompatible API changes.
  • In a continuous integration process, it can automatically prevent accidental introduction of binary or source compatibility problems.

Soot
  • A language manipulation and optimization framework
  • consists of intermediate languages for :
  • JavaSquale : A platform to manage software quality
  • Sonar : A continuous inspection engine to manage the technical debt (unittests, complexity, duplication, design, comments, coding standards andpotential problems)

Squale
  • A platform to manage software quality
  • Also available for other languages, using commercial analysis tools

Monday, 21 March 2016

What is CheckStyle and how to use the plugin in eclipse ?


Introduction to CheckStyle

Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard. It automates the process of checking Java code to spare humans of this boring (but important) task. This makes it ideal for projects that want to enforce a coding standard.

Checkstyle is highly configurable and can be made to support almost any coding standard. An example configuration file is supplied supporting the Sun Code Conventions. As well, other sample configuration files are supplied for other well known conventions.
Checkstyle can check many aspects of your source code.

Historically it' s main functionality has been to check code layout issues, but since the internal architecture was changed in version 3, more and more checks for other purposes have been added. Now Checkstyle provides checks that findclass design problems, duplicate code, or bug patterns like double checked locking.


Requirements
  • Eclipse3.3 or later
  • JRE/JDK1.5 or later


Installation
1. Download plugin

2. Update site
Start Eclipse and open a project.
Select "Help" - "Software Updates" - "Find and Install"
Click "Next", then click "New archived site" button.
Select the path of downloaded JAR file.
Click through the rest of the dialog boxes to install the plugin.

Using the Plugin
Right click on the java file or package or complete project and, choose Checkstyle - Check code with Checkstyle.
Open the file that you checked for violations. It will show the markers for the violations.
All the violations will be displayed in Checkstyle violations view along with their counts.


Bug description for CheckStyle


Customizing the rule set

Modify following file :
<eclipse-installation-dir> / Plugins / com.atlassw.tools.eclipse.checkstyle_4.4.3/sun_checks.xml

And comment following rules :
JavadocStyle, FinalParameters, GenericIllegalRegexp, LineLength, NoWhitespaceAfter,
NoWhitespaceBefore, WhitespaceAfter, WhitespaceAround, FileTabCharacter,TabCharacter
Example
<!--
<module name="JavadocStyle"/>
-->

Restart the eclipse and check for violations again.