Quality metrics and angular js applications

Embed Size (px)

Citation preview

Quality Metrics And AngularJs Applications

Quality?Definitions of Programmatic quality often straddle the fence between art and science.Programming is a tension between objective observations through codified repeatable steps and subjective evaluations born out of personal experience and insight.The act of programming is often an amalgamation of creative problem solving and applying an engineers rigor to refine a solution.Both the subjective and objective positions are needed to evaluate JavaScript source. Subjective Quality : Subjective quality often describes code that is inspired or essential (innate excellence)Objective Quality : Objective quality asserts that if genius can be measured, it can be quantified and repeated. The quality of a cake is not dependent on the innate excellence of the baker, but instead is a result of the exact choice and measurement of ingredients, and the precision to which the recipe is followed.

How is Quality Measured?When quality gets relate to programming, several dimensions (facets) comes visible and are commonly expressed as software metrics.

Software metric is a measure of some property of a piece of software or its specifications.

Quality Metrics - AestheticsThis metric measures the visual cohesion of the code, but also encompasses the consistency and thoughtfulness of formatting, naming conventions, and document structure. Aesthetics are measured to answer these questions:How readable is the code?How are the individual parts organized on the page?Does it use best practices in terms of programming style?

Quality Metrics - CompletenessCompleteness measures whether the code is fit for purpose. To be considered complete, a program must meet or exceed the requirements of the specified problem. Completeness can also measure how well the particular implementation conforms to industry standards or ideals. The questions about completeness this measure attempts to answer are these:Does the code solve the problem it was meant to?Does the code produce the desired output given an expected input?Does it meet all the defined use cases?Is it secure?Does it handle edge cases well?Is it well-tested?

Quality Metrics - Performance Performance measures an implementation against known benchmarks to determine how successful it is. These metrics may consider attributes such as program size, system resource efficiency, load time, or bugs per line of code. Using performance measures, you can answer the following questions:How efficient is this approach?What load can it handle?What are the limits on capacity with this code?

Quality Metrics - EffortThis metric measures the development cost incurred to produce and support the code. Effort can be categorized in terms of time, money, or resources used. Measuring effort can help answer these questions:Is the code maintainable?Does it deploy easily?Is it documented?How much did it cost to write?

Quality Metrics - DurabilityTo be durable, a programs life in production is measured. Durability can also be thought of as a measure of reliability, which is another way to measure longevity. Durability can be measured to answer these questions:Does it perform reliably?How long can it be run before it must be restarted, upgraded, and/or replaced?Is it scalable?

Quality Metrics - Reception Reception measures how other programmers evaluate and value the code. Tracking reception allows you to answer these questions:How hard to understand is the code?How well-thought-out are the design decisions?Does the approach leverage established best practices?Is it enjoyable to use?

Why Measure Code Quality?What gets measured gets done. Measurement in this context means to look forward in order to forecast change. When applied continually through the development process, measuring code quality gives you the ability to interpret the health of your project. Technical debt is a metaphor that describes the increasing cost in terms of time, money, and resources that bad code steals from your project over time. There are many quality metrics, including code complexity analysis, that can identify areas of code debt in your software.There are several measures (such as the Halstead metrics) that can suggest the amount of future effort that will be required to maintain your codebase. Knowing this can inform your ability to accurately budget for these improvements.Many code-quality measures attempt to understand the pathways through your code. These measures can then identify the likelihood that bugs exist, and where they may be potentially hiding. These tools are especially valuable when evaluating another teams code because they can act like mine detectors, which sweep algorithmically through the unknown field of functions.Although the ability to find new bugs is important, so too is the skill to know when it is safe to stop writing tests. Many prominent developers have proven that tests arent free, so knowing when to stop saves money. Many code quality tools can tell you when you have reached an appropriate level of test coverage using simple heuristics.Embracing code quality measures is a form of preventative maintenance.

How Measure Code Quality?Static Code Analysis is a collection of algorithms and techniques used to analyze source code without running the code, in order to automatically find potential errors or poor coding practices.The tasks solved by static code analysis software can be divided into 3 categories:Recommendations on code formatting/style. Some static analyzers allow you to check if the source code corresponds to the code formatting standard accepted in your company.Detecting errors in programs.Metrics computation. Software metrics are a measure that lets you get a numerical value of some property of software or its specifications.

