Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add style guideline for const-decl best practices #8884

Merged
merged 4 commits into from May 3, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -15,7 +15,7 @@ intro: The sections below include the coding conventions with respect to top-lev
```ballerina
import ballerina/http;

const int MIN_AGE = 20;
const MIN_AGE = 20;
int repetitions = 0;

service / on ep1 {
Expand All @@ -29,7 +29,7 @@ intro: The sections below include the coding conventions with respect to top-lev
// This import is indented correctly.
import ballerina/http;

const int MIN_AGE = 20; // Not indented correctly.
const MIN_AGE = 20; // Not indented correctly.
int repetitions = 0; // Not indented correctly.

// Not indented correctly.
Expand All @@ -50,6 +50,49 @@ intro: The sections below include the coding conventions with respect to top-lev

* Imports should be sorted alphabetically, first by the organization name and then by the module name.

## Constant declaration

* Use the SCREAMING_SNAKE_CASE for constant names.
lochana-chathura marked this conversation as resolved.
Show resolved Hide resolved

**Example,**
lochana-chathura marked this conversation as resolved.
Show resolved Hide resolved

```ballerina
// don't
const minAge = 20;
const MinAge = 20;
const min_age = 20;

// do
const MIN_AGE = 20;
```

* It is recommended to define the constants omitting the type descriptor, unless the type descriptor is used as the inherent type.
lochana-chathura marked this conversation as resolved.
Show resolved Hide resolved

**Example,**

```ballerina
// don't
const int MIN_AGE = 20;
const decimal TAX_RATE = 0.15;

// do
const MIN_AGE = 20;
const TAX_RATE = 0.15d;
```

* It may be necessary to explicitly define the type descriptor when the constant is a complicated expression.
lochana-chathura marked this conversation as resolved.
Show resolved Hide resolved
lochana-chathura marked this conversation as resolved.
Show resolved Hide resolved

**Example,**

```ballerina
// don't
const COMPLEX_VALUE = (50 * 2 + 100) % 256;

// do
// The explicit `byte` type descriptor ensures this constant can be used where a `byte` is expected.
lochana-chathura marked this conversation as resolved.
Show resolved Hide resolved
const byte COMPLEX_VALUE = (50 * 2 + 100) % 256;
prakanth97 marked this conversation as resolved.
Show resolved Hide resolved
```

## Function definition
* Do not keep spaces between the function name and the open parentheses `(` of the function signature.

Expand Down