Flutter Dev

Flutter Dev

1629453805

Dart Code Metrics | Tools to Analyze and Improve Your Code Quality

Dart Code Metrics

Dart Code Metrics is a static analysis tool that helps you analyse and improve your code quality.

Links

Usage

Analyzer plugin

A plugin for the Dart analyzer package providing additional rules from Dart Code Metrics. All issues produced by rules or anti-patterns will be highlighted in IDE.

Install package as a dev dependency

OR

add it manually to pubspec.yaml

and then run

Add configuration to analysis_options.yaml

Reload IDE to allow the analyzer to discover the plugin

CLI

The package can be used as a command-line tool. It will produce a result in one of the supported formats:

Basic usage

Install the package as listed in the Analyzer plugin usage example.

If you want the command-line tool to check rules, you should configure rules entry in the analysis_options.yaml first.

dart pub run dart_code_metrics:metrics lib

# or for a Flutter package
flutter pub run dart_code_metrics:metrics lib

Global usage

dart pub global activate dart_code_metrics
dart pub global run dart_code_metrics:metrics lib

# or for a Flutter package
flutter pub global activate dart_code_metrics
flutter pub global run dart_code_metrics:metrics lib

Options

Usage: metrics [arguments...] <directories>

-h, --help                                        Print this usage information.


-r, --reporter=<console>                          The format of the output of the analysis
                                                  [console (default), console-verbose, codeclimate, github, gitlab, html, json]
