113 lines
1.9 KiB
Markdown
113 lines
1.9 KiB
Markdown
# Coding Standards
|
|
|
|
## Code Structure
|
|
|
|
### No Else Blocks - Use Early Returns
|
|
|
|
Always prefer early returns and guard clauses over else blocks. This reduces nesting and improves readability.
|
|
|
|
**❌ Bad:**
|
|
```typescript
|
|
if (condition) {
|
|
// do something
|
|
return result;
|
|
} else {
|
|
// do something else
|
|
return otherResult;
|
|
}
|
|
```
|
|
|
|
**✅ Good:**
|
|
```typescript
|
|
if (condition) {
|
|
return result;
|
|
}
|
|
|
|
return otherResult;
|
|
```
|
|
|
|
**❌ Bad:**
|
|
```typescript
|
|
if (error) {
|
|
throw new Error('Failed');
|
|
} else {
|
|
return processData();
|
|
}
|
|
```
|
|
|
|
**✅ Good:**
|
|
```typescript
|
|
if (error) {
|
|
throw new Error('Failed');
|
|
}
|
|
|
|
return processData();
|
|
```
|
|
|
|
### Multiple Conditions
|
|
|
|
For multiple conditions, stack guard clauses:
|
|
|
|
**❌ Bad:**
|
|
```typescript
|
|
if (cas !== undefined) {
|
|
if (cas === 0 && existing) {
|
|
return false;
|
|
} else {
|
|
if (cas > 0 && (!existing || existing.modifyIndex !== cas)) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
**✅ Good:**
|
|
```typescript
|
|
if (cas === 0 && existing) {
|
|
return false;
|
|
}
|
|
|
|
if (cas > 0 && (!existing || existing.modifyIndex !== cas)) {
|
|
return false;
|
|
}
|
|
```
|
|
|
|
### No Unnecessary Comments
|
|
|
|
Avoid conversational comments like "let's", "now we", etc. Code should be self-documenting through good naming.
|
|
|
|
**❌ Bad:**
|
|
```typescript
|
|
// Let's check if the user exists
|
|
const user = await findUser(id);
|
|
|
|
// Now let's validate the permissions
|
|
if (!user.hasPermission()) {
|
|
throw new Error();
|
|
}
|
|
```
|
|
|
|
**✅ Good:**
|
|
```typescript
|
|
const user = await findUser(id);
|
|
|
|
if (!user.hasPermission()) {
|
|
throw new UnauthorizedException();
|
|
}
|
|
```
|
|
|
|
Comments should explain **why**, not **what**.
|
|
|
|
**✅ Acceptable:**
|
|
```typescript
|
|
// Consul API requires plain text "true"/"false" responses, not JSON
|
|
return success.toString();
|
|
```
|
|
|
|
## Benefits
|
|
|
|
1. **Reduced Nesting**: Flatter code structure
|
|
2. **Better Readability**: Main logic flow is clear
|
|
3. **Easier Maintenance**: Less cognitive load
|
|
4. **Clearer Intent**: Guard clauses make preconditions explicit
|