- Notifications
You must be signed in to change notification settings - Fork74
kodecocodes/java-style-guide
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This style guide is different from other you may see, because the focus iscentered on readability for print and the web. We created this style guide tokeep the code in our tutorials consistent.
Our overarching goals areconciseness,readability andsimplicity.
You should also check out outSwiftandObjective-Cstyle guides too.
This style-guide is somewhat of a mash-up between the existing Java languagestyle guides, and a tutorial-readability focused Swift style-guide. The languageguidance is drawn from theAndroid contributors style guideand theGoogle Java Style Guide.Alterations to support additional readability in tutorials were inspired by theraywenderlich.com Swift style guide.
It is possible to get Android Studio to adhere to these style guidelines, viaa rather complex sequence of menus. To make it easier, we've provided a codingstyle that can be imported into Android Studio.
First, clone this repository and runinstall.sh.
Then, open Android Studio. To set this codestyle as the default, selectFile > Other Settings > Default Settings...:
InEditor > Code Style, choose theScheme to beraywenderlich.com:
From now on, projects you createshould follow the correct style guidelines.
- Nomenclature
- Declarations
- Spacing
- Getters & Setters
- Brace Style
- Switch Statements
- Annotations
- XML Guidance
- Language
- Copyright Statement
- Smiley Face
- Credit
On the whole, naming should follow Java standards.
Package names are alllower-case, multiple words concatenated together,withouthypens or underscores:
BAD:
com.RayWenderlich.funky_widget
GOOD:
com.raywenderlich.funkywidget
Written inUpperCamelCase. For exampleRadialSlider.
Written inlowerCamelCase. For examplesetValue.
Written inlowerCamelCase.
Static fields should be written inuppercase, with an underscore separatingwords:
publicstaticfinalintTHE_ANSWER =42;
As distasteful as it is, field naming should follow the Android source codenaming conventions:
- Non-public, non-static field names start with an
m. - Static field names start with an
s.
For example:
publicclassMyClass {publicstaticfinalintSOME_CONSTANT =42;publicintpublicField;privatestaticMyClasssSingleton;intmPackagePrivate;privateintmPrivate;protectedintmProtected;}
Note: You can set Android Studio to follow this convention. See this SOlink for detailshttp://stackoverflow.com/questions/22732722/intellij-android-studio-member-variable-prefix
Written inlowerCamelCase.
Single character values to be avoided except for temporary looping variables.
In code, acronyms should be treated as words. For example:
BAD:
XMLHTTPRequestStringURLfindPostByID
GOOD:
XmlHttpRequestStringurlfindPostById
Access level modifiers should be explicitly defined for classes, methods andmember variables.
Prefer single declaration per line.
BAD:
Stringusername,twitterHandle;
GOOD:
Stringusername;StringtwitterHandle;
Exactly one class per source file, although inner classes are encouraged wherescoping appropriate.
Enum classes should be avoided where possible, due to a large memory overhead.Static constants are preferred. Seehttp://developer.android.com/training/articles/memory.html#Overheadfor further details.
Enum classes without methods may be formatted without line-breaks, as follows:
privateenumCompassDirection {EAST,NORTH,WEST,SOUTH }
Spacing is especially important in raywenderlich.com code, as code needs to beeasily readable as part of the tutorial. Java does not lend itself well to this.
Indentation is using spaces - never tabs.
Indentation for blocks uses 2 spaces (not the default 4):
BAD:
for (inti =0;i <10;i++) {Log.i(TAG,"index=" +i);}
GOOD:
for (inti =0;i <10;i++) {Log.i(TAG,"index=" +i);}
Indentation for line wraps should use 4 spaces (not the default 8):
BAD:
CoolUiWidgetwidget =someIncrediblyLongExpression(that,reallyWouldNotFit,on,aSingle,line);
GOOD:
CoolUiWidgetwidget =someIncrediblyLongExpression(that,reallyWouldNotFit,on,aSingle,line);
Lines should be no longer than 100 characters long.
There should be exactly one blank line between methods to aid in visual clarityand organization. Whitespace within methods should separate functionality, buthaving too many sections in a method often means you should refactor intoseveral methods.
For external access to fields in classes, getters and setters are preferred todirect access of the fields. Fields should rarely bepublic.
However, it is encouraged to use the field directly when accessing internally(i.e. from inside the class). This is a performance optimization recommendedby Google:http://developer.android.com/training/articles/perf-tips.html#GettersSetters
Only trailing closing-braces are awarded their own line. All others appear thesame line as preceding code:
BAD:
classMyClass{voiddoSomething() {if (someTest) {// ... }else {// ... } }}
GOOD:
classMyClass {voiddoSomething() {if (someTest) {// ... }else {// ... } }}
Conditional statements are always required to be enclosed with braces,irrespective of the number of lines required.
BAD:
if (someTest)doSomething();if (someTest)doSomethingElse();
GOOD:
if (someTest) {doSomething();}if (someTest) {doSomethingElse(); }
Switch statements fall-through by default, but this can be unintuitive. If yourequire this behavior, comment it.
Alway include thedefault case.
BAD:
switch (anInput) {case1:doSomethingForCaseOne();case2:doSomethingForCaseOneOrTwo();break;case3:doSomethingForCaseOneOrThree();break;}
GOOD:
switch (anInput) {case1:doSomethingForCaseOne();// fall throughcase2:doSomethingForCaseOneOrTwo();break;case3:doSomethingForCaseOneOrThree();break;default:break;}
Standard annotations should be used - in particular@Override. This shouldappear the line before the function declaration.
BAD:
protectedvoidonCreate(BundlesavedInstanceState) {super.onCreate(savedInstanceState);}
GOOD:
@OverrideprotectedvoidonCreate(BundlesavedInstanceState) {super.onCreate(savedInstanceState);}
Since Android uses XML extensively in addition to Java, we have some rulesspecific to XML.
View-based XML files should be prefixed with the type of view that theyrepresent.
BAD:
login.xmlmain_screen.xmlrounded_edges_button.xml
GOOD:
activity_login.xmlfragment_main_screen.xmlbutton_rounded_edges.xml
Similarly to Java, indentation should betwo characters.
Wherever possible XML resource files should be used:
- Strings =>
res/values/strings.xml - Styles =>
res/values/styles.xml - Colors =>
res/color/colors.xml - Animations =>
res/anim/ - Drawable =>
res/drawable
Where appropriate, XML attributes should appear in the following order:
idattributelayout_*attributes- style attributes such as
gravityortextColor - value attributes such as
textorsrc
Within each of these groups, the attributes should be ordered alphabetically.
Use US English spelling.
BAD:
Stringcolour ="red";
GOOD:
Stringcolor ="red";
The following copyright statement should be included at the top of every sourcefile:
/* * Copyright (c) 2017 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */Smiley faces are a very prominent style feature of the raywenderlich.com site!It is very important to have the correct smile signifying the immense amount ofhappiness and excitement for the coding topic. The closing square bracket ] isused because it represents the largest smile able to be captured using ASCIIart. A closing parenthesis ) creates a half-hearted smile, and thus is notpreferred.
Bad:
:)Good:
:]This style guide is a collaborative effort from the most stylishraywenderlich.com team members:
About
The official Java style guide for raywenderlich.com
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Contributors5
Uh oh!
There was an error while loading.Please reload this page.

