Clean Code Chapter 1&2: Clean Code & Meaningful names

I have started reading the book Clean Code by Robert C. Martin, which is considered to be a industry standard for writing maintainable and elegant code.

Because this book is such a heavy read, and each chapter is full of content and a knowledge bank in itself, for personal reference I’ve decided to summarise each chapter in a set of blog posts.

Chapter 1 : Clean Code

This was more like chapter 0. Author describes what is clean code and cost of maintaining it. How clean code is directly related to team productivity and what makes clean code clean.

It contains views on clean code by many of industries best known people like Bjarne Stroustrup, Michael Feathers etc.

One of my favourite definitions form the book covers it best :

I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well – Bjarne Stroustrup

Chapter 2 : Meaningful Names

Names are everywhere in software. We name our variables, our functions, our arguments, classes, and packages. Because we do it so much, we should do it well.

1. Use intention revealing names : 

The name of a variable, function, or class, should answer all the big questions. It should tell you why it exists, what it does, and how it is used.

int d; // time elapsed

Here d reveals nothing. A better name would be

int timeElapsedSinceCreation;

2. Avoid Disinformation :
Programmers must avoid leaving false clues that obscure the meaning of code. We should avoid words whose entrenched meanings vary from our intended meaning.
ex

int accountsList;

Should only be named so if it is a actually a list data structure that’s used to store the accounts. Not an array or set.

3. Make meaningful distinctions
Entities named different, should be different, mean different.

If we have classes called

ProductInfo

or

ProductData

, you have made the names different without making them mean anything different. Info and Data are indistinct noise that doesn’t differentiates what they actually mean.

4. Use pronounceable names

Makes communicating about the code easy.
ex.

long genydhms;

is not a good name.

long generationTimestamp;

is a better choice

5. Use searchable names
Avoid single letter variables and constants as they are difficult to search.

6. Avoid Encodings

Hungarian notations, member prefixes, interface and implementations should be avoided.

It just adds another burden to remember the encoding format being used.

7. Avoid mental mappings
Readers shouldn’t have to mentally translate your names into other names they already know.
ex.

int r;

Where

r

is lower cased url with host name removed adds to much requires too much mental juggling and mapping when working with the code.

A better name would be,

int urlWithoutHostName;

8. Class Names
Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser.
Avoid words like Manager, Processor, Data, or Info in the of a class. A class name should not be a verb.

9. Method Names
Methods should have verb or verb phrase names like postPayment, deletePage, or save.

10. Don’t be cute

If names are too clever, they will be memorable only to people who share the
author’s sense of humor, and only as long as these people remember the joke.

Don’t tell little culture-dependent jokes like eatMyShorts() to mean abort().

11. Pick one work per concept
Pick one word for one abstract concept and stick with it.

It’s confusing to have a controller and a manager and a driver in the same
code base. What is the essential difference between a DeviceManager and a ProtocolController?

11. Use solution domain names
It’s OK and preferable to use names from computer science and programming domains.
ex.
In transctionObserver

the word observer means a great deal to person who knows the observer pattern.

12. Use problem domain name
The code that has more to do with problem domain concepts should have names drawn from the problem domain.
ex..

int mriRecord

In a healthcare app will give a great deal of context than just

int record

.

13. Add meaningful context
Enclose names in well named functions, classes, namespaces, etc.
ex.

String state;

In a class called FiniteStateMachine will mean different that in a class called Address.

14. Don’t Add Gratuitous Context
In an imaginary application called “Gas Station Deluxe,” it is a bad idea to prefix every class with GSD.
Frankly, you are working against your tools. You type G and press the completion
key and are rewarded with a mile-long list of every class in the system. Is that
wise? Why make it hard for the IDE to help you?

 

This was part one of a 16 part series on the book Clean Code by Robert C. Martin, where each post covers a gist of a single chapter.

Thanks!

Philosophy Behind The Offensive Programming

football-1149952_640

Recently I was listening to a podcast and there was this really smart guy Piwai talking about something that instantly captivated by attention. That was the coining of the term Offensive Programming.

What is offensive programming?

Well, you can find the literature on  Wikipedia and also I am not the best person to explain that. So check that out please. But fundamentally, offensive programming refers to a style of programming that is exact opposite of the more famous counter-part the defensive programming.

Defensive programming refers to coding style which adheres to dealing gracefully with conditions that should not happen.

Offensive programming on the other hand, well just tells you to let the app crash. Don’t try to recover, don’t try to handle the exception, just log the stack trace and crash.

The reason behind this is that in reality the problem can be much bigger and somewhere else in the code, as a side effect of you are getting this error in first place. This forces you to fix the problem at the source and will possibly result in a healthier code base.

When it makes sense to be offensive?

This was my exact concern while I was listening to this podcast. Thankfully, Piwai answered that himself. I also, talked about it with a really smart guy at the office and he also made the same remarks.

