2 Coding Standards
Jan Klattenhoff edited this page 2025-03-19 12:02:22 +01:00

Coding Standards

This page outlines the coding standards and style guidelines for the Casino Gaming Platform.

General Principles

  • Readability: Code should be easy to read and understand
  • Maintainability: Code should be easy to maintain and extend
  • Consistency: Coding style should be consistent across the codebase
  • Testability: Code should be designed with testing in mind
  • Documentation: Code should be well-documented

Version Control

Git Workflow

We follow a feature branch workflow:

  1. Create a feature branch from main
  2. Make changes and commit to the feature branch
  3. Create a pull request to merge back into main
  4. Ensure CI passes and the code is reviewed
  5. Merge the pull request

Commit Messages

We use semantic commit messages:

Format: <type>(<scope>): <subject>

Where <type> is one of:

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation changes
  • style: Formatting, missing semicolons, etc; no code change
  • refactor: Code refactoring
  • test: Adding or refactoring tests
  • chore: Updating build tasks, etc; no production code change

References:

Examples:

feat: add user balance display
fix(auth): resolve token expiration issue
docs: update API documentation

Frontend (Angular)

Code Organization

Directory Structure

src/
├── app/
│   ├── feature/        # Feature modules
│   │   ├── home/       # Home feature
│   │   ├── deposit/    # Deposit feature
│   │   └── ...
│   ├── shared/         # Shared components/services
│   │   ├── components/ # Reusable components
│   │   ├── services/   # Shared services
│   │   └── ...
│   ├── model/          # Data models/interfaces
│   └── service/        # Application services
├── assets/             # Static assets
└── environments/       # Environment configurations

Naming Conventions

  • Files: kebab-case

    • Components: user-profile.component.ts
    • Services: auth.service.ts
    • Models: user.model.ts
  • Classes: PascalCase with suffixes

    • Components: UserProfileComponent
    • Services: AuthService
    • Guards: AuthGuard
    • Directives: HighlightDirective
    • Pipes: FormatDatePipe
  • Component Selectors: kebab-case with prefix

    • app-user-profile
    • app-navbar
  • Interfaces and Models: PascalCase

    • User
    • GameSession
  • Enums: PascalCase

    • TransactionType
    • GameStatus
  • Constants: UPPER_SNAKE_CASE

    • MAX_SESSION_TIME
    • API_ENDPOINTS

Coding Style

  • Use TypeScript's strict mode
  • Use typed variables and function returns
  • Prefer arrow functions for callbacks
  • Use async/await for asynchronous operations
  • Use template strings for string interpolation
  • Use destructuring for object and array access
  • Use the spread operator for shallow copies

Component Best Practices

  • One component per file
  • Keep components small and focused
  • Use OnPush change detection strategy where appropriate
  • Use input and output bindings for component communication
  • Use services for cross-component communication
  • Implement lifecycle hooks explicitly
  • Document component inputs and outputs

Service Best Practices

  • Use the singleton pattern for services
  • Use dependency injection to provide services
  • Keep services focused on a single responsibility
  • Use RxJS for handling asynchronous operations
  • Document service methods and parameters

RxJS Usage

  • Use appropriate operators (map, filter, switchMap, etc.)
  • Complete observables to prevent memory leaks
  • Use the async pipe in templates
  • Handle errors with catchError
  • Use shareReplay for sharing observable results

Angular Template Guidelines

  • Use structural directives (*ngIf, *ngFor) sparingly
  • Prefer ngContainer for structural directives
  • Limit template complexity
  • Use trackBy with *ngFor for performance
  • Avoid logic in templates
  • Use pipes for data transformation

CSS/SCSS Guidelines

  • Use TailwindCSS utility classes
  • Create custom utility classes with @apply directive
  • Use scoped component styles
  • Follow mobile-first responsive design
  • Use CSS variables for theming

Backend (Java/Spring Boot)

Code Organization

Package Structure

