Byte sized bits to cleaner Android code: Functions

Marko Petrovski
Web Factory LLC
Published in
2 min readSep 26, 2019

A few steps that can be taken to achieve a cleaner, more readable and less error prone code.

onCreate not onClutter

We have all written or came across an Activity / Fragment onCreate method with lots of random bits of code, undocumented, same code found in multiple places. In a nutshell, a mess. The code itself might do the job, but it’s not clean, it’s not immediately clear what it does.

Take a look at this example:

The field names are not descriptive, we don’t know if it’s a TextView, an EditText, what the button does, the id’s in the .xml file are non-descriptive and we have the same few lines of code in multiple places.

Improvements

  • Extract logical pieces to functions

We have also added a Javadoc. If the functions is not self-explanatory with code (which we should strive for it to be), we can add a Javadoc. But keep in mind that if the function changes, so should the Javadoc. If we leave it unchanged, then it’s just confusing and misleading.

  • Add descriptive field names

Field names should be descriptive, when some one reads a variable it should immediately be clear to what it is and what it does.

I think that after these few simple steps we can all agree that the code is much clearer, cleaner, readable and understandable.

Conclusion

The above mentioned isn’t exclusive only to our onCreate methods, it should be used everywhere. It always pays off to make a method from a piece of logic, even if it is just used in an onCreate. The benefit we get from a clear structure and a well documented method are too big to pass up.

--

--