Wednesday, March 18, 2015

MyNotes: Code Style

Before I get deep into coding I want to take a minute to talk about my code style guidelines.  I have guidelines for the code, XML layouts and XML resource values.

Code Style

I basically follow the Android Contributors Guidelines.  This is includes a very simplified Hungarian notation that prefixes an "m" to all class attributes.  I go a step further and prefix an "s" to all non-final static objects.  I also use all caps with underscores for static final variables.  It ends up looking like this:

class MyClass {
      private static final Object THIS_IS_FINAL_AND_STATIC = new Object();
     
      private static Object sThisIsNotFinal = new Object();
     
      private int mObjectAttribute = new Object();
}

XML Layouts

Firstly, I try to name the files to signify what is inside.  I start the file name with what the layout is for:
  • Activity layouts:
    • activity_main.xml
    • activity_note_edit.xml
  • Fragment layouts:
    • fragment_main_toolbar.xml
    • fragment_note_filter.xml
  • Custom Components:
    • component_note.xml
    • component_grid,xml
  • Include Layouts:
    • include_activity_main_content.xml
    • include_subtoolbar.xml
  • Item to use in RecyclerViews:
    • recycler_item_note.xml
    • recycler_item_name.xml
My only other guideline is to be specific and verbose when naming ids. I have problems in the past where really simple id names caused a conflict at runtime. Those are unpleasant bugs to figure out and eliminate.  Since then I nip the problem in the bud by being specific on the names.  So if I have a TextView that will contains a label in an activity layout instead of :
<TextView android:id="@+id/name" />
I will use:
<TextView android:id="@+id/activity_main_first_name_label" />

XML Values

The values files can get out of hand really fast.   To prevent this, I try to only use the default files (strings.xml, colors.xml, etc.) for the global values.  I then group the items based on functionality and put them in their own files.  I always prefix the files with the type of resource it contains (integers, dimen, strings, etc).  It ends up looking like this:

strings.xml
strings_toolbar_strings.xml
strings_help,xml
colors.xml
colors_theme.xml
colors_note.xml



No comments :

Post a Comment