Single Responsibility

Single Responsibility

Rule of 1

[Style Y001]
  • Define 1 component per file, recommended to be less than 400 lines of code.

Why?: One component per file promotes easier unit testing and mocking.

Why?: One component per file makes it far easier to read, maintain, and avoid collisions with teams in source control.

Why?: One component per file avoids hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies.

The following example defines the app module and its dependencies, defines a controller, and defines a factory all in the same file.

  /* avoid */
  angular
      .module('app', ['ngRoute'])
      .controller('SomeController', SomeController)
      .factory('someFactory', someFactory);

  function SomeController() { }

  function someFactory() { }

The same components are now separated into their own files.

  /* recommended */

  // app.module.js
  angular
      .module('app', ['ngRoute']);
  /* recommended */

  // some.controller.js
  angular
      .module('app')
      .controller('SomeController', SomeController);

  function SomeController() { }
  /* recommended */

  // some.factory.js
  angular
      .module('app')
      .factory('someFactory', someFactory);

  function someFactory() { }

Back to Table of Contents

Small Functions

[Style Y002]
  • Define small functions, no more than 75 LOC (less is better).

Why?: Small functions are easier to test, especially when they do one thing and serve one purpose.

Why?: Small functions promote reuse.

Why?: Small functions are easier to read.

Why?: Small functions are easier to maintain.

Why?: Small functions help avoid hidden bugs that come with large functions that share variables with external scope, create unwanted closures, or unwanted coupling with dependencies.

Back to Table of Contents