Lint Driven Development

It is no wonder that “Lint Driven Development – LDD” is one of the most essential development approach that every developer should follow up! It is an integral part of every developer’s toolbox! If you could agree my statement, then you’re already on the track of super cool development. If not, then I can get you a step further towards that through this blog.

What is linting?

You write code. Probably a lot of code. And you make mistakes. Probably a lot of mistakes. Sometimes your mistake is a real bug that can be fixed. Sometimes it’s just an unclear coding style which may seem trivial at first but they become patently important as the codebase grows and as more people stick their hands in it. You can’t always focus on fixing this inevitable mistakes that you do! Isn’t it? Because, there is probably no practical way to make it impossible to write sloppy and unclear code, but it is fascinating to consider how tooling has evolved to make it harder. One fine tooling is “Linters” which understands you and your code.

Linter is part of the style guide. It’s a small piece of software that automatically checks if your code has any stylistic or potential errors and meets the predefined code convention rules. You don’t have to manually go through the code base to check style and any errors. Linting helps us in two ways. First, it looks for code that will potentially break. Second, it provides a style guide for the development team to follow.

Why Linting is Important?

Some great movies involves compelling stories, and colorful screenplays that are easy to watch and understand. From that aspect, the job of a developer is similar to that of the movie director, since the code has to be easy to read and comprehensive. I know it’s pretty hard to focus on code quality when you’re under pressure to meet the next deadline, but if you’re thinking long term, you definitely need to write code that’s readable and maintainable.

In addition to its readability and maintainability there lies an important third reason which is lower technical debt which allows speeding up long term software development since it can be reused without involving any future developer’s time to work on fixing the old bugs and styling the code.

How Linters prevent our problems?

Linting tools throws warnings about certain types of code that can lead to common problems. Some are quite major. As a Javascript Engineer, I’ll list down some major problems in JS code and how linters could prevent those problems!

Problem #1
Most of us have got this one common question in our mind that our code works in development but why not in production? We all knew that most modern web stacks support minification, but neither the minifiers nor the browser tell us when are we missing semicolons. But a missing semicolon can break minified javascript and so it stops in production. So Linters notify you about the missing semicolons, braces, etc..

Problem #2:

Have you ever created a variable called “id” or “name” or “value”? Yeah, so has every other developer in history, and people who work on the same codebase as you is not an exception. And if someone forgets to declare all their variables with var, as they can overwrite each other unexpectedly. The scope of the variables is gone as well as your code.

You don’t always need to rely on your reviewers to find mistakes in your code and in some cases it takes too much of your reviewer’s time to find some sloppy mistakes or even they might miss it completely. Linting your JS can prevent potential XSS security holes, readability problems, and many more!

Linting Tools

Linters comes with a lot of tools that are capable of finding stylistic errors and sloppy mistakes in every technology that we use. Among many JS linters, ESLint seems to be the best available linter as it is completely plug-able, every single rule is a plugin and we can add more rules at run-time. It gives concise output, and also includes the rule name by default so it’s always easy to know which rules are causing the errors. We also have Linters for most languages like TS, CSS, HTML, Python, etc..

There are different means by which one can use linting tools to improve the code quality. To mention a few,

Linting manually, in the browser

Copy and Paste your code into JSHint or CSSLint or HTMLHint or any other static code analysis tool to check for some interesting lint errors. This might be the quickest way to get started with linting.

Linting from your code editor

Many code editors have support for configurable linting, such as VSCode. Here is the guide to configure Linters in VSCode. It has many extensions for all of the linters above. Grab one and have it check your code automatically which is really great since you’re already in your editor, where you can clean your code up simultaneously while you write it.

Linting from the command line

If you’re using a command line tool like Npm, you’re ahead of the curve. Just install a linter of your choice and follow some commands to get notified of your errors in code.

Linting as part of the build process

This is the best way to ensure that these types of problems never see the light of day. I recommend adding a flag to the ng serve and the ng build commands that automatically runs ng lint before each build and causes a build failure on any linter rule violation.

Even if you set up a linter, it might warn you against invalid code but it cannot stop you from pushing this code to the repo. This is where Git pre-commit hook comes into the picture. It’ll restrict the developer from committing the code if it doesn’t pass the rules available in .git/hooks. For information about Git Hooks, please visit here.

It is NoteWorthy!

I recommend turning off most of your linter’s settings when you start using it, so that you have a minimal set of errors to start with. Consider the ones it throws out, learn what they mean and then fix them. Later, re-enable another setting and repeat until you understand all the rules. I understand, it takes some time to understand everything and to get them fixed up. Let me copy out some words from Bruce Lee.

“I fear not the man who has practiced 10,000 kicks once,

         but I fear the man who has practiced one kick 10,000 times.”

– Bruce Lee

Software development is pretty much always slower than anyone wants it to be. It takes time. Sometimes you just have to be patient enough to turn out the code you need to write. No matter how long you’ve been in this field, you should keep practicing the craft of coding.

Conclusion

Linting is a vital part of our workflow, and will definitely help us improve our skills. If you were not using linting, I hope this blog convinced you a bit to configure lint to your code. I think Linting is one of the traits that makes a good developer! What do you think makes a great developer? Love to hear from you!

Top 9 mistakes to avoid for Angular v1 developers

AngularJs has seen a tremendous improvement over the last couple of years. With a strong core team, thousands of supporting modules in the ecosystem and backed by Google, AngularJs is the most favourite UI javascript library currently!

