Static Analysis
Tags: webdev, codecoverage, testing
Published: 2023-02-07 12:23:54

---
title: Static Analysis
published: true
description: 
tags: webdev, codecoverage, testing
cover_image: https://toppng.com/uploads/preview/code-letters-screen-blur-multi-colored-text-11570104627xg3s2ydash.jpg
---

> **What are these texts?**
> I was studing and for me to have some real study done I need to write it down, this is a small collection of topics that I studied in the last few weeks.
> Other links from the same study-pool:
> - [Branching Strategies](https://dev.to/shinspiegel/branching-strategies-535m/edit) > > - [CI / CD](https://dev.to/shinspiegel/ci-cd-nb7)
> - [Critical Rendering Path](https://dev.to/shinspiegel/critical-rendering-path-1acm)
> - [Requirements](https://dev.to/shinspiegel/requirements-7d4)
> - [Release Strategy](https://dev.to/shinspiegel/release-strategy-51be)
> - [REST](https://dev.to/shinspiegel/rest-3877) 
> - [Static Analysis](https://dev.to/shinspiegel/static-analysis-2650)
> - [Web Security](https://dev.to/shinspiegel/web-security-c9h)

## What are "static analysis" tools?

Static analysis tools refer to various tools that examine source code, executables, and even documentation to find problems before they occur. No code is actually executed.

These tools vary widely in scope and purpose, from compiler-level logic error checking and code style enforcement to cloud-based tool suites that cover everything from formatting documentation to analyzing code complexity.

In short, you can think of a static analysis tool as any tool that helps you maintain a healthy codebase without actually running that code.

## Why are they useful to you?

Ultimately, we want successful features/tools/products/etc. Build and deliver. It takes effort, time and money.

In the short term, we can choose to accept technical debt, smelly code, and bad practices.

Ultimately, however, all of these things catch up to us. Technical debt, smelly code, and emerging bugs slow down development cycles, reduce product quality, and ultimately increase the effort, time, and money required to develop a product.

Static analysis tools can help us find and fix these issues more easily before they have a significant impact on our projects, reducing and preventing these issues across the board.

## Code Quality

You can enforce coding standards and analyze dependency graphs.

You can analyze control flow, nesting, and data flow, as well as the complexity of blocks, functions, classes, files, and more.

There are tools to analyze requirements documents or code documents.

They can be used to reformat code or measure test coverage.

These things tend to look small in isolation, but if ignored, the quality of our code can slowly degrade over time.

With the right tools, we can analyze and optimize our code more easily. This makes the process more efficient and therefore more likely to last over the life of our project.

If our code was evaluated the same way by a tool every time, our team might also learn to write code with fewer problems.

Static analysis tools can improve the initial quality of our code, which can reduce the number of issues the tool needs to detect. Through this iterative process, the codebase can be further refined.

In a perfect world, we would start by writing problem-free code. Of course, we don't live in a perfect world and bug-free code is a dream, but if we continually analyze our code, fix those problems, and learn from the process, we can continue to write more efficient code.

## Code Review

The simple answer is that you don't.

A big part of growing up as a software engineer is learning to analyze our code and introduce many of the ideas mentioned above. While reviewing code we can skip any type of tools and apply code analysis.

But building software is much more than just code and yet we only have so much time in the day and so much brain power to spare. Finding and implementing all these different code quality components slows down the code review process considerably and makes it a burden rather than a great learning opportunity.

Incorporating static analytics into the development and/or build pipeline automatically relieves the burden of manually performing analytics. There is no need to apply code patterns by manually commenting out each PR line. Code complexity analysis can be time-consuming and difficult for a developer.

This tool can perform the same analysis every day with the same attention to detail. Relying on static analysis tools also removes the human element from potentially frustrating parts of the review process such as careful design or convention errors.

The tool suggests deviations from an agreed-upon style without the need for back-and-forth between team members. There is no bias. The machine is not in a bad mood and hangs on every little thing.

Either the device succeeds or fails. Less time spent discussing and debating minor points in the review leaves more time for more interesting and important conversations. What tools do well cant happen if its entirely the developers responsibility.

Secure your code reviews and automate as much as possible.

## Tools to use:

These are some common use tools for the most commons scenarios on the Javascript and front-end development.

### ESLint

ESLint is an open source Javascript tool by Zakas in June 2013. Often used to find problematic patterns or code that doesn't follow certain style guidelines. ESLint is written using Node.js to provide a fast runtime environment and easy installation via npm. With ESLint you can enforce coding standards using a fixed set of independent rules. Yes you can enable and disable the rule. These rules are fully binding.

#### Why use ESLint?

JavaScript is a dynamic language that is loosely typed and very prone to developer error. ESLint helps you incorporate guidelines into your coding standards and helps reduce these errors. The main reason for implementing such a guide is that each developer has their own writing style (naming conventions/tabs/single or double quotes for strings etc.). Additionally different styling techniques can make your codebase look different more error prone and more fragile. This can lead to pitfalls that you don't want to face especially when dealing with JavaScript.

#### When to use it?

This is the type of tool that can be used regardless of project size or team. In both cases you should apply the usual standard coding practices/guidelines. Linting tools like ESLint allow developers to find problems without running their own JavaScript code. One of the main reasons for creating ESLint was to allow developers to create their own lining rules.

#### How to use it?

You can install ESLint using npm or yarn:

```sh
npm install eslint --save-dev ## or yarn
```

Note: It is also possible to install ESLint globally rather than locally (using npm install eslint --global). However, this is NOT recommended, and any plugins or shareable configs that you use must be installed locally in either case.

After installing it, initialize it with the following command:

```sh
npx eslint --init
```

Note: — init assumes you have a package.json file already. If you don't, make sure to run npm init or yarn init beforehand.

The moment you're done with the installation and initialization you'll have a .eslintrc.{js,yml,json} file in your directory. In it, you'll see some rules configured like this:

```json
// eslint.rc
{
  "rules": {
    "semi": ["error", "always"],
    "quotes": ["error", "double"]
  }
}
```

If you're here that means you've successfully configured the ESLint. Here's how you can use it:

```sh
npx eslint <your file>.js
## or
npx eslint <folder containing js files>
```

You can also add lint in your `package.json` file (if not already added)

```json
"scripts": {
  ...
  "lint": "eslint .",
  ...
}
```

### Prettier

Prettier applies a consistent code style to your code base (ie code patterns that don't affect the AST). This is because it ignores the original style and recasts the parsed AST to its own rules that use maximum lines. Consider the length and wrap the cords when necessary.

#### Why prettier?

The biggest reason for adopting Prettier is to stop all the ongoing debate about style. Its generally agreed that a general style guide is valuable for a project or team but getting there can be a painful and rewarding process. People are very passionate about how to write specific code and no one likes to spend time writing or getting information.

Prettier is generally recommended for those with existing codebases and JavaScript experience but those who benefit disproportionately are those new to codebases. People might think this is only useful for people with very limited programming experience but we've seen experienced engineers shorten the onboarding time to join the company because they've coded before. Different styles can be used and developers can come. in other programming languages.

What usually happens after using Prettier is that they realize that they actually spent a lot of time and mental energy designing their code. With good editor integration you can hit that magic link key and the code is formatted. It was an eye-opening experience if ever.

#### How to use it?

Prerequisites: Node.js (^10.12.0, or >=12.0.0)
You can install ESLint using npm or yarn:

```sh
npm install prettier --save-dev ## or yarn
touch .prettierrc ## Create the basic configuration file
```

In the configuration file you can extra configure for your taste of for the project needs.

```json
// .prettierrc
{
  "trailingComma": "es5",
  "tabWidth": 4,
  "semi": false,
  "singleQuote": true
}
```

You can run the prettier and format the files with

```sh
npx prettier --write .
```

You can also add lint in your `package.json` file (if not already added)

```json
"scripts": {
  ...
  "lint": "prettier --write .",
  ...
}
```

### SonarQube

From all the options, this is the heavier one.

SonarQube is an open source platform developed by SonarSource for continuous code quality checking. Sonar performs static code analysis and provides detailed reports on code duplication code smells errors and vulnerabilities.

#### Benefits of SonarQube

- **Sustainability** - Reduce complexity and improve application life by duplicating code for potential vulnerabilities.
- **Productivity** - Reduce maintenance costs and operational risk at scale. This eliminates the need to modify the code.
- **Quality** - Code quality control is an integral part of the software development process.
- **Errors** - It detects code errors and prompts developers to automatically fix them before sending output.
- **Consistency** - Determines where code standards are violated and improves quality.

Developers provide functionality that developers need on tight deadlines. It is important for developers to compile quality code multiple times due to potential code duplication errors and deployment complexity.

#### How to use it?

Pre-requisites: Docker and Docker-compose

Create a docker compose file, add the follow content:

```yml
## docker-compose.yml
## https://github.com/SonarSource/docker-sonarqube/blob/master/example-compose-files/sq-with-postgres/docker-compose.yml
version: "3"
services:
  sonarqube:
    image: sonarqube:community
    hostname: sonarqube
    container_name: sonarqube
    depends_on:
      - db
    environment:
      SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonar
      SONAR_JDBC_USERNAME: sonar
      SONAR_JDBC_PASSWORD: sonar
    volumes:
      - sonarqube_data:/opt/sonarqube/data
      - sonarqube_extensions:/opt/sonarqube/extensions
      - sonarqube_logs:/opt/sonarqube/logs
    ports:
      - "9000:9000"
  db:
    image: postgres:12
    hostname: postgresql
    container_name: postgresql
    environment:
      POSTGRES_USER: sonar
      POSTGRES_PASSWORD: sonar
      POSTGRES_DB: sonar
    volumes:
      - postgresql:/var/lib/postgresql
      - postgresql_data:/var/lib/postgresql/data

volumes:
  sonarqube_data:
  sonarqube_extensions:
  sonarqube_logs:
  postgresql:
  postgresql_data:
```

after the file created you just need a simple `docker-compose up` on the folder with the file to start the sonarqube.