Anda di halaman 1dari 47

Good Programming skills

To develop Skills to write programs that are more understandable, following good programming practices Code Refactoring to improve quality of code Introduction to Defensive Programming

The Importance of Good Programming Skills


The gap between the best software engineering practice and the average practice is very wide - perhaps wider than in any other engineering discipline. A tool that disseminates good practice would be important. - Fred Brooks in "The Mythical Man-Month
In a survey in TCS, 89 Project Leaders & Group Leaders ranked important skills for entrants to ILP as follows:

Good Programming Practices Process Mindset Communication Skills Adaptability & Teamwork Concern for Quality Knowledge of Core Computer Science Topics

A true project experience


A TCS project well appreciated by client for Correctness On Time Delivery Good project Managements

Customer requested enhancements for the well delivered product but later complained that enhancement requests were pending with TCS for months.
Root Cause : Poor Understandability of code

Improving Understandability Advantages


Self-review is easier leading to less defects Debugging takes less time Another developer will find it easier to maintain your program

1.Follow Standards
All team members following the same standards, makes more understandable your code Follow the ILP coding guidelines and build this habit. Each project will have its own coding guidelines based on TCS coding guidelines

A Problem An employee less than 1 year of experience is a fresher.1-2 years of experience is a Junior Engineer.2-5 is a lead engineer.5-8 is a manager.8-15 a senior manager and 15 and above General manager. A fresher is eligible only for basic salary. A Junior Engineer is eligible for HRA as well. A lead engineer is eligible for HRA and LTA. All the managers are eligible for Medical allowances also. General managers are eligible for special allowance along with all the other allowances. Calculate the salary of an employee. HRA is 10% of basic salary, LTA is 2%,Medical allowance 15% and special allowance is 20% of basic salary.

2. Refactor to Improve Understandability

A routine should perform one and only one operation.


Describe everything the routine does In the routine's name The routine has too many parameters (9) , parameters >7 is not recommended Some of routines parameters unused (age) The routines parameters are poorly ordered Avoid unnecessary parameters (allow1,allow2,allow3,allow4)

The routines name doesnt convey anything(getitwork21( )) The routine doesn't have a single purpose (It finds the employee type and computes salary) The routine has a bad layout. (The physical organization of the code on the page gives few hints about its logical organization) The variable/parameter names not meaningful. (allow1,e,Type) The routine isn't documented. The routine doesn't defend itself against bad data. (If basic salary is given as negative, it doesn't throw any error )

With people first in mind, refactor the interface to meet the standards discussed void getItwork21(String Type,int allow2,int bSAL,int allow1,int e,int allow3, int allow4,int age,String name)

We did code refactoring to improve understandability, We can also refactor code to

remove duplicate code enhance robustness adaptability, re-use or to apply some creative insight.

Refactoring Saves maintenance costs Makes it more comfortable for the maintainer. These factors must be balanced with the effort and time required for the refactoring.

Data-Level Statement-Level Routine-Level

Source: Code Complete, Second Edition by Steve McConnell

Specific Refactorings
Data-Level Replace a magic number with a named constant Rename a variable with a clearer or more informative name Move an expression inline Replace an expression with a routine Introduce an intermediate variable Convert a multiuse variable to multiple single-use variables Use a local variable for local purposes rather than a parameter

Specific Refactorings
Statement-Level Decompose a boolean expression Move a complex boolean expression into a well-named boolean function Consolidate fragments that are duplicated within different parts of a conditional Use break or return instead of a loop control variable Return as soon as you know the answer instead of assigning a return value within nested if-then-else statements

Specific Refactorings
Routine-Level Extract routine/method Move a routine s code inline Substitute a simple algorithm for a complex algorithm Add/Remove a parameter Separate query operations from modification operations Combine similar routines by parameterizating them Separate routines whose behavior depends on parameters passed in

Refactor safely
Refactor one at a time Save the code before refactoring Retest after each refactoring Add test cases Review the changes Keep refactoring small Make frequent checkpoints Adjust your approach depending on the risk of the refactoring

Source: Code Complete, Second Edition by Steve McConnell

3. Comment Judiciously

Every function must provide its purpose For java, Javadoc is a good choice for documentation as- it is generally adequateeasy to understand and use- it is popular

