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

if statements only allow SINGLE boolean expressions #31

Open
coolaj86 opened this issue Mar 28, 2022 · 0 comments
Open

if statements only allow SINGLE boolean expressions #31

coolaj86 opened this issue Mar 28, 2022 · 0 comments
Labels
syntax the strict subset of JavaScript that is AJScript

Comments

@coolaj86
Copy link
Collaborator

This rule is taken from Zig.

❌ Bad Example

if (!(new Date() < expiresAt && new Date() > activeAt)) {
    throw new Error("not valid");
}
if (!(Date.now() < expires)) {
    throw new Error("expired");
}

✅ Good Example

let now = Date.now();
let isValid = now < expiresAt && now >= activeAt;
if (!isValid) {
    throw new Error("not valid");
}
let now = Date.now();
let isActive = now < expiresAt;
if (!isActive) {
    throw new Error("expired");
}

Rationale

Complex expressions become quadratically more difficult as they are expanded. Limiting if statements to simple expressions improves readability, generally, and also causes the code to become more self-documenting (i.e. isActive vs now < expiresAt && now >= activeAt).

Also, due to the nature of JavaScript (i.e. NaN comparisons), it's easy to have false conditions such as now > expires_at == false when bugs have crept in now > NaN == false.

Using named boolean expressions (i.e. isActive) that can easily be negated (i.e. !isActive) improves correctness and security.

@coolaj86 coolaj86 added the syntax the strict subset of JavaScript that is AJScript label Mar 28, 2022
@coolaj86 coolaj86 changed the title if statements only allow single boolean expressions if statements only allow SINGLE boolean expressions Feb 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
syntax the strict subset of JavaScript that is AJScript
Projects
None yet
Development

No branches or pull requests

1 participant