So at Square (the company who do payments and author libraries) what they do is, they stick to a defensive style of programming  for interfaces and parts of code that deals with external interfaces and/or user interactions. Basically, something that is not in your control.

But, for the internal interfaces, where the classes you wrote are going to interact with each other, you don’t have to be that paranoid about that. This is where he (Piwai) said you should switch to the offensive approach. You have full control over the classes you wrote, and the expected behaviour is in your control. If it fails to do so, it’s better to just crash and let the problem to be fixed at the source.

That is the exact reason he said at Square, they make very liberal use of assertions in the code. Assertions are not forgiving at all.

Example Please!

I would attempt to point to examples here, one that the Piwai himself talked in very brief and the one that I’ve encountered myself where I thought it made sense.

In this example, say we are handling credit card objects. There is no point to internally validate the credit card object every time you deal with it.

As soon as we get a credit card, we decorate it with a validated credit card. That’s all the defensiveness we had to offer.

Now internally, we go offensive and throw exceptions or assertions every time we encounter an invalidate credit card object.

The code below is not perfect, but can give you an idea.

class ValidatedCreditCard extends CreditCard{

    CreditCard creditCard;
    
    ValidatedCreditCard(CreditCard creditCard){
      // Handling external user interactions defensively.
      try{
        creditCard.validate();
      }
      catch (CreditCardValidationError e) {
        // Handle and try to fix the error
        tryToFixTheCardDetails();
      }
      this.creditCard = creditCard;
    }
}

public static void main(String[] args){

    CreditCard c  = getCreditCardFromUser();
    c = ValidatedCreditCard(c);
    // Time to go offensive
    // ...
    if (c == null){
      throw new CardInvalidException();
    }
}

Another example I can think of is a much simpler one and more relatable.
Suppose, we have a utility function that uploads a file to s3.
It would make sense to follow offensive programming style and just throw an exception if somehow they file or the key reaching the function is None.

def upload_file_to_s3(file, key):
    if file is None or key is None:
        raise TypeError

 

Few more tips from the podcast

1. How to start with offensive programming?

Best way is to start putting assertions in the code, where you think is suitable. Yeah, we’ll experience more crashes and that’s awesome!

Because now we know that we have a problem.

2.  We feel more confident about the code base:

We just know that, this method doesn’t try to handle nulls, thus I can confidently say that it was not null or it would’ve crashed.

3. Do incremental roll outs.

When you ship a code, roll it out like for 1% of users. We’ll have a ton of crash reports, and that’s good! I mean not for the 1% users but they are taking one for the team!

4. Crash at preventable errors and recover from expect-able errors :

Preventable errors are invalid arguments, NPEs etc. Go offensive on these.

Expectable errors are like resource depletion, invalid user inputs etc.

Try to recover from these.

 

Overall, it was nice to listen to a guy who works at a company like Square talking about how they use offensive programming for a healthier code base. And if Square is doing something, we all can learn something from that!

5 notes on MVP architecture pattern for Android

                                                           Image credits Macoscope

MVP (Model View and Presenter) is an architectural pattern inspired by the popular MVC pattern.

MVP addresses two main points :

  1. Make views as dumb as possible. The dumber the better.
  2. Make each layer loosely coupled and easily testable in isolation.

I am using MVP in one of my production project and have used in some dem0 apps. Here are my 5 notes on using MVP for android.

  1. Package Structure :

Android project contains lots of code and files even for application of medium complexity. Even when not following MVP I have found that arranging the project files in such a way that files that are accessed together are put in same package is more efficient and intuitive than any other approach.

What I prefer doing is create separate package for separate verticals of the app and put all related files like activities, fragments, views, presenters, adapters etc in that package.

ex. packages like add task, view task, list task for a To-Do app.

2. Libraries that are useful for MVP :

In MVP you want your model and presenter to be independent of the life cycle of view. For this, you can use dependency injector library like Dagger2.

Other than that, using RxJava and reactive programming principles for creating presenter is also becoming increasingly popular.

Libraries you can use for this purpose are : RxAndroid and EventBus.

3. Managing Remote and local data sources in the Model :

Android apps have to fetch data from the server. At the same time fetched data must be cached to make the app usable offline and increase the speed.

What I prefer doing is to create three model classes :

1. Remote Data Source

2. Local Data Source

3. Data Repository

All presenters talk to Data Repository class. Data repository model contains references to Local and Remote data repository and calls data from either according to situation.

As the name suggests Local Data Source deals with cached data and disk storage whereas Remote Data Source deals with API calls and responses.

4. User Experience is the top priority :

One thing that we all have to keep in mind that the real test of application is, if it is able to provide user a nice experience.

At the end of the day, user only notices the user experience of the application and not the architecture used. So if you have to make some design sacrifices to make the UX better, do it.

The real test of the machine is the satisfaction it provides to the mind. There is no other bigger test.

5. Testing Advantages :

Main motive behind MVP pattern was to make the testing of layers easy.

