These guidelines promote clean, consistent, and maintainable code for ERP systems.
I. Readability
Write code that is easy to understand.
Code Formatting
- Indentation: Use 4 spaces, no tabs.
if (condition) {
let variable = 'value';
} - Spacing: Spaces after keywords, around operators, not before/after parentheses. No trailing whitespace. Blank lines between code blocks.
if (condition) {
const result = value1 + value2;
this.doSomething(result);
} - Line Length: Soft limit 120, aim for 80 characters. Break long lines.
const longName = this.someObject.someMethod(arg1, arg2, arg3);
- Braces: Opening brace on the same line, closing brace on its own line.
if (condition) {
// Code
} else {
// Code
} - Semicolons: Always use semicolons.
Naming Conventions
- Descriptive, meaningful names. Avoid abbreviations. Use English.
- Variables: camelCase.
const
(value types),let
(objects, reassignment),var
(global).const customerName = 'John Doe'; let orderTotal = 0;
- Constants: UPPERCASE_UNDERSCORE.
const MAX_VALUE = 100;
- Functions/Methods: camelCase.
function calculateTotal() {} order.getTotal();
- Classes: PascalCase.
class CustomerOrder {}
- Files: camelCase.
customerOrder.js
- Directory Structure: Group by functionality (e.g.,
models
,controllers
). Use consistent naming (e.g., lowercase). - Database:
- Table names: Plural, lowercase (e.g.,
customers
). - Column names: snake_case, lowercase (e.g.,
customer_id
).
- Table names: Plural, lowercase (e.g.,
Comments and Documentation
- Explain why, not just what.
- Clarify complex logic, algorithms.
- Document parameters, return values (using JSDoc).
/**
* Calculates total order amount.
* @param {Array<OrderItem>} items - Order items.
* @param {number} taxRate - Tax rate.
* @returns {number} Total amount.
*/
function calculateTotal(items, taxRate) {
// ...
} - When to Comment: Complex logic, non-obvious code, declarations, important variables.
- When NOT to Comment: Obvious code (e.g.,
x = y + z; // Add y and z
).
Code Structure and Organization
- Modularization: Break code into independent modules.
- Logical flow: Write code that executes in a clear, predictable sequence.
Whitespace and Visual Clarity
- Use consistent spacing, line breaks, and indentation to create a visually appealing and easy-to-scan codebase.
II. Consistency
Write code that adheres to a uniform style and structure.
- Style Guide Adherence: Follow language-specific (e.g., PSR for PHP) or company-wide style guides.
- Project Structure: Use a consistent directory layout and file naming scheme.
- API Design: Design APIs that are uniform and predictable in their behavior and naming.
- Error Handling: Use a standardized approach for handling errors (e.g., exceptions).
- Dependency Management: Use a tool (e.g., npm, yarn) and a consistent approach to manage project dependencies.
III. Reusability
Write code that can be used in different parts of the system.
- Modular Design: Create reusable components or libraries.
- Configuration Management: Externalize settings to allow components to adapt to different environments without code changes.
- Abstraction and Encapsulation: Hide implementation details to create reusable modules with well-defined interfaces.
- Code Libraries and Frameworks: Utilize existing libraries and frameworks to avoid rewriting common functionality.
IV. Maintainability
Write code that is easy to modify and debug.
- Test-Driven Development (TDD): Write tests before writing code. Use unit and integration tests.
- Code Reviews: Conduct peer reviews to get feedback and improve code quality.
- Refactoring: Regularly improve code structure without changing its functionality.
- Version Control: Use Git (or another VCS) for tracking changes and collaboration.
- Logging and Monitoring: Implement logging to track application behavior and monitor performance.
V. Performance
Write code that is efficient and fast.
- Algorithm Efficiency: Choose algorithms with optimal time and space complexity.
- Resource Management: Manage memory, network connections, and file I/O efficiently.
- Optimization Techniques: Use profiling to identify bottlenecks and apply caching where appropriate.
- Database Optimization: Optimize database queries, use indexes, and consider database design.
- JavaScript Specifics:
- Minimize DOM manipulation.
- Use asynchronous operations (
Promises
,async/await
). - Optimize front-end assets (minify, bundle).
- Use a CDN for static assets.
VI. Security
Write code that protects the system from vulnerabilities.
- Input Validation: Sanitize all user input to prevent injection attacks (e.g., SQL injection, XSS).
- Authentication and Authorization: Implement secure access control using strong password hashing and the principle of least privilege.
- Data Encryption: Protect sensitive data using appropriate encryption techniques.
- Secure Coding Practices: Follow secure coding guidelines to avoid common vulnerabilities.
- Cross-Site Request Forgery (CSRF) Protection: Use anti-CSRF tokens.
- File Uploads: Validate file types, sizes, and contents. Store uploads outside the web root.
- Dependencies: Keep libraries and frameworks up to date.
- Error Reporting: Log errors, but don’t expose sensitive information in production.
- Asynchronous Operations: Use
Promises
andasync/await
.async function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
VII. Error Handling
- Exception Handling: Use
try-catch
blocks to handle errors gracefully. - Logging Errors: Log errors with enough detail to facilitate debugging.
- Fallback Strategies: Implement alternative flows or default behavior to handle errors and prevent application crashes.
VIII. Documentation
- Inline Comments: Explain complex or non-obvious code.
- API Documentation: Document API endpoints, parameters, and responses.
- Project READMEs: Provide an overview of the project, setup instructions, and usage examples.
- Architecture Documents: Describe the high-level design and structure of the system.
IX. Quality
Testing
- Always test the code yourself & ensure that everything is working as required.
- If there’s an internal client, have them test it on staging before confirmation.
- Once you are satisfied with the working, commit the changes
- After the commit, test everything once more to ensure that everything is commited.
Approval
- After the initial commit, have your senior review the working.
- If any modifications are required, make the modifications & make a 2nd commit.
- Make sure to share the URL, screenshots & summary of changes made so they can review it easily.
QA
- The task should be moved to QA with proper details