Skip to content

Coding Guidelines

Kantapon Hemmadhun edited this page Nov 7, 2024 · 16 revisions

YumeLink Coding Guidelines

Coding Style

Follow flake8 coding style with

  • flake8
  • flake8-docstring

Example:

def calculate_area(radius):
    """Calculate the area of a circle given its radius.
    
    Args:
        radius (float): The radius of the circle.
    
    Returns:
        float: The area of the circle.
    """
    if radius < 0:
        raise ValueError("Radius cannot be negative")
    return 3.14159 * radius ** 2

coding conventions

DRY - Don't repeat yourself

Avoid duplicating code. If you find yourself repeating similar code in different parts of the project, refactor it into reusable functions, classes, or mixings.

Example:

from django.db import models

class Author(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField()
    date_of_death = models.DateField(null=True, blank=True)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

Don't reinvent the wheel

Use built-in libraries and standard functions instead of recreating them. Prefer well-tested third-party libraries for common tasks.

Example:

from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    return render(request, 'dashboard.html')

Query optimization

Use efficient data retrieval strategies, such as limiting fields selected, avoiding unnecessary joins, and leveraging indexing where applicable.

  • Prefer parameterized queries to avoid SQL injection. When possible, avoid redundant queries by caching frequently accessed data.

Example:

books = Book.objects.select_related('author').only('title', 'author__name')

Error Handling

  • Handle exceptions gracefully using try-except blocks.
  • For complex functions, log exceptions with meaningful error messages to facilitate debugging.
  • Do not expose sensitive error messages in production.

Example:

try:
    room = Room.objects.get(id=room_id)
except Room.DoesNotExist:
    raise Http404("Room not found")

Sensitive data settings

Keep sensitive data, such as SECRET_KEY, database credentials, and API keys, in a .env file, using django-environ or python-decouple for environment variable management.

Example:

  1. Install django-environ or Install python-decouple:
pip install django-environ
pip install python-decouple
  1. Create a .env file in the root of your project
# .env file
SECRET_KEY=your-secret-key-here
DEBUG=False
DATABASE_URL=postgres://user:password@localhost:5432/mydatabase
ALLOWED_HOSTS=yourdomain.com
  1. Configure settings.py to use python-decouple or use django-environ:
# settings.py
import environ

# Initialize environment variables
env = environ.Env()
environ.Env.read_env()  # Reads .env file
# settings.py
from decouple import config

Testing

Write unit tests using Django’s TestCase and ensure adequate test coverage.

Example:

from django.test import TestCase
from .models import Room

class RoomTest(TestCase):
    def test_room_creation(self):
        room = Room.objects.create(name="Deluxe", price=10000)
        self.assertEqual(room.name, "Deluxe")

Resolve conflicts with group review and merge.

Ensure code is reviewed via GitHub Pull Requests before merging to the main branch. Use meaningful commit messages.

Example:

git commit -m "Added user data to database system"

Issue format

Use a structured format for all issues. All issue form configuration files must begin with name, description, and body key-value pairs.

Example:

<feature in merge's purpose>
<what you did (list)>
- what you did 1
- ...
<may conflict> (optional)
- <file affected> 
- <existing feature affected>

<how to use on your device after this merge> (optional) (can mention in code-text-channal in discord instead>
1. step 1
2. ...

<notes> (Optional)
- what else should team knows

or

Logging and sign in with OAuth
- replaced current log in and sign in method with OAuth

May conflict
- url.py
- user sign in and log in feature

How to use on your device
1. log in
2. choose OAuth option
3. log in with your email

Note:
- after you signed in you should see your user object in mongoDB

Clone this wiki locally