Basic idea is to keep the presenter and model android free, so that they can be tested without Android instrumentation by the JVM itself.

Views can then be tested by Android Instrumentation tests.

Mockito and Espresso can come handy for testing purposes.

Conclusion :

MVP, in my opinion is so far the best way to architect your android application project. It simplifies many issues like testing and making views lighter. Combine it it RxJava and dependency injection and you’ve got a nice recipe for android projects.

I am learning more about RxJava and testing frameworks will share my views on that soon.

Thanks.

Practice Shapes : Android App To Learn Shapes

Only way to learn something is to learn it by yourself.

Recently I have been playing with Canvas in android and it has been fun! 😀

As they say knowledge is knowing tomato is a fruit. Wisdom is not putting it in vegetable basket. And best way to persist new gained “wisdom” is to put it in use.

Practice Shapes is a fun app both for kids and grown-up kids (Yes. You!), to test their drawing skills. Though I know drawing on a mobile screen with your fingers is not your favorite thing, but still you will enjoy it! 😀

Download the app from play store :

 

This app is open source : You can fork it at https://github.com/priyankvex/Practice-Shapes/

 

TECH STACK : 

  • Android SDK
  • Bitmap Images of Shapes

The power lies in not reinventing the wheel, but to use it to move forward.

OPEN SOURCE LIBRARIES USED : 

  1. Universal Image Loader
  2. Sugar ORM
  3. Fancy Buttons

To Create Images : 

To create images for the app on which user draws, i used GIMP. These are just simple images with transparent background.

Right now, there are total of 18 images in the app under 3 difficulty levels.

If you can add more images feel free to do so.

Screenshots of app : 

drawing_ss

hard_shapes_ssscore

Download the app from play store :


Rails Number Helper Port to Android

A polyglot developer will understand, there is always something you like about one language and you wish was available for another language too.

So, recently I started learning rails and found number_helper API very cool and fun to use. It gives you easy API to convert numbers into many formats like number_to_human which will convert 20000 to 20 Thousands or number_to_human_size that will convert 1024 to 1 KB.

That was it I wanted this stuff for Android too. It just makes processing numbers to fit the UI needs so damn easy.

Here is my attempt to port this rails module to Android.

Here is the source code :

https://github.com/priyankvex/Rails-Number-Helper-For-Android

Usage : 

Just copy the module number_helper in your application folder and include module dependency.

Examples : 

 


        // Number to human converter
        NumberToHumanConverterBuilder builder2 = new NumberToHumanConverterBuilder(123456);
        NumberToHumanConverter converter2 = builder2.build();
        try {
            String humanNumber = converter2.convert();
            // OUTPUT : 123.456 Thousands
            Log.d(Config.TAG, humanNumber);
        } catch (InvalidSeparatorException | InvalidDelimiterException
                | InvalidPrecisionException e) {
            e.printStackTrace();
        }

Examples can be found here.
https://github.com/priyankvex/Rails-Number-Helper-For-Android/blob/master/app/src/main/java/com/wordpress/priyankvex/numberhelperdemo/MainActivity.java

Features : 

  • Easy to use API.
  • High utility for UI needs.
  • Small in size.
  • Custom exceptions to fit the needs of Android.

 

Making GCM client in Android and Application server in Ruby on Rails

It is always fun to play with new APIs and tools. GCM is not something I was getting my hands on for the first time but it changed completely since last time I did a project using this.

But the good news is it has changed for good. New service classes makes it easier to write GCM clients for Android, GCM default configuration makes writing test servers and apps to play with very less tedious. In fact my first reaction was this is GCM reincarnated. 

GCM Client and App server
GCM Client and App server

New API : New Party!

You can have a look at the source code here :

https://github.com/priyankvex/GCM-Android-Client-and-Rails-Server

To create Android client I stuck with sample provided in the docs. Sweet and simple to implement. Just little tweaks done to make it fit my needs.

For creating application server i.e the 3rd party server required by the GCM stack, it used Ruby on Rails. In that specifically I used “gcm” gem.

Again not a very complex server but good enough to get a hold of things.

Server features : 

  1. Save incoming device tokens (registration ids).
  2. Web form to send message to all devices registered.
  3. Send welcome notification when device is registered.

Client features (Android App) :

  1. Get GCM token for the device.
  2. Send token to applications server.
  3. Show notification when message is pushed from server.

 

Paint App in Android

Recently I was learning about Canvas and Custom views in Android and to put the theory in practice I made a pretty simple Paint App. 

Source code of the app can be found https://github.com/priyankvex/Paint-App-Android.

Screenshot of the app
Screenshot of the app

 

The App is pretty simple with features
1.  Create Drawings (Obvious one :P).
2.  Select different brush sizes.
3.  Eraser with different sizes.
4.  Color pallet.
5.  Save drawings in Gallery.

Source code of the app can be found https://github.com/priyankvex/Paint-App-Android.

Brownie points if you can guess the character I drew! 😀