Why Style Guidelines?Code would become easier to read and maintain.Code looks more organized and professional.Code would become more expressive and consistent.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs. End of line character ("lf", "cr", or "crlf")Indentation settingsTrim trailing white spaceFile encodingLine width etc

Enforcing Styles - Through IDE

Enforcing Styles - Through BeautifiersBeautifiers are programs that process code by using a series of formatting conventions to apply style uniformly to the source code. Two of the most popular beautifiers are CodePainter and JS BeautifyCodePainter : A JavaScript beautifier that can both infer coding style and transform code to reflect that style. CodePainter extends EditorConfig

Linting Code Linting refers to using the magic powers of static analysis to find potentially erroneous, inconsistent, or otherwise undesirable (whatever that means to you) bits of code in a program. Linting is useful because it can:Catch bugsHelp you avoid potential mistakesKeep your code clean, especially post-refactorEnforce style guidelines

Linting Linters does not measure complexity directly, it does force you to know what your code is doing. This decreases complexity and ensures that you do not use any overly complicated or error-prone constructs. Simply put, it is a measure of code sanity. It detects the bad parts of your code.Here are some common mistakes that JavaScript Lint looks for:Missing semicolons at the end of a line.Curly braces without an if, for, while, etc.Code that is never run because of a return, throw, continue, or break (dead code)Case statements in a switch that do not have a break statement.Comments within comments.Ambiguity whether two adjacent lines are part of the same statement.Statements that don't do anything etc.

Linting - How do we do it? Using JSLintWas made by Douglas Crockford (Author of the book, JavaScript: The Good Parts, Inventor of JSON , Developer of JSMin)Initial release 2002Enforces Crockford's personal style preferencesHas relatively limited configuration options

Linting - But I don't like some of Crockford's rules!Neither did some other people. One guy called JSLint:
A tool that makes sure you write your code like Douglas CrockfordAnton Kovalyov(Author of Third-Party JavaScript) forked JSLint, added magic, and called it JSHint.Like JSLint but lets you configure the rules moreInitial release 2010Adoption: 80% more GitHub stars

Linting - But what if I want my own new rules?ESLint (The pluggable linting utility for JavaScript) JSHint covers most use cases, but it can't possibly cover them all out of the box. So another guy came along and added even more magic. Like JSHint, but with a different source of magicThis different magic lets us write out own rules easilyIs completely style agnostic; have it your wayInitial release 2013Made primarily by Nicholas Zakas, who therefore wrote a book: Professional JS for Web Devs

Code ComplexityLinters and parsers are excellent tools for establishing a base line for code quality. However many a times only measuring syntactic quality is not sufficient, there should be a way to mitigate complexity creeping into the code base.Antoine de Saint-Exupery could have been talking about quality when he said, Perfection is achieved, not when there is nothing left to add, but when there is nothing left to take away.Anyone who has programmed for any amount of time knows that code is our enemy. A simple fact of development is that as code increases, quality declines. Code is syntactic cellulite; easier to add than to remove. Code bloat (as it is called) leads to a complex program because there is more source for programmers to read, understand, and maintain. Smart programmers fight complexity by leveraging design patterns and application frameworks. They embrace development methodologies that attempt to reduce complexity through a consistent approach to programming. In addition to these approaches, complexity can also be measured programmatically using quality metrics tuned to find difficult code.

Code ComplexityComplexity metrics, which are well-suited for JavaScript:Excessive CommentsLines of CodeCouplingVariables per functionArguments per functionNesting depthCyclometric complexityNPATH complexityHalstead MetricsProgram Length (N)Vocabulary Size (n)Program Volume (V)Program Level (L)Difficulty Level (D)Programming Effort (E)Time to Implement (T)Number of Bugs (B)

Code Complexity - ToolsA primary goal of objective quality analysis is to create a series of programmatic measures, which can score complexity on-demand using a consistent and repeatable process. There are several complexity analysis tools in JavaScript, one of them is complexity report.Complexity-report :Phil Booths complexity-report is a straightforward command-line tool that analyzes any JavaScript file and then generates a complexity report from it. Complexity is determined from the following metrics:

Lines of CodeArguments per functionCyclomatic complexityHalstead MetricsMaintainability Index

