Coding standards

From binaryoption
Jump to navigation Jump to search
Баннер1
  1. Coding Standards

This article provides a comprehensive introduction to coding standards for MediaWiki development, aimed at beginners. Following established coding standards is crucial for maintaining a consistent, readable, and maintainable codebase. A unified style simplifies collaboration, reduces errors, and makes the wiki easier to extend and improve over time. This guide addresses PHP, CSS, JavaScript, and MediaWiki markup, the primary languages used in extending and customizing a MediaWiki installation. We will also touch upon aspects related to database interaction and extension development.

Why Coding Standards Matter

Before diving into specific standards, it’s important to understand *why* they exist.

  • **Readability:** Consistent formatting makes code easier to understand, both for the original author and for anyone else who needs to work with it later. Imagine reading a book where the font size and style changed randomly – it would be very distracting. Code is similar.
  • **Maintainability:** Well-structured code is easier to modify and update without introducing bugs. When everyone follows the same conventions, it’s simpler to locate and fix problems. Poorly formatted or inconsistent code can become a nightmare to debug.
  • **Collaboration:** Coding standards facilitate teamwork. Developers can easily understand each other’s code, leading to smoother collaboration and fewer conflicts. This is especially important in open-source projects like MediaWiki where contributions come from diverse sources.
  • **Error Prevention:** Certain coding practices, like explicit type checking, can help prevent common errors. Consistent indentation and formatting can also make it easier to spot mistakes.
  • **Code Review:** Standards provide a baseline against which code can be reviewed. Reviewers can focus on the logic and functionality of the code, rather than getting bogged down in stylistic issues. Effective code review is critical for quality assurance.
  • **Automation:** Coding standards allow for automated tools (like linters and code formatters) to check and enforce the standards, further reducing errors and improving consistency.

PHP Coding Standards

