Skip to content

Commit 8e7dbf0

Browse files
restore code tips
1 parent 734ff94 commit 8e7dbf0

38 files changed

+2905
-98
lines changed

app/tag-data.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
"JavaScript": 6,
33
"Debugging": 2,
4+
"Code Tips": 34,
45
"Best Practices": 8,
56
"Next.js": 19,
67
"TypeScript": 3,
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
---
2+
alias: AHA Principle, Avoiding Hasty Abstractions, Moist Programming
3+
category: General
4+
5+
publish: true
6+
slug: avoid-hasty-abstractions-aha
7+
8+
title: Avoid Hasty Abstractions (AHA)
9+
summary: Prefer duplication over the wrong abstraction. Avoid rushing into creating abstractions without a clear understanding of the problem domain.
10+
draft: false
11+
tags: ['Code Tips']
12+
date: 2023-06-23
13+
---
14+
15+
## Usage
16+
17+
### 📝 Guideline
18+
19+
**Avoid Hasty Abstractions**: Prefer duplication over the wrong abstraction.
20+
21+
Avoid rushing into creating abstractions without a clear understanding of the problem domain. It is better to tolerate duplication initially than to create premature or incorrect abstractions.
22+
23+
### 🛠️ How to Apply
24+
25+
- **Prefer duplication**: If you're unsure about the correct abstraction, it's better to have duplicated code temporarily until you fully understand the commonalities and requirements for abstraction. 📊
26+
- **Identify commonalities**: Look for patterns and similarities in the duplicated code. When you notice parts that can be generalized, you'll be in a better position to provide meaningful abstractions. 🧩
27+
- **Consider future requirements**: Instead of prematurely optimizing for performance or designing the "perfect" API, focus on code that can easily adapt to future changes. 🔮
28+
- **Avoid premature abstractions**: If you abstract too early, you might end up with complex code that's difficult to maintain. Wait until you have a good understanding of the use cases before creating abstractions. 🚧
29+
- **Mindful Abstraction**: When the commonalities are clear, it's the right time to create abstractions. Abstract out the shared functionality into functions or modules that accurately capture the essence of the problem. 🌤️
30+
31+
## Pros and Cons
32+
33+
### 👍 Pros
34+
35+
- **Increased Clarity**: Duplicating code initially allows you to gain a deeper understanding of the problem, leading to clearer and more concise abstractions. 🔍
36+
- **Flexible Adaptation**: Delaying abstractions until commonalities are well-understood enables easier adaptation to future changes in requirements or use cases. 🔄
37+
- **Accurate abstractions**: By avoiding hasty abstractions, you ensure that your abstractions accurately represent the underlying problem domain. 🎯
38+
39+
### 👎 Cons
40+
41+
- **Code duplication**: Delaying abstractions may result in some code duplication, which can be seen as a drawback.♻️
42+
- **Maintenance overhead**: Duplicated code may require updates in multiple places if changes are needed, leading to increased maintenance overhead. 🪨
43+
44+
## Examples
45+
46+
### ❌ Bad
47+
48+
```typescript
49+
// Bad Example: Hasty Abstraction that don't provide much value and forces one item per operation
50+
function performOperation(items: Item[], operation: string): void {
51+
for (const item of items) {
52+
performCustomOperation(item, operation)
53+
}
54+
}
55+
56+
function performCustomOperation(item: Item, operation: string): void {
57+
if (operation === 'operation1') {
58+
// Custom operation 1
59+
} else if (operation === 'operation2') {
60+
// Custom operation 2
61+
}
62+
// More operations...
63+
}
64+
```
65+
66+
### ✅ Good
67+
68+
```typescript
69+
// Good Example: Avoid Hasty Abstraction
70+
71+
function performOperation(items: Item[], operation: string): void {
72+
if (operation === 'operation1') {
73+
for (const item of items) {
74+
// Custom operation 1 logic
75+
}
76+
} else if (operation === 'operation2') {
77+
for (const item of items) {
78+
// Custom operation 2 logic
79+
}
80+
}
81+
// More operations...
82+
}
83+
```
84+
85+
## References
86+
87+
### 🔀 Related principles
88+
89+
- **Optimize for change first**: This principle complements AHA by emphasizing the need for flexibility in the face of evolving requirements. 🔧
90+
- [**Don't Repeat Yourself (DRY)**](/blog/dont-repeat-yourself-dry): While AHA suggests temporary duplication, DRY focuses on removing duplication through well-designed abstractions. 🔄
91+
- [**Write Everything Twice (WET)**](/blog/write-everything-twice-wet): AHA encourages careful consideration of abstractions, which aligns with the idea of avoiding unnecessary complexity promoted by WET. ♻️

data/blog/avoid-mental-mapping.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
title: Avoid Mental Mapping
3+
4+
summary: Master the technique of avoiding mental mapping in your code. Enhance readability and eliminate confusion with explicit variable naming.
5+
category: Variables
6+
slug: avoid-mental-mapping
7+
draft: false
8+
tags: ['Code Tips']
9+
date: 2023-05-22
10+
---
11+
12+
## Usage
13+
14+
### 📝 Guideline
15+
16+
**Avoid Variable Mental Mapping**: Use explicit names for variables instead of using an alias. A single-letter name is just a placeholder for the reader to map into the actual concept, and this can lead to confusion.
17+
18+
Mental mapping occurs when a reader or reviewer needs to decipher the meaning of a variable by inferring its purpose from its context. By using clear and descriptive names, you can eliminate mental mapping and make your code more readable and maintainable.
19+
20+
### 🛠️ How to Apply
21+
22+
- Use meaningful variable names that accurately describe the purpose and content of the data. 📌
23+
- Avoid using single-letter variables unless they are widely recognized and have a clear purpose. 🚫
24+
- Refactor code to replace ambiguous or confusing variable names with more descriptive ones. 🔁
25+
26+
## Pros and Cons
27+
28+
### 👍 Pros
29+
30+
- **Improved Code Comprehension**: Clear and explicit variable names enhance code readability and make it easier to understand the purpose of each variable. 📚
31+
- **Reduced Mental Effort**: Eliminating mental mapping reduces cognitive load and allows developers to focus on the logic and functionality of the code. 💡
32+
33+
### 👎 Cons
34+
35+
- **Increased Code Length**: Descriptive variable names can make the code longer, potentially affecting readability in some cases. 📏
36+
- **Naming Challenges**: Finding the right balance between concise and descriptive variable names can be challenging, requiring careful consideration. 🔍
37+
38+
## Examples
39+
40+
### ❌ Bad
41+
42+
```typescript
43+
// Bad
44+
const x = 5 // What does 'x' represent?
45+
const y = 10 // And what about 'y'?
46+
const result = x * y // No context, mental mapping required
47+
```
48+
49+
### ✅ Good
50+
51+
```typescript
52+
// Good
53+
const width = 5 // Descriptive name for the width of a shape
54+
const height = 10 // Descriptive name for the height of a shape
55+
const area = width * height // Clear context, no mental mapping needed
56+
```
57+
58+
## References
59+
60+
### 🔀 Related principles
61+
62+
- **Avoid Abbreviations**: Abbreviating variable names can increase mental mapping. 🚫
63+
- **Use Descriptive Naming**: Clear and meaningful names provide better understanding. 📚
64+
- **Avoid Magic Numbers**: Replace unclear numeric values with named constants. 🔢
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
---
2+
title: Avoid Negative Conditionals
3+
4+
draft: false
5+
tags: ['Code Tips']
6+
date: 2023-06-05
7+
summary: Negatives are harder to understand. Conditional functions should be expressed as positives every time.
8+
category: General
9+
slug: avoid-negative-conditionals
10+
---
11+
12+
## Usage
13+
14+
### 📝 Guideline
15+
16+
**Avoid Negative Conditionals**: Negatives are harder to understand. Conditional functions should be expressed as positives.
17+
18+
Conditional functions that use negative statements can make the code harder to read and comprehend. By expressing conditional logic in positive terms, you can enhance code readability and make it easier to understand the intended behavior.
19+
20+
### 🛠️ How to Apply
21+
22+
- **Use positive conditionals**: Instead of checking for the absence of a condition, check for its presence. This can make the code more straightforward and easier to follow. 🐣
23+
- **Use descriptive variable and function names**: Choose names that clearly convey the purpose of the condition, making the code more self-explanatory. 📛
24+
- **Invert conditions sparingly**: If inverting a condition improves code clarity, do so sparingly. Be mindful of the potential impact on code readability. 🤏
25+
- **Avoid using "not" in function names**: Function names should not include the word "not" as it can make the code less intuitive. Instead, utilize the "not" Boolean operator with the function call itself to express negation. ⛔️
26+
27+
## Pros and Cons
28+
29+
### 👍 Pros
30+
31+
- **Improved readability**: Positive conditionals make the code easier to understand, as they express the desired behavior directly. 😃
32+
- **Reduced cognitive load**: Avoiding negative conditionals helps reduce mental strain and makes it easier to reason about code. 🧠
33+
34+
### 👎 Cons
35+
36+
- **Increased verbosity**: Positive conditionals may require additional code or conditions to handle negative cases, potentially leading to increased verbosity. 💬
37+
- **Risk of error**: If the positive conditionals are not written accurately, there is a possibility of introducing logic errors. ❌
38+
39+
## Examples
40+
41+
### ❌ Bad
42+
43+
```typescript
44+
if (!isNotLoggedIn) {
45+
// Do something if logged in
46+
} else {
47+
// Do something if not logged in
48+
}
49+
```
50+
51+
### ✅ Good
52+
53+
```typescript
54+
if (isLoggedIn) {
55+
// Do something if logged in
56+
} else {
57+
// Do something if not logged in
58+
}
59+
```
60+
61+
## References
62+
63+
### 🔀 Related principles
64+
65+
- **Positive Language Principle**: Using positive language throughout the codebase enhances readability and clarity. 🌟
66+
- **Use Intention-Revealing Names**: Choosing descriptive names for variables and functions helps eliminate the need for negative conditionals by clearly indicating the intention behind the code. 📛
67+
- **Guard Clause Principle**: Utilizing guard clauses helps improve code readability by handling special cases early on and reducing nesting depth. 🚧

data/blog/avoid-side-effects.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
---
2+
title: Avoid side effects
3+
alias: Side Effect Prevention, Side Effect Minimization, Side Effect Avoidance
4+
5+
draft: false
6+
tags: ['Code Tips']
7+
date: 2023-06-12
8+
summary: Improve code reliability by avoiding side effects. Minimize hidden consequences, enhance predictability, and simplify testing.
9+
category: Functions
10+
slug: avoid-side-effects
11+
---
12+
13+
## Usage
14+
15+
### 📝 Guideline
16+
17+
**Avoid Side Effects**: Minimize or eliminate code that modifies state or produces non-obvious consequences.
18+
19+
Code that produces unexpected changes to the system's state or has hidden consequences can be difficult to reason about and debug. By avoiding side effects, you can create code that is more predictable, easier to test, and less prone to bugs.
20+
21+
### 🛠️ How to Apply
22+
23+
- **Immutability**: Favor immutability whenever possible to prevent accidental modifications of shared data. 🚫
24+
- **Pure Functions**: Write pure functions that only depend on their input and produce consistent output, without modifying external state. 🧪
25+
- **Avoid Global State**: Minimize the use of global variables or shared state, as they can lead to hidden dependencies and unintended side effects. 🌍
26+
27+
## Pros and Cons
28+
29+
### 👍 Pros
30+
31+
- **Predictability**: Code without side effects is easier to understand and predict because its behavior is more explicit and deterministic. 🎯
32+
- **Testability**: Side-effect-free code is easier to test, as it can be isolated and its behavior can be verified without the need for complex setup or mocking. 🧪
33+
- **Concurrency**: Code with fewer side effects is generally more amenable to concurrent or parallel execution, as it avoids shared mutable state and potential race conditions. 🏃‍♂️
34+
35+
### 👎 Cons
36+
37+
- **Performance impact**: Avoiding side effects may introduce additional data copies or indirection, impacting performance slightly. However, improved maintainability and reliability often outweigh this trade-off. 🐢
38+
- **Integration challenges**: When working with legacy codebases or third-party libraries that heavily rely on side effects, adopting a side effect free approach can be challenging. 🚧
39+
40+
## Examples
41+
42+
### ❌ Bad
43+
44+
```typescript
45+
// Bad example: Function with side effects
46+
let counter = 0
47+
48+
function incrementCounter() {
49+
counter++
50+
}
51+
52+
incrementCounter()
53+
console.log(counter) // Output: 1
54+
```
55+
56+
### ✅ Good
57+
58+
```typescript
59+
// Good example: Pure function without side effects
60+
function incrementCounter(counter: number): number {
61+
return counter + 1
62+
}
63+
64+
let counter = 0
65+
counter = incrementCounter(counter)
66+
console.log(counter) // Output: 1
67+
```
68+
69+
## References
70+
71+
### 🔀 Related principles
72+
73+
- **Separation of Concerns**: Avoiding side effects is closely related to the principle of separation of concerns, as it promotes modular and decoupled code by isolating state manipulation. 🧩
74+
- **Immutable Data**: The concept of immutability complements side effect prevention by emphasizing the use of unmodifiable data structures to prevent unintended changes. 🔒
75+
- **Pure Functions**: Side effect avoidance aligns with the use of pure functions, which have no side effects and produce consistent results based solely on their input. 🧪
76+
- **Functional Composition**: Pure functions without side effects can be easily composed together to create larger and more complex functions. This encourages modular and reusable code. 🔀

0 commit comments

Comments
 (0)