de.szut.casino/
├── config/               # Configuration classes
├── user/                 # User module
│   ├── UserController.java
│   ├── UserService.java
│   ├── UserRepository.java
│   ├── UserEntity.java
│   └── dto/              # Data Transfer Objects
│       ├── CreateUserDto.java
│       └── GetUserDto.java
├── deposit/              # Deposit module
├── game/                 # Game module
├── security/             # Security configuration
└── exceptionHandling/    # Exception handling

Naming Conventions

  • Classes: PascalCase with suffixes

    • Controllers: UserController
    • Services: UserService
    • Repositories: UserRepository
    • Entities: UserEntity
    • DTOs: CreateUserDto, GetUserDto
    • Exceptions: ResourceNotFoundException
  • Methods: camelCase

    • Controller methods: getUser(), createUser()
    • Service methods: findUserById(), updateUserBalance()
    • Repository methods: follow Spring Data naming conventions
  • Variables: camelCase

    • Entity fields: firstName, createdAt
    • Method parameters: userId, requestBody
    • Local variables: userEntity, validationResult
  • Constants: UPPER_SNAKE_CASE

    • DEFAULT_PAGE_SIZE
    • JWT_EXPIRATION_TIME

Java Coding Style

  • Follow standard Java conventions
  • Use Java 17 features where appropriate
  • Use consistent indentation (4 spaces)
  • Limit line length to 120 characters
  • Order class members logically
  • Document public APIs with Javadoc

Spring Best Practices

  • Use constructor injection instead of field injection
  • Use Spring Data repositories for database access
  • Use Spring Security for authentication/authorization
  • Use DTO pattern for API requests/responses
  • Use exception handling for error responses
  • Use validation annotations for input validation

API Design Guidelines

  • Follow RESTful conventions
  • Use appropriate HTTP methods (GET, POST, PUT, DELETE)
  • Use consistent URL patterns
  • Use proper HTTP status codes
  • Provide meaningful error messages
  • Document API with OpenAPI/Swagger
  • Version the API

Database Access

  • Use JPA for database access
  • Define explicit column names and types
  • Use appropriate indexes
  • Define relationship mappings explicitly
  • Use transactions for data consistency
  • Consider performance implications of queries

Testing Guidelines

  • Write unit tests for services and controllers
  • Use MockMvc for controller tests
  • Use Mockito for mocking dependencies
  • Use JUnit 5 for tests
  • Test happy path and error cases
  • Use test data builders for test data

Documentation

Code Documentation

  • Document public methods with JavaDoc or TSDoc
  • Document complex logic with inline comments
  • Document non-obvious behavior
  • Keep documentation up-to-date with code changes

API Documentation

  • Use OpenAPI/Swagger for API documentation
  • Document request and response formats
  • Document error responses
  • Document authentication requirements
  • Document rate limiting

Wiki Documentation

  • Document architecture and design decisions
  • Document deployment and setup procedures
  • Document troubleshooting steps
  • Keep wiki up-to-date with code changes

Security Practices

  • Never commit secrets or credentials
  • Use environment variables for configuration
  • Validate all user input
  • Use prepared statements for database queries
  • Use HTTPS for all communication
  • Follow OWASP security guidelines
  • Implement proper error handling
  • Use proper access controls

Performance Considerations

  • Use caching where appropriate
  • Optimize database queries
  • Use pagination for large result sets
  • Optimize frontend rendering
  • Minimize HTTP requests
  • Use appropriate data structures and algorithms
  • Consider scalability in design decisions

Accessibility

  • Follow WCAG 2.1 AA guidelines
  • Use semantic HTML
  • Provide alternative text for images
  • Ensure keyboard navigation works
  • Test with screen readers
  • Consider color contrast
  • Support text scaling

Cross-Browser Compatibility

  • Support latest versions of Chrome, Firefox, Safari, and Edge
  • Test on different browsers
  • Use feature detection instead of browser detection
  • Consider mobile browsers
  • Use polyfills for older browsers

Conclusion

Adherence to these coding standards helps maintain a consistent, high-quality codebase. These standards are guidelines rather than strict rules, and there may be valid reasons to deviate from them in certain situations. Use your best judgment and discuss with the team when in doubt.