-o, --output-directory=<OUTPUT>                   Write HTML output to OUTPUT
                                                  (defaults to "metrics")


    --cyclomatic-complexity=<20>                  Cyclomatic Complexity threshold
    --lines-of-code=<100>                         Lines of Code threshold
    --maximum-nesting-level=<5>                   Maximum Nesting Level threshold
    --number-of-methods=<10>                      Number of Methods threshold
    --number-of-parameters=<4>                    Number of Parameters threshold
    --source-lines-of-code=<50>                   Source lines of Code threshold
    --weight-of-class=<0.33>                      Weight Of a Class threshold


    --root-folder=<./>                            Root folder
                                                  (defaults to current directory)
    --exclude=<{/**.g.dart,/**.template.dart}>    File paths in Glob syntax to be exclude
                                                  (defaults to "{/**.g.dart,/**.template.dart}")


    --set-exit-on-violation-level=<warning>       Set exit code 2 if code violations same or higher level than selected are detected
                                                  [noted, warning, alarm]

Library

See example/example.dart.

Configuration

To configure the package add the dart_code_metrics entry to the analysis_options.yaml and update plugins list of the analyzer.

analyzer:
  plugins:
    - dart_code_metrics

dart_code_metrics:
  anti-patterns:
    - ... # add this entry to configure the list of anti-patterns
  metrics:
      ... # add this entry to configure the list of reported metrics
  metrics-exclude:
    - ... # add this entry to configure the list of files that should be ignored by metrics
  rules:
    - ... # add this entry to configure the list of rules

Basic config example:

analyzer:
  plugins:
    - dart_code_metrics

dart_code_metrics:
  anti-patterns:
    - long-method
    - long-parameter-list
  metrics:
    cyclomatic-complexity: 20
    number-of-arguments: 4
    maximum-nesting-level: 5
  metrics-exclude:
    - test/**
  rules:
    - newline-before-return
    - no-boolean-literal-compare
    - no-empty-block
    - prefer-trailing-comma
    - prefer-conditional-expressions
    - no-equal-then-else

Configuring a rules entry

To enable a rule add its id to the rules entry. All rules have severity which can be overridden with severity config entry. For example,

dart_code_metrics:
  rules:
    - newline-before-return:
        severity: style

will set severity to style. Available severity values: none, style, performance, warning, error.

Rules with a configurable badge have additional configuration, check out their docs for more information.

Configuring a metrics entry

To enable a metric add its id to the metrics entry in the analysis_options.yaml. All metrics can take a threshold value. If no value was provided, the default value will be used.

Configuring a metrics-exclude entry

To exclude files from a metrics report provide a list of regular expressions for ignored files. For example:

dart_code_metrics:
  metrics-exclude:
    - test/**
    - lib/src/some_file.dart

Configuring an anti-pattern entry

To enable an anti-pattern add its id to the anti-patterns entry.

Ignoring a rule or anti-pattern

If a specific rule or anti-pattern warning should be ignored, it can be flagged with a comment. For example,

// ignore: no-empty-block
void emptyFunction() {}

tells the analyzer to ignore this instance of the no-empty-block warning.

End-of-line comments are supported as well. The following communicates the same thing:

void emptyFunction() {} // ignore: no-empty-block

To ignore a rule for an entire file, use the ignore_for_file comment flag. For example,

// ignore_for_file: no-empty-block
...

void emptyFunction() {}

tells the analyzer to ignore all occurrences of the kebab-case-types warning in this file.

It's the same approach that the dart linter package use.

Additionally, exclude entry for the analyzer config can be used to ignore files. For example,

analyzer:
  exclude:
    - example/**

will work both for the analyzer and for this plugin.

If you want a specific rule to ignore files, you can configure exclude entry for it. For example,

dart_code_metrics:
  rules:
    no-equal-arguments:
      exclude:
        - test/**

Metrics

Metrics configuration is described here.

Available metrics:

Rules

Rules are grouped by a category to help you understand their purpose.

Right now auto-fixes are available through an IDE context menu (ex. VS Code Quick Fix).

Rules configuration is described here.

Common

Flutter specific

Intl specific

Angular specific

Anti-patterns

Like rules, anti-patterns display issues in IDE, except that their configuration is based on a metrics entry in the config.

Troubleshooting

Please read the following guide if the plugin is not working as you'd expect it to work.

Contributing

If you are interested in contributing, please check out the contribution guidelines. Feedback and contributions are welcome!

How to reach us

Please feel free to ask any questions about this tool. Join our community chat on Telegram. We speak both English and Russian.

LICENCE

MIT

 analyzer:
   plugins:
     - dart_code_metrics

 dart_code_metrics:
   anti-patterns:
     - long-method
     - long-parameter-list
   metrics:
     cyclomatic-complexity: 20
     maximum-nesting-level: 5
     number-of-parameters: 4
     source-lines-of-code: 50
   metrics-exclude:
     - test/**
   rules:
     - newline-before-return
     - no-boolean-literal-compare
     - no-empty-block
     - prefer-trailing-comma
     - prefer-conditional-expressions
     - no-equal-then-else
 $ dart pub get

 # or for a Flutter package
 $ flutter pub get
 dev_dependencies:
   dart_code_metrics: ^4.1.0
 $ dart pub add --dev dart_code_metrics

 # or for a Flutter package
 $ flutter pub add --dev dart_code_metrics

Use this package as an executable

1. Install it

You can install the package from the command line:

$ dart pub global activate dart_code_metrics

Use it

The package has the following executables:

$ metrics

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add dart_code_metrics

With Flutter:

 $ flutter pub add dart_code_metrics

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):


dependencies:
  dart_code_metrics: ^4.1.0

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:dart_code_metrics/analyzer_plugin.dart';
import 'package:dart_code_metrics/config.dart';
import 'package:dart_code_metrics/lint_analyzer.dart';
import 'package:dart_code_metrics/reporters.dart';
import 'package:dart_code_metrics/unused_files_analyzer.dart';

example/example.dart

import 'dart:io';

import 'package:dart_code_metrics/lint_analyzer.dart';

Future<void> main() async {
  // Get some folder you would like to analyze
  const foldersToAnalyze = ['lib', 'test'];

  // Root folder path is used to resolve relative file paths
  const rootFolder = 'projectRoot';

  // First of all config has to be created for a checker
  const config = LintConfig(
    excludePatterns: ['test/resources/**'],
    excludeForMetricsPatterns: ['test/**'],
    metrics: {
      'maximum-nesting-level': '5',
      'number-of-methods': '10',
    },
    rules: {
      'double-literal-format': {},
      'newline-before-return': {'severity': 'info'},
    },
    antiPatterns: {'long-method': {}},
  );

  const analyzer = LintAnalyzer();

  final result =
      await analyzer.runCliAnalysis(foldersToAnalyze, rootFolder, config);

  // Now runner.results() contains some insights about analyzed code. Let's report it!
  // For a simple example we would report results to terminal

  // Now pass collected analysis reports from runner to reporter and that's it
  await analyzer
      .getReporter(
        name: 'console',
        output: stdout,
        config: config,
        reportFolder: '.',
      )
      ?.report(result);

  // There is also JsonReporter for making machine-readable reports
  // HtmlReporter produces fancy html-documents with bells and whistles
  // And CodeClimateReporter produces reports that are widely understood by various CI tools
  // If none of these fits your case you can always access raw analysis info via results() method of runner and process it any way you see fit
}

Download Details:

Author:  dart-code-checker

Source Code: https://github.com/dart-code-checker/dart-code-metrics 
 

What is GEEK

Buddha Community

Dart Code Metrics | Tools to Analyze and Improve Your Code Quality
Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Tyrique  Littel

Tyrique Littel

1604023200

Effective Code Reviews: A Primer

Peer code reviews as a process have increasingly been adopted by engineering teams around the world. And for good reason — code reviews have been proven to improve software quality and save developers’ time in the long run. A lot has been written about how code reviews help engineering teams by leading software engineering practitioners. My favorite is this quote by Karl Wiegers, author of the seminal paper on this topic, Humanizing Peer Reviews:

Peer review – an activity in which people other than the author of a software deliverable examine it for defects and improvement opportunities – is one of the most powerful software quality tools available. Peer review methods include inspections, walkthroughs, peer deskchecks, and other similar activities. After experiencing the benefits of peer reviews for nearly fifteen years, I would never work in a team that did not perform them.

It is worth the time and effort to put together a code review strategy and consistently follow it in the team. In essence, this has a two-pronged benefit: more pair of eyes looking at the code decreases the chances of bugs and bad design patterns entering your codebase, and embracing the process fosters knowledge sharing and positive collaboration culture in the team.

Here are 6 tips to ensure effective peer reviews in your team.

1. Keep the Changes Small and Focused

Code reviews require developers to look at someone else’s code, most of which is completely new most of the times. Too many lines of code to review at once requires a huge amount of cognitive effort, and the quality of review diminishes as the size of changes increases. While there’s no golden number of LOCs, it is recommended to create small pull-requests which can be managed easily. If there are a lot of changes going in a release, it is better to chunk it down into a number of small pull-requests.

2. Ensure Logical Coherence of Changes

Code reviews are the most effective when the changes are focused and have logical coherence. When doing refactoring, refrain from making behavioral changes. Similarly, behavioral changes should not include refactoring and style violation fixes. Following this convention prevents unintended changes creeping in unnoticed in the code base.

3. Have Automated Tests, and Track Coverage

Automated tests of your preferred flavor — units, integration tests, end-to-end tests, etc. help automatically ensure correctness. Consistently ensuring that changes proposed are covered by some kind of automated frees up time for more qualitative review; allowing for a more insightful and in-depth conversation on deeper issues.

4. Self-Review Changes Before Submitting for Peer Review

A change can implement a new feature or fix an existing issue. It is recommended that the requester submits only those changes that are complete, and tested for correctness manually. Before creating the pull-request, a quick glance on what changes are being proposed helps ensure that no extraneous files are added in the changeset. This saves tons of time for the reviewers.

5. Automate What Can Be Automated

Human review time is expensive, and the best use of a developer’s time is reviewing qualitative aspects of code — logic, design patterns, software architecture, and so on. Linting tools can help automatically take care of style and formatting conventions. Continuous Quality tools can help catch potential bugs, anti-patterns and security issues which can be fixed by the developer before they make a change request. Most of these tools integrate well with code hosting platforms as well.

6. Be Positive, Polite, and Respectful

Finally, be cognizant of the fact that people on both sides of the review are but human. Offer positive feedback, and accept criticism humbly. Instead of beating oneself upon the literal meaning of words, it really pays off to look at reviews as people trying to achieve what’s best for the team, albeit in possibly different ways. Being cognizant of this aspect can save a lot of resentment and unmitigated negativity.

#agile #code quality #code review #static analysis #code analysis #code reviews #static analysis tools #code review tips #continuous quality #static analyzer

Samanta  Moore

Samanta Moore

1621137960

Guidelines for Java Code Reviews

Get a jump-start on your next code review session with this list.

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started. We’ve put together a list of things you should keep in mind when you’re reviewing Java code. Read on!

1. Follow Java Code Conventions

2. Replace Imperative Code With Lambdas and Streams

3. Beware of the NullPointerException

4. Directly Assigning References From Client Code to a Field

5. Handle Exceptions With Care

#java #code quality #java tutorial #code analysis #code reviews #code review tips #code analysis tools #java tutorial for beginners #java code review

Max Weber

1617264834

SonarQube - Code Quality and Code Security - Code Quality Gates

Code Metrics are important for business and developer. For that, SonarQube offers a nice solution. Unfortunately, SonarQube does currently not provide a full-blown Dart & Flutter Solution. Still, amazing community members created a Plugin to make it possible to have at least the key figures and a Quality Gate for Flutter & Dart.

https://youtu.be/QD5J8YvQPPM

#flutter #dart #sonarqube #code #metrics #tutorial

Tyrique  Littel

Tyrique Littel

1604016000

Embold Is Like Autocorrect For Code, Says Vishal Rai, Founder & CEO

In our digital world, software is king. In a world so heavily dependent on software, poor code quality can result in grave consequence, from billions of dollars in lost revenue, to even fatal accidents. Here’s where Embold comes in—a static code analysis product aimed at empowering developers to do their best work.

Embold is a general-purpose static code analyser that has been designed for developers to analyse and improve their code by identifying issues across four dimensions, including design and duplication. We, at Analytics India Magazine, spoke to founder and CEO, Vishal Rai, to understand how Embold can detect anti-patterns in code for seamless integration.

Embold started a decade ago, with the vision of creating a product that can revolutionise the way developers write and design code. According to Vishal Rai, the idea was to develop a tool for software engineers and developers to write code faster and of better quality. And, after a time of extensive research and development, Vishal Rai, along with his partner Sudarshan Bhide launched their product in 2018.


Play

“We have noticed an interesting trend — as teams started becoming bigger, the issues in software started increasing as well and it was very frustrating when you were on programs which weren’t achieving their stated goals because of poor quality,” said Rai. “And that’s where we saw the opportunity of helping companies to write the product as great as Google or Apple and decided to reinvent software analytics.”

Embold — Empowering Developers to Reach Their Highest Potential

Developers always undergo immense pressure of building their products faster at the best quality possible, and such pressure can lead to compromised code quality. This impact of one line of code or one weak link can create significant issues and can massively affect the entire company. And that is why Rai believes that developers need support in being more productive. With Embold, Vishal and Sudharshan brought in a technology that can help developers be more efficient in their work and make the process of software development easy. Explaining the technology, Rai compared it with “autocorrect for code.” He said, “If you look at the legacy tools, they were built for the waterfall model, aka linear-sequential life cycle model, where one release took six months which gave enough time to test the tools. But in the current time, everything is fast, and thus developers require tools that can help them work fast and give them feedback that can be easily implemented in their workflow.” And that’s where Embold’s platform fits into the workflow that helps them find problems and maintain their code.  As a matter of fact, Rai acknowledges that there have been many great tools, already in the market, but all of them have been created for great engineers. However, today, not every engineer is necessarily as experienced as others, and in such cases, it is imperative to make tools that are easy to use and help developers analyse their software. “Embold has been built for the future, the technologies that we have ingrained have neural networks, state-of-the-art in-memory databases and analysers that are far more evolved than legacy tools,” said Rai. “Embold has been created to enable people who aren’t as skilled to write better codes. Not only it fills the skills gap but also brings the new age developers closer to the best developers on the planet.”


#featured #bugs and errors in code #embold a autocorrect for code #embold find bugs and errors in code #embold for developers #embold help developers #embold maintains code quality #embold revolutionise writing code #static code analyser