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 code styling chapter #18

Merged
merged 4 commits into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions docs/code-styling/bad-code-styling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
---
sidebar_position: 3
---
# Bad Code Style Examples
These examples show how poor code style practices can lead to code that is difficult to read, maintain, and debug. Issues such as unclear naming, improper use of language features, inconsistent formatting, and poor error handling can all contribute to technical debt and reduce code quality.
## Example 1: C - Addition Function
```c
int add(int a,int b){printf("%d",a+b); // adds two numbers}
```
## Why This is Bad Code Style:

No Spaces After Commas: There are no spaces between parameters (a,int b), making the code harder to read.

Non-Descriptive Function Name: The function name (add) is too generic and does not follow good naming conventions.

Inline Comment Without Spacing: The comment (// adds two numbers) is directly attached to the code, which makes it difficult to distinguish between code and comments.

Single-Line Function Body: The entire function is written in one line, which reduces readability and makes debugging difficult.

## Example 2: Python - Improper List Sorting
```py
def srt(lst):
return lst.sort()
```
## Why This is Bad Code Style:

Non-Descriptive Function Name: The function name srt is not descriptive, making it unclear what the function does.

Misuse of sort(): The function uses lst.sort(), which sorts the list in place and returns None, potentially causing confusion if the caller expects a sorted list as a return value.

Lack of Documentation: There is no docstring or comment to explain what the function does or what parameters it takes.

## Example 3: JavaScript - Inconsistent Error Handling
```js
function getData(url) {
fetch(url)
.then(response => {
if (response.status != 200) {
console.log('Error: ' + response.status);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => {});
}
```
## Why This is Bad Code Style:

Inconsistent Error Handling: The catch block is empty, which means that errors are not properly handled or logged, making debugging difficult.

Magic Numbers: The comparison response.status != 200 uses a magic number (200). It would be better to use a named constant for clarity.

Lack of Readable Indentation: The chained .then() calls and inconsistent formatting make the code difficult to read.

Lack of Descriptive Messages: The error message ('Error: ' + response.status) is vague and does not provide much context for the actual issue.
81 changes: 81 additions & 0 deletions docs/code-styling/good-code-styling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
---
sidebar_position: 2
---

# Good Code Style Examples
These examples illustrate the benefits of following good code style practices, such as using descriptive naming, proper spacing, clear documentation, and effective error handling. These practices help improve readability, maintainability, and reduce the likelihood of bugs.

## Example 1: Java - Calculator Class

```java
public class Calculator {
/**
* Adds two numbers and returns the result.
*
* @param a The first number.
* @param b The second number.
* @return The sum of the two numbers.
*/
public int addNumbers(int a, int b) {
return a + b;
}
}
```

## Why This is Good Code Style:

Readable Function Name: The function name (addNumbers) is descriptive and follows a consistent naming convention, making it easy to understand the purpose of the function.

Proper Spacing: The code uses spaces between parameters (a, b) which makes the function signature more readable.

Descriptive Documentation: The comment block (/** */) provides detailed information about the function, including parameters and the return value. This helps other developers understand the code quickly.

## Example 2: Python - Sorting a List

```python
def sort_numbers(numbers):
"""
Sorts a list of numbers in ascending order.

Parameters:
numbers (list): A list of numbers to be sorted.

Returns:
list: A sorted list of numbers.
"""
return sorted(numbers)
```
## Why This is Good Code Style:

Descriptive Function Name: The function name sort_numbers clearly describes what the function does.

Docstring: The function includes a detailed docstring that describes the parameters and return value, making it easier for other developers to understand the purpose and usage of the function.

Simplicity: The function body is simple and uses Python's built-in sorted() function, demonstrating a clear and efficient approach.

## Example 3: JavaScript - Fetching Data from an API
``` js
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
}
```
## Why This is Good Code Style:

Error Handling: The use of try...catch ensures that errors during the fetch operation are properly handled, making the code more robust.

Clear Function Name: The function name fetchData makes it immediately clear that the function is fetching data.

Readability: Proper indentation and spacing make the code easy to follow. The use of descriptive error messages ('Network response was not ok') helps with debugging.




21 changes: 21 additions & 0 deletions docs/code-styling/why-code-style.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
sidebar_position: 1
---

# Why Code Styling is Important

Good code styling is crucial for creating software that is readable, maintainable, and efficient to develop. Code is read far more often than it is written, which means well-styled code makes it easier for developers (including yourself) to understand and modify it later. Proper styling can also help to minimize bugs and reduce onboarding time for new developers joining a project.

## How Messy Code Affects Projects

Messy code, also known as spaghetti code, is code that is difficult to follow and understand due to poor styling, inconsistent conventions, and lack of proper documentation. Such code can cause significant problems for any project:

Harder to Debug: When code is cluttered and inconsistent, finding and fixing bugs becomes a cumbersome task. A lack of structure makes it hard to pinpoint where issues are occurring.

Difficult to Maintain: As projects grow, messy code becomes increasingly hard to manage. Small changes can have unexpected consequences, and modifying existing features can introduce new bugs due to the tangled nature of the code.

Onboarding Challenges: New developers joining a project with poor code styling often struggle to understand the existing codebase. This leads to longer onboarding times and increased chances of mistakes as new team members attempt to understand how things work.

Increased Technical Debt: Messy code contributes to technical debt, meaning future development becomes more costly and time-consuming. Eventually, poorly styled code may need to be entirely rewritten, which can stall progress and delay releases.

Poor Performance: Messy code often lacks optimization, as it is written without forethought or structure. This can lead to performance bottlenecks that could have been avoided with well-structured code from the beginning.