Official Android Coding Style Conventions



Similar documents
Android Programming Basics

Android Programming: Installation, Setup, and Getting Started

Hadoop Streaming coreservlets.com and Dima May coreservlets.com and Dima May

Android Programming: 2D Drawing Part 1: Using ondraw

The Google Web Toolkit (GWT): The Model-View-Presenter (MVP) Architecture Official MVP Framework

Java with Eclipse: Setup & Getting Started

Virtual Machine (VM) For Hadoop Training

Map Reduce Workflows

Apache Pig Joining Data-Sets

JHU/EP Server Originals of Slides and Source Code for Examples:

The Google Web Toolkit (GWT): Declarative Layout with UiBinder Basics

For live Java EE training, please see training courses

Advanced Java Client API

Building Web Services with Apache Axis2

Session Tracking Customized Java EE Training:

HBase Key Design coreservlets.com and Dima May coreservlets.com and Dima May

Hadoop Distributed File System (HDFS) Overview

The Google Web Toolkit (GWT): Overview & Getting Started

HBase Java Administrative API

Localization and Resources

Software Development (CS2500)

Web Applications. Originals of Slides and Source Code for Examples:

CSE 308. Coding Conventions. Reference

Managed Beans II Advanced Features

HDFS Installation and Shell

Basic Java Syntax. Slides 2016 Marty Hall,

Dinopolis Java Coding Convention

Object-Oriented Programming in Java: More Capabilities

Install Java Development Kit (JDK) 1.8

Debugging Ajax Pages: Firebug

HDFS - Java API coreservlets.com and Dima May coreservlets.com and Dima May

Web Applications. For live Java training, please see training courses at

Handling the Client Request: Form Data

AppendixA1A1. Java Language Coding Guidelines. A1.1 Introduction

2011 Marty Hall An Overview of Servlet & JSP Technology Customized Java EE Training:

Some Scanner Class Methods

Servlet and JSP Filters

No no-argument constructor. No default constructor found

Form Validation. Server-side Web Development and Programming. What to Validate. Error Prevention. Lecture 7: Input Validation and Error Handling

Application Security

CS 241 Data Organization Coding Standards

Creating Java EE Applications and Servlets with IntelliJ IDEA

What servlets and JSP are all about

Getting Started: Creating a Simple App

Code convention document Argus-viewer

<Insert Picture Here> What's New in NetBeans IDE 7.2

MapReduce on YARN Job Execution

Java Application Developer Certificate Program Competencies

Java Program Coding Standards Programming for Information Technology

Getting Started with the Internet Communications Engine

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Building a Multi-Threaded Web Server

C Coding Style Guide. Technotes, HowTo Series. 1 About the C# Coding Style Guide. 2 File Organization. Version 0.3. Contents

Hadoop Introduction coreservlets.com and Dima May coreservlets.com and Dima May

Creating Web Services Applications with IntelliJ IDEA

Rapid Application Development. and Application Generation Tools. Walter Knesel

Software Engineering Techniques

Hypercosm. Studio.

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

Building and Using Web Services With JDeveloper 11g

Hello World. by Elliot Khazon

Creating a 2D Game Engine for Android OS. Introduction

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Developing an Android App. CSC207 Fall 2014

Vim, Emacs, and JUnit Testing. Audience: Students in CS 331 Written by: Kathleen Lockhart, CS Tutor

Lecture 5: Java Fundamentals III

Software Development Interactief Centrum voor gerichte Training en Studie Edisonweg 14c, 1821 BN Alkmaar T:

ELET4133: Embedded Systems. Topic 15 Sensors

OUR COURSES 19 November All prices are per person in Swedish Krona. Solid Beans AB Kungsgatan Göteborg Sweden

Android Studio Application Development

Moving from CS 61A Scheme to CS 61B Java

Java Code Conventions. September 12, 1997

How to build your first Android Application in Windows

3 Improving the Crab more sophisticated programming

10 Java API, Exceptions, and Collections

IOIO for Android Beginners Guide Introduction

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Kotlin for Android Developers

Computer Programming I

Approach of Unit testing with the help of JUnit

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Exception Handling In Web Development DevelopIntelligence LLC

& JSP Technology Originals of Slides and Source Code for Examples:

Mobile Application Development

CQCON 2013: five Sling features you should know

INTEGRATING MICROSOFT DYNAMICS CRM WITH SIMEGO DS3

Software Construction

Would You Like To Earn $1000 s With The Click Of A Button?

Taxi Service Coding Policy. Version 1.2

How to develop your own app

The Social Accelerator Setup Guide

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Fundamentals of Java Programming

DAVE Software Development Kit overview. Preparing the workbench. Creating a simple APP. Step 1: Create a new APP project

Tutorial #1. Android Application Development Advanced Hello World App

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

JavaScript: A Crash Course

Advantages. manage port forwarding, set breakpoints, and view thread and process information directly

Transcription:

