Share
Embed
Android Coding Guidelines
Presentation of the version 0.2 of our Coding Guidelines @ Sixt
Enrique López Mañas
September 23, 2014
Transcript
15 slides
-
Indentation • Blocks that are nested more should be
indented more. Blocks that are nested the same should be indented the same. • In case of doubt, automa?c indenta?on (op?on + cmd + L) -
Naming best practices • Aim
to write self documen?ng code • Do not use magic numbers. CREATE CONSTANTS • Do not use uncommon abbrevia?ons (Btn, Lbl, Tv) • Include units in a name (distanceInMeters) • Most meanings have mul?ple words. PICK ONE • Try to avoid comments by crea?ng meaningful names for methods -
Starting instance variables • “m” for non public, non
sta?c. “s” for sta?c • (only in view classes) -
Some other elements • TextView, EditText... begins with the
name of the func?onality and then the type (reason: alphabe?cal sor?ng). • TextView showOfferTextView; • Strings: same patern but separa?ng them with _. Reason: is used throughout the Android plaZorm • show_offer_text_view -
Capitalization rules • Classes start with uppercase le]er
• public class Foo • Constant in uppercase le]er, descrip?ve name • private sta?c final int THIS_IS_A_CONSTANT = 1; • Everything else with lowercase le]er • private int fooFunc?on() {..}; • private boolean hasBeenFound; -
Breaking things • Wri?ng short methods • No
official limit. As small as possible • If you have the same code twice -‐> refactor. No excep?on. • Short methods avoid wri?ng large docs • Keep lines short • Google recommends lines of max 100 characters. Not sure why this is a magic number, but is anyway a good prac?ce to keep lines short. • If you strictly need to keep them large (i.e., mul?ple if else condi?ons) then switch to a new line -
JavaDoc • Keep it simple! • Use it
as you do it. Not when you are finished. • Don’t document constructor, ge]er, se]er • If a method is complex enough, say what it does! • Useful annota?ons • @Deprecated • @author • @see • @param • @return • @Override -
Multiple returns • Mul?ple returns can increase readability.
private void onEvent(Loca?onUpdatedEvent event) { if (event != null && isInCloseDistance() && !mRequestRunning) { doYourStuff(); } else { return null; } } private void onEvent(Loca?onUpdatedEvent event) { if (event == null) { return; } if (!isInCloseDistance()) { return; } if (mRequestRunning) { return; } doYourStuff(); } -
Good practices • • Brackets: Use K&R style with
4 indenta?on spaces (automa?c in Eclipse and Android Studio) -
Good practices • Importers: don’t use *, list each
class member. • You can automa?cally perform the imports.