But ‘with great powers comes great responsibilities!‘ More and more developers are flocking to AngularJs everyday and it becomes more important to understand the nuances and code accordingly.  Here are some top mistakes developers make while coding in AngularJs and the steps to avoid them!

  1. Modularity

    Keeps angularjs code modular - By Srijith Radhakrishnan, SquashApps
    Keeps angularjs code modular

    Oh please! Please put stuff where they belong! We all have our tendencies to piece together a quick app for a client demo or something and put all stuff in the controllers. You wont believe me how many times I have seen a controller go beyond 500 lines of code!

    • Use Services/Factories wherever required
    • Directives are meant for DOM related stuff. Use them!
    • Keep a watch on the size of the file. Its sometimes as simple as that. If you think it is getting big, time to refactor!
  2. Overloading the RootScope
    Dont overload the rootscope
    Don’t overload the rootscope

    Lot of us think that rootScope in the angular world is some kind of a goods train and we could load all the stuff we want to on it and it would be delivered at the right spot! (Forgive my analogy!) Hope you get the point. When we want to share information between controllers or other modules, the first thing that comes to the mind is ‘Why not use rootscope!?

    • Well, at first, its all going to be fine
    • Then one day, rootScope is going to be a huge datastore on your client side application
    • This could overload angular’s digest cycle in watching these variables and cause a performance degradation
    • You could argue that the performance hit is going to take a while, but hey! It is going to happen!
    • Check out this wonderful explanation on SO about this
  3. Too many watchesDont have too many watches in AngularJSKind of relates to my previous point. Watch is usually used to ‘watch’ a variable and do operations when its value changes. The problem is that ‘watch expressions’ are run multiple (!) times during angular’s digest cycle. Boils down to a simple math. If 1 watch expression is triggered multiple times during a digest cycle, just imagine the performance hit that an app with 100 watch expressions takes!
  4. Broadcasting (events) like a radio station!
              There may be scenarios where broadcasting an event is the right way to go. But sometimes, we tend to solve the problems in the easiest way. After all, we are humans. (or are we??) . If there is a need to transfer data from modules within the app, you could use a factory, or a location parameter in the url or rootscope (sparingly!) or session/local storages or using controller inheritance (so in your child controller you would just do $scope.$parent.getSomeData())
  5. Cancelling Timeouts/IntervalsThere might be a scenario where you might need to add a $timeout to perform some actions after a stipulated time.
    Although timeouts could be totally avoided, if you really have to deal with them, cancel them after the controller is destroyed. You could listen to the controller’s destroy event like this and cancel the timeouts/intervals you created within the controller

    // Creating a timeout
    $scope.timer = $timeout(function() {
           doSomething();
    }, 1000 );

    // Cancel it when the controller is destroyed
    $scope.$on(‘$destroy’, function (){
        $timeout.cancel($scope.timer);
    });

     

  6. DOM manipulations

    DO NOT absolutely do DOM manipulations in controller. Why?

    • DOM manipulations are slow
    • Controllers are not meant for DOM manipulations!
    • Directives are meant for just that.
    • And if you have a directive for DOM manipulation you could reuse it in any other controller. But you cant reuse it if its within the controller itself
  7. Understanding callbacks
    Understand callbacks before you jump into Angular. A lot of times timeouts have been created for the lack of understanding on callbacks. Take for example this simple scenario

    • You want to call a REST api and get a response
    • Then print something on the html. Simple.WRONG: $http.get(some_URL, function(success){}, function(error){});
      $timeout(function(){
      #Hey it takes 5 secs for the above call to complete. Let me just do a timeout!
      $scope.message  = ‘Call success’;
      }, 5000);Btw, this does not exactly execute in 5 seconds. There will be a blog soon on why! (I know you know it already, but we still want to write about it!)RIGHT : 1)  $http.get(some_URL, function(success){$scope.message = ‘Call success’;}, function(error){$scope.message = ‘Call failed’;});(OR)2) var promise = $http.get(some_URL);
      promise.then(function(success){$scope.message = ‘Call success’;}, function(error){$scope.message = ‘Call failed’;});Read more about promises here and about callbacks here
  8. Dependency Injection
    • We found this the hard way but dont inject dependencies for your angular module like thisBAD app.controller(‘MyController’, function(Dep1, Dep2){
      });GOOD app.controller(‘MyController’, [‘Dep1’, ‘Dep2’, function(Dep1, Dep2){
      }]);ok Why do I have this redundancy? Why are my dependencies first injected as inline array annotations and then as parameters to the controller?
      Simple answer
      : Minification
      Detailed: JS minifiers rename the arguments before minification and then  Angular has no absolute idea of what those arguments are! There are two solutions to this
    • Either follow the implementation in the ‘Good’ section above (or)
    • Use tools like ng-annotate which would automatically do the inline array annotations for you.Read more here
  9. JSHINT (static code anaylis) and Tests!

    JS Linting and TESTS are your friends!
    JS Linting and TESTS are your friends!


    Often times, we ignore these guys as we need to meet that one deadline or go to the market before the other guy does! So much that we forget the good stuff that they bring. I am just going to jot down the advantages

    • JSHINT has caught more bugs than all the fish ever caught in human history (Crazy Analogy again. Forgive!)
    • If you had a friend who would sit with you all day while you code and test all your stuff, would you be happy?
      1. If the answer is YES, Karma is the name! Not the literal meaning, but this awesome test runner
      2. If the answer is NO, you need some socializing 😉(Note: if you have a large inherited codebase with no absolutely no tests, dont go about making that your priority! Of course tests are important but not more than the core business! Allocate may be 20% of your time weekly to write tests for the old code and dont write any new code without tests. Eventually you would be boasting a decent test coverage!)I am planning to do a blog later on how Panitr maintains near perfect test coverage

Following good coding practices not only enriches your knowledge but also helps the future app maintainer to not go mad and file a lawsuit against you 😉