PHP is the primary server-side language used in MediaWiki. The MediaWiki coding standards are largely based on the [PSR standards](https://www.php-fig.org/psr/), particularly [PSR-2](https://www.php-fig.org/psr/psr-2/) (coding style guide) and [PSR-12](https://www.php-fig.org/psr/psr-12/) (extended coding style guide). Here's a breakdown:

  • **File Encoding:** All PHP files must be saved with UTF-8 encoding *without* a Byte Order Mark (BOM).
  • **Indentation:** Use four spaces for indentation. Tabs are strongly discouraged. Most code editors can be configured to automatically convert tabs to spaces.
  • **Line Length:** Limit line length to 120 characters. Longer lines are harder to read and can cause problems with some editors.
  • **Namespaces:** Use namespaces to organize your code. This is especially important for extensions and large modifications. Namespaces prevent naming conflicts and improve code organization.
  • **Class Names:** Use StudlyCaps for class names (e.g., `MyAwesomeClass`).
  • **Method Names:** Use camelCase for method names (e.g., `calculateTotalCost`).
  • **Variable Names:** Use descriptive, lowercase variable names with underscores to separate words (e.g., `user_name`, `total_amount`). Avoid single-letter variable names except in very short loops.
  • **Constants:** Use uppercase with underscores (e.g., `MAX_USERS`, `DEFAULT_TIMEOUT`).
  • **Braces:** Use braces for all control structures (e.g., `if`, `else`, `for`, `while`, `foreach`). Put the opening brace on the same line as the control structure.
  • **Docblocks:** Use Docblocks to document your code. Docblocks should include a description of the class, method, or variable, as well as any parameters and return values. Use the `@param` and `@return` tags. See PHP documentation for details.
  • **Error Handling:** Use exceptions for error handling. Avoid using `die()` or `exit()` in production code.
  • **Database Interaction:** Use prepared statements to prevent SQL injection vulnerabilities. Always sanitize user input before using it in database queries. Familiarize yourself with the MediaWiki [database abstraction layer].
  • **Commenting:** Write clear and concise comments to explain complex logic. Avoid stating the obvious. Comments should explain *why* the code is doing something, not *what* it is doing.
  • **Avoid Global Variables:** Minimize the use of global variables. They can make code harder to understand and maintain. Consider using dependency injection instead.
  • **Use Strict Typing:** Utilize strict typing (declare_strict_types=1) in PHP files to enhance code reliability and catch type-related errors early on.

CSS Coding Standards

CSS is used for styling the wiki's appearance.

  • **Indentation:** Use two spaces for indentation.
  • **Selectors:** Keep selectors as specific as necessary but avoid unnecessary nesting.
  • **Properties:** List properties in a consistent order (e.g., alphabetical order or grouped by category).
  • **Color Values:** Use hexadecimal color values (e.g., `#FF0000` for red).
  • **Units:** Use consistent units (e.g., `px`, `em`, `rem`).
  • **Comments:** Use CSS comments (`/* ... */`) to explain complex styles.
  • **File Organization:** Organize CSS files logically (e.g., separate files for different components or sections of the wiki).
  • **Avoid Inline Styles:** Avoid using inline styles (`style="..."`). They make code harder to maintain and override. Use CSS classes instead.
  • **Media Queries:** Use media queries to adapt the style to different screen sizes and devices. This is crucial for responsive design. Learn about responsive web design principles.
  • **CSS Preprocessors:** Consider using a CSS preprocessor like Sass or Less to make your CSS more maintainable and organized. However, ensure compatibility with the MediaWiki environment.

JavaScript Coding Standards

JavaScript is used for adding interactivity to the wiki.

  • **Indentation:** Use two spaces for indentation.
  • **Semicolons:** Use semicolons at the end of each statement.
  • **Variable Declarations:** Use `const` and `let` instead of `var`. `const` should be used for variables that will not be reassigned, and `let` should be used for variables that may be reassigned.
  • **Naming Conventions:** Use camelCase for variable and function names.
  • **Comments:** Use JavaScript comments (`// ...` or `/* ... */`) to explain complex logic.
  • **Function Length:** Keep functions short and focused. If a function is too long, break it down into smaller functions.
  • **Error Handling:** Use `try...catch` blocks to handle errors.
  • **Avoid Global Variables:** Minimize the use of global variables. Use closures or modules instead.
  • **Strict Mode:** Use strict mode (`"use strict";`) to catch common coding errors.
  • **jQuery:** While MediaWiki uses jQuery, be mindful of its performance implications. Consider using native JavaScript methods when possible. Understand the principles of JavaScript performance optimization.
  • **Asynchronous Operations:** Use `async/await` or Promises for asynchronous operations.

MediaWiki Markup Standards

MediaWiki markup is used for creating and editing wiki pages.

  • **Headers:** Use headers consistently (e.g., `== Section ==`, `=== Subsection ===`).
  • **Lists:** Use lists (bulleted or numbered) to organize information.
  • **Tables:** Use tables to present data in a structured format.
  • **Links:** Use internal links (`link`) and external links (`Link text`) consistently.
  • **Images:** Use images to illustrate concepts. Provide alt text for all images.
  • **Templates:** Use templates to avoid repeating code. See the template system documentation.
  • **Categories:** Use categories to organize pages.
  • **Formatting:** Use bold text (`text`) and italic text (`text`) sparingly.
  • **Code Blocks:** Use code blocks (`
    <code>...</code>
    `) to display code.
  • **Comments:** Use comments (``) to add notes to the source code. Comments are not visible on the rendered page.
  • **Accessibility:** Ensure your markup is accessible to users with disabilities. Use appropriate headings, alt text, and color contrast.

Database Interaction Standards

When working with the MediaWiki database, adhere to these standards:

  • **Use the Database Abstraction Layer:** Never directly execute SQL queries. Always use the MediaWiki database abstraction layer to prevent SQL injection vulnerabilities and ensure compatibility with different database systems.
  • **Prepared Statements:** Utilize prepared statements for all database queries.
  • **Sanitize Input:** Sanitize all user input before using it in database queries.
  • **Indexing:** Properly index your database tables to improve query performance. Understand concepts related to database indexing.
  • **Transactions:** Use transactions to ensure data consistency.
  • **Schema Changes:** Document all schema changes carefully.
  • **Performance Optimization:** Optimize your database queries to improve performance. Consider using caching to reduce database load. Explore concepts of query optimization.

Extension Development Standards

If you are developing a MediaWiki extension, follow these additional standards:

  • **Extension Points:** Use extension points to hook into the MediaWiki core.
  • **Hooks:** Use hooks to modify the behavior of existing features.
  • **Special Pages:** Create special pages to provide new functionality.
  • **Configuration:** Provide configuration options for your extension.
  • **Internationalization:** Internationalize your extension to support multiple languages.
  • **Documentation:** Provide clear and concise documentation for your extension.
  • **Security:** Follow security best practices to prevent vulnerabilities. Perform security audits regularly.
  • **Licensing:** Choose an appropriate license for your extension.

Tools for Enforcing Coding Standards

Several tools can help you enforce coding standards:

  • **PHP_CodeSniffer:** A tool for detecting coding style violations in PHP code.
  • **PHPStan:** A static analysis tool for PHP code.
  • **ESLint:** A tool for detecting coding style violations in JavaScript code.
  • **Stylelint:** A tool for detecting coding style violations in CSS code.
  • **Code Formatters:** Tools like Prettier can automatically format your code to conform to a specific style.
  • **Git Hooks:** Configure Git hooks to run code analysis tools automatically before committing code.

By consistently applying these coding standards, you can contribute to a more robust, maintainable, and collaborative MediaWiki environment. Remember to consult the official MediaWiki documentation and community resources for the most up-to-date information. Understanding version control systems like Git is essential for collaborative development. Consider learning about agile methodologies for project management within a development team. Also, familiarize yourself with techniques in technical debt management.

MediaWiki development PHP documentation Database abstraction layer Template system Code review Responsive web design JavaScript performance optimization Database indexing Query optimization Security audits Version control systems Agile methodologies Technical debt management

PSR Standards PSR-2 Coding Style Guide PSR-12 Extended Coding Style Guide ESLint Stylelint PHP_CodeSniffer PHPStan Prettier Sass Less Guide to JavaScript CSS Tutorial PHP Tutorial MediaWiki Tutorial SQL Injection Explained JavaScript Design Patterns JavaScript Best Practices CSS Best Practices CSS Tricks PHP Best Practices SQL Injection Tutorial SQL Injection GeeksforGeeks Security Stack Exchange OWASP Portswigger Web Security Academy

Start Trading Now

Sign up at IQ Option (Minimum deposit $10) Open an account at Pocket Option (Minimum deposit $5)

Join Our Community

Subscribe to our Telegram channel @strategybin to receive: ✓ Daily trading signals ✓ Exclusive strategy analysis ✓ Market trend alerts ✓ Educational materials for beginners

Баннер