Code Complexity - PlatoJarrod Oversons Plato is a code quality analysis dashboard that creates a collection of visually pleasing and informative reports. Plato harnesses JSHint and complexity-report to do the actual analysis and then massages their raw reports into a collection of informative charts and graphs.Plato is a fabulous tool for exploring the quality metrics of a particular codebase. It does what all good visualizations do, which is to allow the viewer to come to a deeper understanding of the data. Plato achieves this by allowing the viewer to consider the same scores at various scales and in numerous contexts.It is especially useful for nontechnical people who still have something at stake when it comes to the quality of a codebase.

Code Complexity - Plato

There is no error free codeAdditional recommendation to ensue error free codeUnit testing and ensuring sufficient code-coverageFunctional TestsCode reviews

Testing - Why do you need to write tests?Because you're not Chuck Norris. Chuck Norris' code tests itself, and it always passes, with 0ms execution time Testing Proves that There Are No Bugs in a ProgramTesting Ensures that the Program Is High QualityTesting Prevents Future ErrorsTesting Proves that the Program Works as DesignedTests works as a documentationTesting makes future enhancement easy and fearlessTests improves the design without breaking it

Testing - Two types of testsUnit TestingUnit testing works by isolating small "units" of code so that it can be tested from every angle.Integration (E2E) TestingE2E testing works by testing full areas of the application by running a test through its entire stack of operations against a special HTTP server from the start to the end (hence end to end). Think about E2E tests as a robot using a browser to run a test and then running an assertion against the page once it's ready.

Testing Tools - KarmaThe major challenge when it comes to testing JavaScript is that it requires a runner setup to test code. The issue with JavaScript runners is that you must properly set them up to include all of the JavaScript code (source and tests) in your application and then somehow wire that into an automated test suite. After that, you will need to open up each browser and test all the specs to see if they test properly with no errors or run a command line program to test your suite on call. If you run your suite from the command line then you'll need to write an automated browser tester into your test suite and this may require some tricky hacking. As you can see, this is too much of a pain and the time and effort to set this up should be saved for more important things like building your application.Karma is an amazing testing tool which is designed to take all the frustration out of setting up a working test runner when testing JavaScript code. Karma works by spawning up each browser that is specified within its configuration file and then running JavaScript code against those browsers to see if they pass certain tests. Communication between Karma and each of the browsers is handled with the karma service running in the terminal using socket.io. Each time a test is run.Karma records its status and then tallies up which browsers have failed for each test and which ones passed and timed out. This makes each test work 100% natively in each browser without the need to test individually.

Testing Tools - JasmineJasmine is a little Behavior-Driven Development framework, created by the guys at Pivotal Labs to allow you to write automated JavaScript tests.

Testing Tools - ProtractorThe new, preferred end-to-end testing framework is called Protractor. Unlike the Angular scenario runner, Protractor is built on Seleniums WebDriver, which is an API, written as extensions, for controlling browsers. Protractor is built atop the Jasmine framework, so we dont need to learn a new framework in order to use it. We can also install it as a standalone test runner or embed it in our tests as a library. See here for more details.

Testing How to know youve tested enough?A program is thought to be well-tested when all the paths through the application are covered by at least one test. Programs with sufficient test coverage are thought less likely to contain bugs, and therefore are often used as a measure of a programs quality. A developers ability to maintain adequate test coverage is an important factor in the cumulative testing practice.Instanbul : A Javascript code coverage tool written in JS

Detecting duplicate code with JSCPDOnly cares about code structure/behavior, Ignores:Formatting/White spacesVariable NamesSmall syntactic variationsDuplicate code in AngularJS

SummaryIt is an exciting time to be a JavaScript developer; technologies have matured, web browsers are more standardized there are new things to play with every day. JavaScript has become an established language, and the Web is the true open platform of today. We've seen the rise of single-page web applications, the proliferation of MVC frameworks such as Backbone.js and AngularJS, the use of JavaScript on the server with Node.js, And even mobile applications created entirely with HTML, JavaScript, and CSS using technologies such as PhoneGap.From its humble beginning with handling HTML forms, to the massive applications of today, the JavaScript language has come very far, and with it, a number of tools have matured to ensure that you can have the same level of quality with it that you have with any other language.

ReferencesMaintainable JavaScriptTestable JavaScriptPro AngularJsExpert JavaScriptJasmine Javascript testingJavaScript Testing with JasmineMany Online resources

*

*