2012 Marty Hall Official Android Coding Style Conventions Originals of Slides and Source Code for Examples: http://www.coreservlets.com/android-tutorial/ Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. 2012 Marty Hall For live Android training, please see courses at http://courses.coreservlets.com/. Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this Android tutorial. Available at public venues, or customized versions can be held on-site at your organization. Courses developed and taught by Marty Hall JSF 2, PrimeFaces, servlets/jsp, Ajax, jquery, Android development, Java 6 or 7 programming, custom mix of topics Ajax courses Customized can concentrate Java on 1 EE library Training: (jquery, Prototype/Scriptaculous, http://courses.coreservlets.com/ Ext-JS, Dojo, etc.) or survey several Courses developed and taught by coreservlets.com experts (edited by Marty) Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Spring, Hibernate/JPA, EJB3, GWT, Hadoop, SOAP-based and RESTful Web Services Developed and taught by well-known Contact author hall@coreservlets.com and developer. At public for details venues or onsite at your location.

Topics in This Section Why follow conventions? Valuable conventions Ones that are widely considered good practice for any Java project (based on general Java industry consensus) Tolerable conventions Ones that do no harm, but are of questionable value (in Marty s highly subjective opinion) Dubious conventions Ones that we would have been better off without (in Marty s highly subjective opinion) 5 2012 Marty Hall Overview Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

7 Official Android Code Conventions Required for Code contributed to Android project Used in All official tutorials and (supposedly) all source code Suggested for Code submitted to the app store Any Android project Details http://source.android.com/source/code-style.html Eclipse preferences file Downloadable from coreservlets.com from this section of the Android Tutorial. Sets spacing, brace style, and use of @Override 8 Pros and Cons of Following Conventions Pros Consistent with official tutorials and Android source More familiar to Android developers who join your team Cons Inconsistent with Java code you wrote before Less familiar to other Java developers Simply bothers you. Java developers often have strong personal preferences My recommendations Most conventions are best practices anyhow Definitely follow those Most others are neither worse nor better than alternatives Probably follow those A few are (arguably) bad or at least wrong in some situations Ignore those if the situation warrants it

