Simple but painful steps for writing a better code

Dmitry Zaytsev
SHARE NOW TECH
Published in
2 min readNov 20, 2017

Let’s get straight to it until your coffee gets cold.

Stop creating new objects inside a class

Unless those are data objects you creating or the class is a factory. Here is what I mean:

This class is:

  • Absolutely not testable.
  • What is a context? We don’t care about the context here.
  • Tightly coupled to Retrofit library. Or whatever other library.

The proper way

It is easier than you think — just pass VehiclesRetrofitApi as a constructor parameter.

How do you pass vehiclesApi now? Dependency injection to the rescue! There is a lot of material out there, just Google it up.

Stop referring to singletons

Keep your singletons. They are fine. Just don’t call them from your code directly. After all, all they are is another dependency of your class.

The proper way

Just pass it as a constructor parameter.

Stop calling your classes Managers

Also don’t call them Handler, Controller or Processor. Such names serve as an excuse for other developers (including you) to keep bloating this class with less and less related stuff.

Follow a simple rule of thumb — will the name become less clear if you will remove a word from it? No? Then remove a word. To me Vehicles tells as much information as VehiclesManager. Which is no information.

The proper way

This one seems to give us vehicles which are close to us. Let’s call it ClosestVehiclesProvider. Might be not perfect, but already better. At least no one will have an excuse to add something like getVehiclesByType here.

Stop creating subclasses

Unless those are algebraic data classes. Interfaces are also perfectly fine. Look at that little monster:

And it’s ugly baby.

What is wrong:

  • We don’t really care about Repository in our ClosestVehiclesProvider.
  • Whom do we test? We can’t create an instance of BaseVehiclesProvider.
  • In this particular case ClosestVehiclesProvider doesn’t even serve as a substitute for BaseVehiclesProvider.
  • What if I don’t need caching from the base class? What if I don’t need the server in the base class?
  • What if we need closest electric vehicles? Or closest vehicles with low fuel level? Or closest electric vehicles with low charge? Amount of subclasses will just blow up.

The proper way

Simple solution — pass it as a constructor parameter.

Wow, I hope this all did not sound too rough. Did my best to keep the explanations short and to the point. In the end, I believe that those steps are not really opinionated and supposed to be a pure goodness 🦄

Those are seemingly simple steps, but just by following them for a couple of weeks you will already notice the improvement in your code base.

--

--