Improving Understandability
Comment judiciously Sample method comment /** Calculates the Salary based on years of experience and basic salary @param experienceYears - the years of experience of an employee @param basicSalary - the basic salary of an employee @return the total salary of an employee */ public static double calcSalary(int experienceYears,int basicSalary){

Improving code correctness Why?

Construction accounts for about 75 percent of the errors on small projects and 50 to 75 percent on medium and large projects. Any activity that accounts for 50 to 75 percent of the errors presents a clear opportunity for improvement - Steve McConnell in Code Complete

Improving Code Correctness Defending Against Bad data


Defensive programming Similar to defensive driving style!

Check the values of all data from external sources Check the values of all routine input parameters Check all return values from all methods to be in the acceptable range Always have an otherwise or default clause in conditional statements to catch those cases that are not expected and so not processed Ensure that your code is not used inappropriately Source: Code Complete, Second Edition by Steve McConnell

Defensive Programming
Why defensive programming helps ?

Programming is complex and a major challenge. With the best of intentions, we may still expect problems

Defensive programming techniques help us discover a defect as close as feasible.

ASSENT JAVA STANDARDS CHECKING TOOL


ASSENT is a specification-driven standards enforcement tool that automatically checks for conformance of an input program to the programming standards or guidelines for the language. ASSENT uses flow analysis techniques to detect runtime properties statically. This enables better and more robust standards checking. By catching the non-conformances earlier in the development life cycle, ASSENT improves the quality of the standards checking and reduces the cost of software development and maintenance.

ASSENT
ASSENT combines sophisticated semantic analysisbased standards-checking with an easy-to-use interface which:

Allows checking through the source files and find any violations to the standard Generates HTML reports of the non-conformances and allows viewing and printing of the reports

ASSENT Start-up
Choose the option Programs-ASSENT-ASSENT JAVA Standards Checker from the Start menu. The following screen appears:

Project Workspace Window Description


The Project Workspace window is a three-pane window as seen in previous slide. The contents of the three panes of the Project Workspace window are as given below: Project pane-The upper-left pane that provides information of the files in the project. Project File View pane-The upper-right pane that acts as a display for the contents of the files in the project.. Project Output View pane-The lower-pane that displays the current status of the tool run on the project. This provides information on how far the tool has reached in checking the current project for compliance to the programming standard.

Note:-Root/Project node represents the project and bears the name of the project. It provides a hierarchical (tree) view of the source files in the project. These files represent the application that is to be checked by the tool. ASSENT checks for conformance of a single compilation unit or an entire project. The FILES node can contain: A .java , a .jsp file or a set of .java files, .jsp files

Adding Program File(s) to a Project


To add program file(s) in a project, 1. Click Insert Files from the Project menu or press [CTRL + INSERT].

Adding Program File(s) to a Project contd..


The Insert Files into Project dialog box appears.

Adding Program File(s) to a Project contd..


2. Select the drive from the Look-in drop-down list box and the directory from the browser view. 3. Choose the appropriate file type from the Files of Type list. 4. If you check the Insert files from all subfolders checkbox, files from all the subfolders of the selected folder will get added in to the project. 5. If you do not check the Insert files from all subfolders checkbox, files from the selected folder will be added in to the project. 6. Click Add. All the respective files will be added to the project pane.

Compliance Check

After adding the files to a project, you can use ASSENT to check your program for conformance to the standard for the language. ASSENT checks conformance of a single compilation unit or an entire program. The input to the tool can be a file or a set of files, i.e., a project file.

To check a program/project for compliance using ASSENT Standards Checker


Click CheckWith- default from the Standards menu of the ASSENT Start-up screen to check on the whole project with the desired rule set.

To check a specific file(s) for compliance using ASSENT Standards Checker


2. Click CheckWith-default in the right-click of the selected file(s) to check specific file(s) with the desired rule set.

The lower pane of the Project screen shows a scrolling display of the results of the Standards Checker at each stage of compliance checking.

A success message is displayed as ASSENT JAVA finished standards checking successfully. Click OK.

Generating Non-Conformance Reports


After you run ASSENT on the project to check the non-conformances, you can generate nonconformance reports in the HTML and Excel form. To generate reports, select Generate Report or press [CTRL+G] from the Reports menu of the ASSENT Start-up screen. The report is generated in accordance with the Report settings.

The following message is displayed.HTML Report generated successfully. Would you like to view the report". Click Yes.

The HTML report is generated with various level of severity and the Line number of the Violation in a new window.

References
Code Complete, Second Edition by Steve McConnell Good Programming Practices & Skills by Abbas K. Sutarwala

Anda mungkin juga menyukai