2012 Marty Hall Conventions that are Good Standard Practice (For any Java project) Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Indentation: blocks that are nested more should be indented more Yes for(...) { for(...) { No for(...) { for(...) { 10

Indentation: blocks that are nested the same should be indented the same Yes for(...) { for(...) { No for(...) { for(...) { 11 Break Things into Small Pieces 12 Write short methods No official limit, but try to keep methods short and focused. Think often about how to refactor your code to break it into smaller and more reusable pieces. This is good advice in any language. This also shows why overly strict rules on the length of comments can be counter productive by encouraging developers to write long methods to avoid writing docs. Keep lines short They have a strict rule of 100 characters except for imports or comments that contain URLs or commands that cannot be broken up. Not sure 100 is the magic number, but short lines are good practice anyhow.

Follow Normal Capitalization Rules Classes start with uppercase letter public class SomeClass { Constants use all caps public static final double GOLDEN_RATIO = (1 + Math.sqrt(5.0))/2; Everything else starts with lowercase letter Instance variables, local variables, parameters to methods, package names Extra rule Use words for acronyms, not all uppercase geturl, not geturl This is good advice in Web apps also 13 Use JavaDoc 14 Use JavaDoc from the beginning Don t wait until the code is finished. Short comments are fine, but use some. Explain purpose and non-obvious behavior. Don t explain standard Java constructs. Document every class /** Represents a collection of Blahs. Used to **/ public class Foo { Document anything public Methods Constructors Instance variables (but very rare to have public ones) Review Oracle JavaDoc guidelines http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html

Use @Override 15 Use @Override when you override methods from parent class Won t be caught until run time public void oncreate(bundle savedinstancestate) { Will be caught at compile time @Override public void oncreate(bundle savedinstancestate) { Guidelines are silent regarding interfaces But, in Java 6 or later, I prefer to also use @Override when implementing methods from interface Use Other Standard Annotations when Warranted (but Rarely) @Deprecated If you use a deprecated method, add this annotation to your method. Also add @deprecated JavaDoc tag explaining why it was necessary to use deprecated code. Of course, try hard to avoid use of deprecated methods @SuppressWarnings Generic collections are prohibited from doing extra work at run time, so casting to generic type can cause warning that Java can t verify the types. Sometimes unavoidable @SuppressWarnings("unchecked") Other similar situations when making generic types Android guidelines require a TODO comment in these cases, saying why you cannot avoid the situation 16

Limit the Scope of Variables Use narrowest scope possible Variables should be declared in the innermost block that encloses all uses of the variable. E.g., if variable is only used inside if statement, declare it inside if statement. Yes if () { double d = somecalculation(); dosomethingwith(d); else { // No use of d No double d = 0; if () { else { 17 18 Initialize Local Variables when Declared Initialize (almost) all local variables Yes String s = "Hello"; No String s; s = "Hello"; Exception: try/catch blocks int n; try { n = Integer.parseInt(someString); catch(numberformatexception nfe) { n = 10;

Put Braces on Conditionals Always use braces for if statements Even if there is only one thing to do Yes if () { dosomething(); No if () dosomething(); Guidelines give small exception If there is only one thing to do and it is all on one line Tolerated (grudgingly?) if () dosomething(); 19 Use TODO Comments for Temporary Code Use // TODO: for code that needs to be changed later Situations Temporary fix OK but not great Works for small sizes, but bad performance in future when data sets get bigger. Examples: // TODO: Switch to a Map when you have more entries // TODO: Remove after UrlTable2 has been checked in Eclipse note Eclipse puts TODO in bold and puts check mark in left margin of code 20

Avoid Finalizers Do not use finalize() Idea finalize() gets called when an object is garbage collected, so you can do cleanup work then (such as closing socket connections) Problem No guarantee when (or even if) finalizer will be called Guidelines Don t use them. Good news Finalizers have long ago fallen out of favor, and many Java developers don t even know what they are. 21 2012 Marty Hall Conventions that Don t Hurt (No harm in following them, but their value is questionable) Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

23 Put Open Braces with Preceding Code Put { with previous line, not on its own line Yes public void foo() { if (...) { dosomething(); No public void foo() { if (...) { dosomething(); Indent 4 Spaces for Blocks Indent 4 spaces when starting a block Yes public void foo() { if (...) { dosomething(); No public void foo() { if (...) { dosomething(); 24

Indent 8 Spaces for Lines Indent 8 spaces when splitting a line Yes String s = somethingverylong(); No String s = somethingverylong(); 25 Fully Qualify Imports List each class name; don t use * Yes import android.widget.button; import android.widget.checkbox; import android.widget.edittext; No import android.widget.*; Exception Can use * for java or javax packages Permitted import java.util.*; 26

Order Import Statements 27 First Android packages import android.foo.bar; Second Third party packages import com.coreservlets.utils.randomutils; Third Standard java or javax packages import java.util.*; Within each group Alphabetical (uppercase Z before lowercase a) Separating groups Blank line between each major grouping Start JavaDoc Comments with 3 rd Person Verb Examples Yes Represents a Responds to mouse clicks with Deletes No This class This method Android s own docs are inconsistent Many (most?) classes start with This class or similar. E.g., View, Activity, LinearLayout 28

2012 Marty Hall Questionable Conventions (You would have been better off without them) Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Start Instance Variables with m (normal) or s (static) 30 Use m for non-public, non static fields m for member variable or data member Yes private String mfirstname; private boolean mismarried; No private String firstname; private boolean ismarried; Use s for static (non-final) fields Yes private static double sbiggestradius; No private static double biggestradius; Marty s opinion Results in less readable names with no real benefit

Impact of Naming Convention on Constructors Standard Style public class Person { public String firstname, lastname; public Person(String firstname, String lastname) { this.firstname = firstname; this.lastname = lastname; Android Style public class Person { public String mfirstname, mlastname; public Person(String firstname, String lastname) { mfirstname = firstname; mlastname = lastname; 31 Never Ignore Exceptions Avoid empty catch blocks Yes try { catch(someexception se) { dosomethingreal(); No try { catch(someexception se) { Marty s opinion Usually, but not always, a good rule 32

Why Ignoring Exceptions Rule is Too Strict Can make shorter code with same safety Android style int n; try { n = Integer.parseInt(); catch(numberformatexception nfe) { n = 10; Shorter style if you could ignore exceptions int n = 10; try { n = Integer.parseInt(); catch(numberformatexception nfe) { 33 Why Ignoring Exceptions Rule is Too Strict (Continued) Sometimes there is nothing to be done try { Thread.sleep(); catch(interruptedexception ie) { // What could you do here? dosomethingafterthepause(); 34

Don t Catch Generic Exception List each Exception type Yes try { catch(exceptiontype1 et1) { catch(exceptiontype2 et2) { 35 No try { catch(exception e) { Why Generic Exception Rule is (Arguably) Too Strict Listing each type is almost always best So exceptions you didn t expect don t get caught there So real failure-handling is not obscured Sometimes combining is concise and safe E.g., if somestring could be null, you could have either NumberFormatException or NullPointerException. But, in both cases, you just want to use original value for n. int n = 10; try { n = Integer.parseInt(someString); catch(exception e) { 36

2012 Marty Hall Wrap-Up Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Summary Strictly follow conventions that reflect widely accepted best practices Also, familiarize yourself with best practices. All developers who have worked with Java more than two years full time should read Josh Bloch s Effective Java (2 nd Edition). Even experts will learn something new and valuable For other conventions, if you don t strongly object, follow the conventions anyhow Even if you don t see any real value If convention really bothers you, ignore it Assuming it is not in category of generally accepted best practices. Personal taste plays role in many of them. 38

2012 Marty Hall Questions? JSF 2, PrimeFaces, Java 7, Ajax, jquery, Hadoop, RESTful Web Services, Android, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training. Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jquery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.