Ever had the feeling that when you read your own code after a couple of weeks, and you can’t figure out what that code does or why you wrote that piece of code?😕😕

Don’t worry, almost every developer has the same feeling! 😆

Again, what about someone else who’s reading the code in the future? If you can’t figure out your own code, how can they? 🤷‍♂️

By experience, you will understand when code looks cryptic and what code will cheat on you after a few days.

So here’s what I do when I think that the code can be hard to understand later (for me or a future reader):

  • Add comments explaining what it does, like:
// This code implements the LERP algorithm   
// based on this calculation <link> from Wikipedia.  
  • If you think that that’s not sufficient, then write extensive documentation like this:
/*
  LERP algorithm

  This function will do linear interpolation based on the algorithm as
mentioned in Wikipedia: https://en.wikipedia.org/wiki/Linear_interpolation

  Example usage:
   val result = lerp(36.0, 38.0, 0.3) // returns 36.6

  Ref 1: https://stackoverflow.com/questions/4353525/floating-point-linear-interpolation
  Ref 2: https://www.johndcook.com/interpolator.html
*/
  • If the code is copied from another source, then cite the source. It will help later to refer again for more details and copy new updates if available. This happens mostly with code from StackOverflow, where new answers/improvements can come in the code that we copied over.
// Ref: stackoverflow.com/answer/1234  
  • Always write code like you are writing it for someone else to read. Pretend to be a reader and go through your code after a couple of days. If you feel confused or blocked, then the code should be changed (or a proper comment should be added).
  • Avoid “show-off” or “smart-looking” style code. You can do that during a coding contest, but when you are writing production code, make it clean, clear, and most importantly, readable.