Best Practices. Contents Bad Practices Good Practices.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Coding Standard: General Rules 1.Always be consistent with existing code. 2.Adopt naming conventions consistent with selected framework. 3.Use the same.
Written by: Dr. JJ Shepherd
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Internal Documentation Conventions. Kinds of comments javadoc (“doc”) comments describe the user interface: –What the classes, interfaces, fields and.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler.
Java 1.5 & Effective Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Subclasses. Inheritance class Animal { int row, column; // will be inherited private Model model; // private prevents inheritance Animal( ) {... } //
Algorithm Programming Coding Advices Bar-Ilan University תשס " ו by Moshe Fresko.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Jun 16, 2014IAT 2651 Debugging. Dialectical Materialism  Dialectical materialism is a strand of Marxism, synthesizing Hegel's dialectics, which proposes.
Exceptions1 Syntax, semantics, and pragmatics. Exception create If (some error){ throw new SomeException(”some message”); } Exceptions2.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Lecture objectives  Differences between Java and C#  Understand and use abstract classes  Casting in Java: why is it important?  Master exceptions.
Java Implementation: Part 3 Software Construction Lecture 8.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
The Java Programming Language
Refactoring Improving the structure of existing code Refactoring1.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Exceptions Handling Exceptionally Sticky Problems.
Java Coding Standards and Best Practices Coding Standards Introduction: After completing this chapter, you will able to keep your code up to standards.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
Refactoring1 Improving the structure of existing code.
Programming in Java Dr. M. Ahmadzadeh. Course Outline (subject to tiny changes) I will cover the following but not necessarily in this order. –Strings.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Object Oriented Software Development
1 CSC/ECE 517 Fall 2010 Lec. 3 Overview of Eclipse Lectures Lecture 2 “Lecture 0” Lecture 3 1.Overview 2.Installing and Running 3.Building and Running.
Software Engineering CS3003 Lecture 4 Code bad smells and refactoring.
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Inheritance and Access Control CS 162 (Summer 2009)
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
GoodOO Programming Practice in Java © Allan C. Milne v
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Error Handling Tonga Institute of Higher Education.
Refactoring1 Improving the structure of existing code.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Effective Java, Chapter 9: Exceptions Items Last modified Fall 2012 Paul Ammann.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Java Best Practices Java Fundamentals & Object-Oriented Programming MELJUN CORTES, MBA,MPA,BSCS.
Principles and examples
More Sophisticated Behavior
Module Road Map Refactoring Why Refactoring? Examples
Improving the structure of existing code
Effective Java, 3rd Edition Chapter 10: Exceptions
Review of Previous Lesson
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Effective Java, Chapter 9: Exceptions
CMPE212 – Reminders Assignment 2 due next Friday.
CS 240 – Advanced Programming Concepts
Presentation transcript:

Best Practices

Contents Bad Practices Good Practices

Bad Practices

Duplicate Code! Every time you need to make a change in the routine, you need to edit it in several places. – Called “Shotgun Surgery”. Follow the “Once and Only Once” rule. Don’t copy-paste code!

Accessible Fields Fields should always be private except for constants. Accessible fields cause tight coupling. Accessible fields are corruptible. If a field needs to be accessed, use “get” and “set” convention.

Using Magic Numbers Magic numbers are not readable, and can lead to “Shotgun Surgery”. for (int i = 1; i =< 52; i++) { j = i + randomInt(53 - i) – 1 swapEntries(i, j) } Replace with constants. final int DECKSIZE = 52; for (int i = 1; i =< DECKSIZE; i++) { j = i + randomInt(DECKSIZE i) – 1 swapEntries(i, j) }

Temporary Fields If a variable need not be shared across methods, make it local. private int x; int method() { x = 0;// if you forget to initialize, you're dead... // do some stuff return x; } int method() { int x = 0;... // do some stuff return x; }

Initializing Strings with “new” Don’t: String str = new String(“This is bad.”); Do: String str = “This is good.”;

Using floats and doubles for currency calculations Binary numbers cannot exactly represent decimals. Use BigDecimal for currency calculations. –...using the constructor that takes a String as a parameter.

Returning null Causes NullPointerExceptions. Instead, return… – empty objects – custom-made “Null Objects”

Subclassing for Functionality Implementation inheritance is difficult to debug. Ask yourself: “Is this a kind of…?” Alternatives: – Prefer interface inheritance. – Prefer composition over inheritance.

Empty Catch Block No indication that an exception has occurred!

Using Exceptions Unexceptionally Use exceptions only for exceptional conditions. Bad: try { obj = arr[index]; } catch (ArrayIndexOutOfBoundsException) { // do something } Good: if (index = arr.size()) { // do something } else { obj = arr[index]; }

Excessive Use of Switches Use of “if” and “switch” statements usually a sign of a breach of the “One Responsibility Rule”. Consider polymorphism instead.

instanceof If you’re using instanceof often, it probably means bad design. Consider adding an overridden method in supertype. instanceof should only be used – as validation prior to casting – when you have to used a poorly-written library

Static Methods Static methods are.. –...procedural They break encapsulation - the method should be part of the object that needs it –...not polymorphic You can't have substitution/pluggability. – You can't override a static method because the implementation is tied to the class it's defined in. Makes your code rigid, difficult to test.

System.exit Only use in stand-alone applications. For server applications, this might shut down the whole application container!

Good Practices

Validate Your Parameters The first lines of code in a method should check if the parameters are valid: void myMethod(String str, int index, Object[] arr) { if (str == null) { throw new IllegalArgumentException(“str cannot be null”); } if (index >= arr.size || index < 0) { throw new IllegalArgumentException(“index exceeds bounds of array”); } … }

Create Defensive Copies Create local copies, to prevent corruption. void myMethod (List listParameter) { List listCopy = new ArrayList(listParameter); listCopy.add(somevar);... }

Modify Strings with StringBuilder String objects are immutable. – You may think you’re changing a String, but you’re actually creating a new object. – Danger of OutOfMemoryErrors. – Poor peformance. StringBuilder is mutable. – All changes are to the same object.

Favor Immutability If your objects don’t change… easier to debug. Fields are private and final. No setters, only getters.

Prefer “final” for Variables Usually, variables / parameters do not need to change. Get into the habit of using final by default, and make a variable not final only when necessary.

Declare Variable Just Before Use Easier to read and refactor.

Initialize Variables Whenever Possible Helpful in debugging, makes it clear what initial value is. Makes sure you don’t use the variable before it’s ready for use.

Follow Code Conventions Improves readability – For other programmers. – For yourself. Readability means… – …less bugs. – …easier to debug.

Refer to Objects by Interfaces Maintainability - changes in implementation need only be done at a single point in code Polymorphism – implementation can be set at runtime. // bad: ArrayList list = new ArrayList(); list.add(somevar); // good: List list = new ArrayList(); list.add(somevar);

Consider Using Enums instead of Constants Constants: – Not typesafe – No namespace You often need to prefix constants to avoid collisions – Brittleness When you change the order, you need to change a lot of code. – Printed values are uninformative

Buffer I/O Streams Requesting OS for I/O resources is expensive. Buffering provides significant increase in performance.

Close Your I/O Streams If you don’t close, other applications may not be able to use the resource. Close using the “finally” block in a try-catch.

Design Close to Domain Code is easily traceable if it is close to the business it is working for. If possible, name and group your packages according to the use cases. – Easy to tell client %completion of feature. – If user reports a bug, easier to find where it is.

If You Override equals() Override hashcode() Always make sure that when equals() returns true, the two object have the same hashcode. Otherwise, data structures like Sets and Maps may not work. There are many IDE plug-ins and external libraries that can help you with this.

Write Self-Documenting Code Comments are important, but… …even without comments your code should be easily readable. Ask yourself: “If I removed my comments, can someone else still understand my code?”

Use Javadoc Liberally Provide as much documentation about your code as possible.

Bubble-Up Exceptions If code is not part of the user interface, it should not handle its own exceptions. It should be bubbled-up to presentation layer… Show a popup? Show an error page? Show a commandline message? Just log to an error log?

References “Effective Java” by Joshua Bloch Refactoring by Martin Fowler