### Go Test and Benchmark Naming Conventions Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Outlines the standard naming conventions for Go tests and benchmarks, ensuring consistency with example naming patterns for functions, types, and methods. ```go func TestFunction(t *testing.T) { /* … */ } func TestFunction_suffix(t *testing.T) { /* … */ } func TestType_Method(t *testing.T) { /* … */ } func TestType_Method_suffix(t *testing.T) { /* … */ } ``` -------------------------------- ### Class Documentation Example Source: https://github.com/adguardteam/codeguidelines/blob/master/Java.md Class documentation should use Javadoc-style comments. It typically includes a one-sentence summary followed by more detailed explanations, conceptual disambiguation, and usage examples if necessary. Author tags should be omitted. ```java /** * An RPC equivalent of a unix pipe tee. Any RPC sent to the tee input is guaranteed to have * been sent to both tee outputs before the call returns. * * @param The type of the tee'd service. */ public class RpcTee { ... ``` -------------------------------- ### Go Method for Type Conversion Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Provides an example of naming conventions for methods that convert external data structures (like config or response) into internal types. The convention is to use `toInternal`. ```go // toInternal converts a user object from the configuration file into // a *User. func (u *confUser) toInternal() (user *User) { // … } ``` -------------------------------- ### Variable Naming (Bad Examples) Source: https://github.com/adguardteam/codeguidelines/blob/master/Java.md Variable names should be short yet meaningful. Avoid starting names with underscores or dollar signs. Examples of less descriptive names are provided. ```java // Bad. long pollInterval; int fileSize; ``` -------------------------------- ### Go Function Argument Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Provides examples of consistent vertical placement for function arguments and return values when they exceed a single line. It contrasts correct multi-line formatting with incorrect mixed placement. ```go // Correct: All arguments vertically aligned func functionWithALongName( firstArgumentWithALongName typeWithALongName, secondArgumentWithALongName otherTypeWithALongName, thirdArgumentWithALongName thirdTypeWithALongName, ) { // … } // Correct: Call with arguments vertically aligned err := functionWithALongName( firstArgumentWithALongName, secondArgumentWithALongName, thirdArgumentWithALongName, ) // Correct: Call with struct literal err := functionWithALongName(arg, structType{ field1: val1, field2: val2, }) // Incorrect: Mixed horizontal and vertical placement // func functionWithALongName(firstArgumentWithALongName typeWithALongName, // secondArgumentWithALongName otherTypeWithALongName, // thirdArgumentWithALongName thirdTypeWithALongName) { // // … // } // Incorrect: Mixed horizontal and vertical placement in call // err := functionWithALongName(firstArgumentWithALongName, // secondArgumentWithALongName, // thirdArgumentWithALongName, // ) ``` -------------------------------- ### C Code Example: Printing Process ID Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md This snippet demonstrates printing a message including the process ID using the C standard library's printf function. It's used as an example for code block formatting within prose. ```c printf("hello from process #%d\n", procnum); ``` -------------------------------- ### C# Naming Conventions: Class Names Source: https://github.com/adguardteam/codeguidelines/blob/master/C Demonstrates correct C# naming conventions for classes, emphasizing the use of PascalCase for class names. It shows an example of a poorly named class versus a well-named one. ```csharp // Bad. private class mountainBike { } // Good. private class MountainBike { } ``` -------------------------------- ### Variable Naming (Good Examples) Source: https://github.com/adguardteam/codeguidelines/blob/master/Java.md Variable names should be short yet meaningful and follow lowerCamelCase. Examples show improved clarity over less descriptive names. ```java // Good. long pollIntervalMs; int fileSizeGb. ``` -------------------------------- ### Markdown Embedded HTML Example Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md Provides an example of embedding HTML within Markdown, specifically for centering an image. Ensure HTML is well-formed. ```markdown

``` -------------------------------- ### JS Consistent Accessor Pattern: get/set Source: https://github.com/adguardteam/codeguidelines/blob/master/JavaScript/Javascript.md Demonstrates a consistent pattern for creating `get()` and `set()` methods for managing object properties, emphasizing uniformity in implementation. ```javascript class Jedi { constructor(options = {}) { const lightsaber = options.lightsaber || 'blue'; this.set('lightsaber', lightsaber); } set(key, val) { this[key] = val; } get(key) { return this[key]; } } ``` -------------------------------- ### C# Naming Conventions: Method and Property Names Source: https://github.com/adguardteam/codeguidelines/blob/master/C Highlights the naming convention for methods and properties in C#, which should follow PascalCase. This example shows a method name that adheres to this standard. ```csharp private void DoSomething() { // Good. long pollIntervalMs = Convert.ToInt32(Console.ReadLine()); } ``` -------------------------------- ### Go Block Closing and Separation Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Illustrates the rule to start a new paragraph after the final closing curly brace of a block. Exceptions include the last block within a larger scope or `defer` statements for destructors. ```go // Correct: New paragraph after block if a == b { // … } for i := 0; i < N; i++ { // … } // Incorrect: No new paragraph after block // if a == b { // // … // } // for i := 0; i < N; i++ { // // … // } ``` -------------------------------- ### Utility Flag Ordering Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Shell.md Instructs to place utility flags in ASCII order and not group them together. For example, `ls -1 -A -l` is preferred over `ls -1Al`. ```sh ls -1 -A -l ``` ```sh # Bad! ls -1Al ``` -------------------------------- ### C# Naming Conventions: Private Variables Source: https://github.com/adguardteam/codeguidelines/blob/master/C Specifies the naming convention for private variables in C#, which should be in PascalCase and prefixed with 'm_'. This example shows the recommended approach. ```csharp // Bad. int fileSize; // Good. int m_FileSizeGb; ``` -------------------------------- ### Throw Appropriate Exception Types in C# Source: https://github.com/adguardteam/codeguidelines/blob/master/C Guides on throwing specific, custom exception types to insulate API users from implementation details. It contrasts throwing generic 'Exception' or implementation-specific exceptions with creating custom exception classes like 'StorageException'. ```C# // Bad. // - Caller is forced to catch Exception, trapping many unnecessary types of issues. public class DataStore { public string FetchValue(string key) { // ... throw new Exception("error message"); } } // Better. // - The interface leaks details about one specific implementation. public DataStore { public string FetchValue(string key) { // ... throw new SQLException("error message"); } } // Good. // - A custom exception type insulates the user from the implementation. // - Different implementations aren't forced to abuse irrelevant exception types. public DataStore { public string FetchValue(string key) { // ... throw new StorageException("error message"); } public class StorageException : Exception { // ... } } ``` -------------------------------- ### C# Naming Conventions: Variable Names Source: https://github.com/adguardteam/codeguidelines/blob/master/C Illustrates best practices for naming variables in C#, advocating for short yet meaningful names and including units where applicable. It shows an example of a good variable name ('pollIntervalMs') versus a less descriptive one. ```csharp private void DoSomething() { // Bad. long pollInterval; int fileSize; } private void DoSomething() { // Good. long pollIntervalMs; int fileSizeGb; } ``` -------------------------------- ### Spaced Comments in JavaScript Source: https://github.com/adguardteam/codeguidelines/blob/master/JavaScript/Javascript.md Highlights the importance of starting all comments, both single-line and multiline, with a space for improved readability. This guideline aligns with common linting rules like `spaced-comment`. ```javascript // bad //is current tab const active = true; ``` ```javascript // good // is current tab const active = true; ``` ```javascript // bad /** *make() returns a new element *based on the passed-in tag name */ function make(tag) { // ... return element; } ``` ```javascript // good /** * make() returns a new element * based on the passed-in tag name */ function make(tag) { // ... return element; } ``` -------------------------------- ### Variable Naming (Better Examples with Units) Source: https://github.com/adguardteam/codeguidelines/blob/master/Java.md For enhanced readability and adaptability, consider incorporating units directly into the type using generic classes like 'Amount'. This makes the field's purpose and units immediately clear. ```java // Better. // - Unit is built in to the type. // - The field is easily adaptable between units, readability is high. Amount pollInterval; Amount fileSize; ``` -------------------------------- ### Go Formatting Tool Recommendation Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Recommends using the `gofumpt` tool with the `--extra -s` flags for consistent and idiomatic Go code formatting. This ensures adherence to best practices. ```go gofumpt --extra -s ``` -------------------------------- ### Go: Fake Interface Implementation with Callbacks Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Demonstrates creating a fake implementation of an interface using callbacks for testing. This approach allows for flexible control over mock behavior during tests, making it easier to isolate and test specific components. ```go // FakeReader … type FakeReader struct { OnRead func(b []byte) (n int, err error) } // Read implements the io.Reader interface for *FakeReader. func (r *FakeReader) Read(b []byte) (n int, err error) { return r.OnRead(b) } ``` -------------------------------- ### Documenting a Constructor in C# (Standard) Source: https://github.com/adguardteam/codeguidelines/blob/master/C Constructor documentation should detail specific usage information and parameters, especially for non-obvious behavior. It must document any thrown exceptions using XMLDoc tags. ```csharp /// /// Initializes a new instance of with the concatentaion of passed values: *explaination if required* /// /// The unique value 1. /// The unique value 2 /// Thrown, if values are equal. public SomeTransientObject( Value1 value1, Value2 value2) { // thrown exceptions must be documented. if (value1.Equals(value2){ throw ArguementException(nameof(value1)); }) // not obvious behaviour must be documented. Value = value1.Append(value2); } ``` -------------------------------- ### Documenting a Constructor in C# (Minimal) Source: https://github.com/adguardteam/codeguidelines/blob/master/C For constructors with transparent initialization, a minimal boilerplate comment is sufficient, indicating the initialization of a new instance and listing parameters with their descriptions. ```csharp /// /// Initializes a new instance of /// /// The description of value1 /// The description of value2 public SomeTransientObject( Value1 value1, Value2 value2) { Value1 = value1; Value2 = value2; } ``` -------------------------------- ### Documenting a Method in C# Source: https://github.com/adguardteam/codeguidelines/blob/master/C Method documentation should explain the method's functionality, potential exceptions, and input parameter formats. It must include a summary, return value description, and parameter details using XMLDoc tags. ```csharp /// /// Adds two doubles and returns the result. /// /// /// The sum of two doubles. /// /// Thrown when one parameter is max /// and the other is greater than zero. /// See to add integers. /// A double precision number. /// A double precision number. public static double Add(double a, double b) { ... } ``` -------------------------------- ### Go File Naming for Entities Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Provides guidelines for naming Go files that define entities. Singular nouns are preferred for individual entities (e.g., `client.go`), while plural nouns are used for collections or containers (e.g., `clients.go`). ```go // File: client.go package foo type Client struct { // … } ``` ```go // File: clients.go package foo type Clients []*Client // … type ClientsWithCache struct { // … } ``` -------------------------------- ### Go Interface Method Parameter Naming Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Illustrates the convention for naming parameters within Go interface method definitions, emphasizing clarity and explicitness. ```go type Frobulator interface { Frobulate(f Foo, b Bar) (r Result, err error) } ``` -------------------------------- ### Go Interface Implementation Commenting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Document methods that implement interfaces using a standard template. For unexported interfaces, clearly state that the interface is hidden. ```go // Foo implements the Fooer interface for *foo. func (f *foo) Foo() { // … } ``` ```go // Unwrap implements the hidden wrapper interface for *fooError. func (err *fooError) Unwrap() (unwrapped error) { // … } ``` -------------------------------- ### Documenting Java Methods: Bad, Better, Great Source: https://github.com/adguardteam/codeguidelines/blob/master/Java.md Demonstrates the evolution of effective Java method documentation. It highlights the importance of providing context, specifying input handling (like nulls), and detailing behavior beyond the method signature. ```java // Bad. // - The doc tells nothing that the method declaration didn't. // - This is the 'filler doc'. It would pass style checks, but doesn't help anybody. /** * Splits a string. * * @param s A string. * @return A list of strings. */ List split(String s); ``` ```java // Better. // - We know what the method splits on. // - Still some undefined behavior. /** * Splits a string on whitespace. * * @param s The string to split. An {@code null} string is treated as an empty string. * @return A list of the whitespace-delimited parts of the input. */ List split(String s); ``` ```java // Great. // - Covers yet another edge case. /** * Splits a string on whitespace. Repeated whitespace characters are collapsed. * * @param s The string to split. An {@code null} string is treated as an empty string. * @return A list of the whitespace-delimited parts of the input. */ List split(String s); ``` -------------------------------- ### Go Switch Statement Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Demonstrates the preferred method for writing Go switch statements with a large number of values in a single case, improving clarity by aligning values. ```go switch n { case longValueName1, longValueName2, longValueName3, longValueName4, longValueName5: return true default: return false } ``` -------------------------------- ### Go Function Signature Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Illustrates correct formatting for Go function signatures, particularly for multi-line return values, to enhance readability. It contrasts a preferred style with a less readable alternative. ```go func functionWithALongName(argumentWithALongName typeWithALongName) ( returnValueWithALongName typeWithALongName, err error, ) { // … } // and **not** this: // Bad! func functionWithALongName(argumentWithALongName typeWithALongName) ( returnValueWithALongName typeWithALongName, err error, ) { // … } ``` -------------------------------- ### C# Ternary Operator Usage Source: https://github.com/adguardteam/codeguidelines/blob/master/C Ternary operators are acceptable for simple, clear-cut conditional assignments. However, they should not be nested or used for complex logic to avoid confusing the reader. This example shows a good vs. bad usage scenario. ```C# // bad int value = a && b ? 11 : a ? 10 : b ? 1 : 0; // good int value = isSimple ? 11 : 1; ``` -------------------------------- ### Documenting a Class in C# Source: https://github.com/adguardteam/codeguidelines/blob/master/C Documentation for a class should provide a clear summary and, if necessary, a more detailed explanation to disambiguate concepts and ensure correct API usage. It should follow XMLDoc-style commenting conventions. ```csharp /// /// Implements a variable-size List that uses an array of objects to store the /// elements. A List has a capacity, which is the allocated length /// of the internal array. As elements are added to a List, the capacity /// of the List is automatically increased as required by reallocating the /// internal array. /// public class List : IList, System.Collections.IList, IReadOnlyList { ... } ``` -------------------------------- ### Go: Handling Unimplemented Methods in Fake Interfaces Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Shows how to handle methods that should not be called during a specific test by using `panic("not implemented")` in fake implementations. This clearly indicates an unexpected invocation and helps debug test failures. ```go r := &FakeReader{ OnRead: func(b []byte) (n int, err error) { panic("not implemented") }, } ``` -------------------------------- ### Go Slice of Struct Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Shows the recommended way to declare and initialize slices of structs in Go, aligning fields for better readability, especially with multiple elements. ```go ts := []T{{ Field: Value0, // … }, { Field: Value1, // … }, { Field: Value2, // … }} ``` -------------------------------- ### C# Inline Commenting Best Practice Source: https://github.com/adguardteam/codeguidelines/blob/master/C Inline comments should be added when the intent or purpose of code isn't completely explicit, but the code itself is clear enough to follow logically. This example shows a C# method with an inline comment explaining a specific capacity adjustment logic. ```C# private void EnsureCapacity(int min) { if (m_Items.Length < min) { long newCapacity = m_Items.Length == 0 ? m_DefaultCapacity : m_Items.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when m_Items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } } ``` -------------------------------- ### Documenting a Constructor in C# (Singleton Exclusion) Source: https://github.com/adguardteam/codeguidelines/blob/master/C For singleton object constructors that are not explicitly used and only take injected types, parameter documentation can be omitted to avoid clutter and merge conflicts, as the information is often redundant. ```csharp /// /// Initializes an instance of /// public SomeService( INiceService niceService, IGoodService goodService, ISmartService smartService, INService nService) { ... } ``` -------------------------------- ### Go Method Receiver Documentation Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Document important contracts for method receivers, such as nilness requirements or mutex states. Receivers are generally assumed to be non-nil unless explicitly documented otherwise. ```go // needsNonNil is an example of a method that requires a non-nil argument. // m must not be nil. r.mu is expected to be locked. func (r *Receiver) needsNonNil(m *Message) (err error) { // … } ``` -------------------------------- ### Manage Resource Scopes Effectively in Go Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Shorten resource scopes to ensure resources like file handles or mutexes are released promptly. This involves factoring out operations that use resources into separate functions to limit their lifetime. ```Go // Bad! Resource r is only closed at the end of the very long function. func Foo() (err error) { r, err := open() check(err) defer r.close() v, err := decode(r) check(err) // Lots of slow stuff with v. r is only closed once Foo exits. } // Good, r is closed after loadV returns. func Foo() (err error) { v, err := loadV() check(err) // Lots of slow stuff with v. } func loadV() (v *V, err error) { r, err := open() check(err) defer r.close() return decode(r) } ``` -------------------------------- ### Go Test Requirement Grouping Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Explains the practice of grouping `require.*` statements with preceding related logic, separating them from subsequent `assert.*` calls or unrelated requirements. This improves test clarity. ```go // Correct grouping of require statements val, ok := valMap[key] require.True(t, ok) require.NotNil(t, val) // Separate assert statement assert.Equal(t, expected, val) ``` -------------------------------- ### Go Statement Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Illustrates the guideline to decorate terminating statements like `break`, `continue`, and `return` with empty lines. This applies unless the statement is the sole element within its block. ```go // Example of correct formatting: if condition { // ... return } // Example of incorrect formatting (if not the only statement): if condition { // ... return // ... } ``` -------------------------------- ### Go Defer Statement Placement Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Suggests placing deferred calls for destructors, such as `f.Close()`, in the same paragraph as their corresponding constructors. This is an exception to the general paragraph separation rule. ```go // Correct placement of defer for destructor f, err := os.Open(fileName) if err != nil { return err } defunc() { processError(f.Close()) }() ``` -------------------------------- ### Script Structure Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Shell.md Defines the required order for script sections: Shebang, optional initial documentation, optional verbosity level parsing, and `set` options. This ensures a consistent and predictable script layout. ```sh #!/bin/sh # Initial documentation (optional) # Verbosity parsing (optional) # set options set -e -u ``` -------------------------------- ### Go Context Helper Function Naming Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Defines naming conventions for Go functions that interact with `context.Context`. Functions returning a new context with values should be named `ContextWithFoo` or `WithFoo`, while those retrieving values are `FooFromContext`. ```go // ContextWithFoo returns a copy of the parent context with the value of `f` // attached to it. func ContextWithFoo(parent context.Context, f Foo) (ctx context.Context) { // … } // FooFromContext returns the Foo attached to the context. func FooFromContext(parent context.Context) (f Foo, ok bool) { // … } ``` -------------------------------- ### Markdown Header Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md Illustrates the proper use of Markdown header levels, showing the correct number of '#' characters and indentation. Consistent indentation improves readability. ```markdown # Article ## Section ### Subsection #### Subsubsection ##### Subsubsubsection ###### Subsubsubsubsection ``` -------------------------------- ### Go TODO Comments Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Text.md Demonstrates the correct format for temporary TODO comments in Go code. These comments use '!!' to mark items needing resolution before publishing, aiding in development and code review. It also shows how to assign TODOs to multiple users. ```go // TODO(usr1): !! Remove this debug before pushing! ``` ```go // TODO(usr1): Fix the frobulation issue. // TODO(usr1, usr2): Fix the frobulation issue. ``` -------------------------------- ### Markdown List Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md Demonstrates correct formatting for unordered and ordered Markdown lists, including indentation and numbering. Ensure consistent spacing after list markers. ```markdown * Item one. * Item two. ``` ```markdown 1. Item one. 1. Item two. ``` -------------------------------- ### Use Class Syntax for Constructors in JavaScript Source: https://github.com/adguardteam/codeguidelines/blob/master/JavaScript/Javascript.md Demonstrates the preference for `class` syntax over direct `prototype` manipulation for defining constructors and methods in JavaScript. It highlights conciseness and ease of reasoning. ```javascript // bad function Queue(contents = []) { this.queue = [...contents]; } Queue.prototype.pop = function () { const value = this.queue[0]; this.queue.splice(0, 1); return value; }; // good class Queue { constructor(contents = []) { this.queue = [...contents]; } pop() { const value = this.queue[0]; this.queue.splice(0, 1); return value; } } ``` -------------------------------- ### Static Interface Type Check Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Perform static interface type checks using a variable declaration to ensure an implementation satisfies an interface. Place these checks before the first method declaration of the implementing type. ```Go // type check var _ ifaceType = (*implType)(nil) ``` -------------------------------- ### Recommended `set` Options for Robustness Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Shell.md Recommends using `set -e -f -u` for robust shell scripting. `set -e` exits on error, `set -f` disables globbing, and `set -u` treats unset variables as errors. `set -x` is suggested for verbose mode debugging. ```sh set -e -f -u ``` -------------------------------- ### Check for Empty Strings Correctly in Go Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Use direct comparison `s == ""` for checking empty strings. If accessing the first character, ensure the string is not empty first using `len(s) > 0` to prevent panics. ```Go // Check against empty strings like this: if s == "" { // … } // Except when the check is done to then use the first character: if len(s) > 0 { c := s[0] } ``` -------------------------------- ### Markdown Link Reference Definitions Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md Explains the placement of Markdown link reference definitions, recommending they be placed at the end of a second-level section or a third-level section if it's large. ```markdown [comment]: # (This is a link reference definition) [example]: https://www.example.com ``` -------------------------------- ### Precondition Checks in Java Source: https://github.com/adguardteam/codeguidelines/blob/master/Java.md Demonstrates the importance of implementing precondition checks, particularly for public methods and constructors. Validating inputs like null parameters early prevents issues from propagating and clarifies expected behavior. ```java // Bad. // - If the file or callback are null, the problem isn't noticed until much later. class AsyncFileReader { void readLater(File file, Closure callback) { scheduledExecutor.schedule(new Runnable() { @Override public void run() { callback.execute(readSync(file)); } }, 1L, TimeUnit.HOURS); } } ``` ```java // Good. class AsyncFileReader { void readLater(File file, Closure callback) { checkNotNull(file); checkArgument(file.exists() && file.canRead(), "File must exist and be readable."); checkNotNull(callback); scheduledExecutor.schedule(new Runnable() { @Override public void run() { callback.execute(readSync(file)); } }, 1L, TimeUnit.HOURS); } } ``` -------------------------------- ### Markdown List Spacing Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md Illustrates the difference between loose and tight Markdown lists. Tight lists are for short numeric data or tables of contents, while loose lists are for general content to improve readability. ```markdown An example of a loose list: * This text is a paragraph, and so will be separated from the other items by a longer vertical space. * That is good because it improves readability both in the rendered form as well as in the text form. * And we care about the readability of our texts and encourage people to write them better. ``` ```markdown The tight list of valid values: * 6; * 24; * 72. ``` -------------------------------- ### Markdown Fenced Code Blocks Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md Recommends using triple-backtick fenced code blocks with language tags for clarity and syntax highlighting. Triple-tilde blocks are an alternative if code contains triple-backticks. ```markdown ```md # This is a Markdown code block ``` ``` ```markdown ``` # This is a plain text code block ``` ``` ```markdown ~~~md # This is a Markdown code block with triple tildes ~~~ ``` -------------------------------- ### Correct export and readonly Usage Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Shell.md Demonstrates the correct way to use `export` and `readonly` separately from variable assignment. This ensures that script termination on command substitution failures is properly handled. ```sh X="$(echo 42)" export X ``` ```sh # Bad! export X="$(echo 42)" ``` -------------------------------- ### YAML Multiline Array Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/YAML.md Demonstrates the preferred indentation and formatting for multiline arrays in YAML files. It shows the standard two-space indent with a hyphen and space, and also accepts four-space indents when generated by a program. ```yaml 'values': - 'value-1' - 'value-2' - 'value-3' ``` -------------------------------- ### Multiline Comments in JavaScript (/** ... */) Source: https://github.com/adguardteam/codeguidelines/blob/master/JavaScript/Javascript.md Demonstrates the correct usage of multiline comments using the `/** ... */` syntax, typically for documentation blocks like JSDoc. It contrasts the preferred style with less readable alternatives. ```javascript // bad // make() returns a new element // based on the passed in tag name // // @param {String} tag // @return {Element} element function make(tag) { // ... return element; } ``` ```javascript // good /** * make() returns a new element * based on the passed-in tag name */ function make(tag) { // ... return element; } ``` -------------------------------- ### Go Error Handling: Wording in Error Messages Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Avoid using the word 'error' within error messages. Instead, provide the action being performed for clarity and conciseness. ```go // BAD! err = foo() if err != nil { return fmt.Errorf("error while calling foo: %w", err) } ``` ```go // Good. err = foo() if err != nil { return fmt.Errorf("performing foo: %w", err) } ``` -------------------------------- ### Go Struct Field Spacing Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Demonstrates adding empty lines between documented struct fields for improved readability. This practice enhances the clarity of complex struct definitions. ```go // FooConfig is the configuration for a single foo. type FooConfig struct { // ID is the unique ID of foo. ID FooID // Name is the human-readable name of this foo. Name string // Timeout is the timeout used for all frobulation operations // performed by this foo. Timeout time.Duration } ``` -------------------------------- ### Line Length Limit Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Shell.md Specifies that script code lines should not exceed one hundred (100) columns. This promotes readability and consistency across different viewing environments. ```sh # This is a very long line that exceeds the 100 column limit and should be wrapped to maintain readability and adhere to the guidelines. This is a very long line that exceeds the 100 column limit and should be wrapped. ``` -------------------------------- ### Go Indentation Limits Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Advises limiting non-test code indentation to four levels, with an allowance for an extra level for error checks or struct initialization. Table-driven tests are an exception, permitting an additional level. ```go // Example of acceptable indentation: func processData(data []byte) error { if len(data) == 0 { return fmt.Errorf("empty data") } config := &Config{ Timeout: 5 * time.Second, } // ... further operations ... return nil } ``` -------------------------------- ### C# Naming Conventions: Interface Names Source: https://github.com/adguardteam/codeguidelines/blob/master/C Provides guidance on C# interface naming, requiring interfaces to be nouns in PascalCase and prefixed with the letter 'I'. It contrasts incorrect and correct interface naming conventions. ```csharp // Bad. public interface Bike { } // Good. public interface IBike { } ``` -------------------------------- ### Go RFC Commenting Style Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md When referencing RFCs in comments, write the identifier without a hyphen and ensure no newline separates letters and numbers. This ensures automatic linking on platforms like pkg.go.dev. ```go // toTime parses an RFC 3339 timestamp. ``` ```go // Bad! A hyphen is used. // toTime parses an RFC-3339 timestamp. ``` ```go // Bad! A newline before the number. // toTime parses and also uses an optimized validation technique on an RFC // 3339 timestamp. ``` -------------------------------- ### Prefer `case` over multiple `test` conditions Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Shell.md Suggests using the `case` statement for conditionals that check for equality against multiple values. This approach is generally more readable and maintainable than chaining multiple `test` or `[` commands. ```sh case "$VAR" in "value1") # ... ;; "value2") # ... ;; *) # ... ;; esac ``` -------------------------------- ### C# Bracket and Block Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/C Demonstrates the preferred C# style for opening braces, which should always be at the beginning of the line after the statement that begins the block. It also shows the importance of using curly braces for all blocks, even single-line ones, and adding an empty line after code blocks within methods. ```C# // bad private void DoSomething() { ... } // good private void DoSomething() { ... } ``` ```C# // bad private void DoSomething() { if (foobar) { ... } DoAnotherAction(); } // good private void DoSomething() { if (foobar) { ... } DoAnotherAction(); } ``` ```C# // bad if (foobar) DoSomething(); // good if (foobar) { DoSomething(); } ``` -------------------------------- ### Markdown Info String for Custom Formats Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md Specifies using 'none' as the info string for fenced code blocks containing plain text or custom formats, such as adblock rules, when no specific language applies. ```markdown ```none ! 127.0.0.1 localhost ``` ``` -------------------------------- ### Optimize Struct Alignment for Memory Efficiency in Go Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Be mindful of structure alignment to minimize padding and improve memory layout. Reordering fields, especially placing pointers closer to the top, can lead to more compact structs. ```Go // Bad! Lots of padding between the uint64s and bools. Pointers are at the // end of the structure. type bad struct { a uint64 b bool c uint64 d bool e uint64 f bool g uint64 h bool y *otherType z *otherType } // Good. The padding is minimized, and the pointers are closer to the top. type good struct { y *otherType z *otherType g uint64 e uint64 c uint64 a uint64 h bool f bool d bool b bool } ``` -------------------------------- ### Equality and Numeric Comparison Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Shell.md Emphasizes using `=` for string comparisons and `-eq` for numeric comparisons within conditional statements. This practice helps catch typing errors and ensures correct comparison logic. ```sh if [ "$string_var" = "expected_value" ]; then # ... fi if [ "$numeric_var" -eq 10 ]; then # ... fi ``` -------------------------------- ### Use let for Reassignable References Source: https://github.com/adguardteam/codeguidelines/blob/master/JavaScript/Javascript.md When reassignment is necessary, use `let` instead of `var`. `let` is block-scoped, unlike `var` which is function-scoped, leading to more predictable behavior. ```javascript // bad var count = 1; if (true) { count += 1; } // good, use the let. let count = 1; if (true) { count += 1; } ``` -------------------------------- ### Go Error Handling: Avoid Redundant Wrapping Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Avoid wrapping errors when the original error already provides sufficient context, such as a file path. This prevents duplication of information in error messages. ```go // Bad! Will duplicate the file name. f, err := os.Open(fileName) if err != nil { return fmt.Errorf("opening %q: %w", fileName, err) } ``` ```go // Don't wrap the error, because it's informative enough as is. err = f() if err != nil { return err } ``` -------------------------------- ### Markdown Quotes Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md Shows the correct way to format blockquotes in Markdown, including handling long quotes by continuing the '>' marker on subsequent lines. ```markdown > This is a quote from some other source. This is a rather long quote > to show exactly how long quotes must be formatted. ``` -------------------------------- ### Go Named Return Values Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Go.md Promotes the use of named return values in Go function signatures to enhance the readability and clarity of the function's output. ```go func split(data []*datum) (less, greater []*datum) { // … } ``` -------------------------------- ### Markdown Bold and Italic Formatting Source: https://github.com/adguardteam/codeguidelines/blob/master/Go/Markdown.md Demonstrates the correct use of asterisks for bold and italic text in Markdown, including placing punctuation inside the formatting. ```markdown This is **very important!** You need to use *these;* those won't work. ``` -------------------------------- ### C# Naming Conventions: Constants Source: https://github.com/adguardteam/codeguidelines/blob/master/C Defines the standard for naming constants in C#, requiring them to be all uppercase with words separated by underscores (_). It contrasts incorrect and correct constant naming. ```csharp // Bad. public const int TimeInSeconds = 5; //Good. public const int TIME_IN_SECONDS = 5; ``` -------------------------------- ### Use Spread Syntax (...) Over apply() for Variadic Functions Source: https://github.com/adguardteam/codeguidelines/blob/master/JavaScript/Javascript.md Prefer the spread syntax (`...`) over `Function.prototype.apply()` when calling variadic functions. The spread syntax is cleaner, does not require specifying a context, and integrates better with `new` expressions. ```javascript // bad const x = [1, 2, 3, 4, 5]; console.log.apply(console, x); // bad new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5])); // good const x = [1, 2, 3, 4, 5]; console.log(...x); // good new Date(...[2016, 8, 5]); ``` -------------------------------- ### JavaScript: Use Block Statements and Line Breaks Source: https://github.com/adguardteam/codeguidelines/blob/master/JavaScript/Javascript.md Demonstrates correct usage of block statements within control structures like `if` and `function`. It shows how to break up multi-line blocks for improved readability, contrasting good and bad practices. ```javascript // bad if (test) return false; // bad if (test) return false; // good if (test) { return false; } // bad function foo() { return false; } // good function bar() { return false; } ``` -------------------------------- ### Action Item Comments (TODO, FIXME) Source: https://github.com/adguardteam/codeguidelines/blob/master/JavaScript/Javascript.md Provides guidance on using `TODO` and `FIXME` prefixes in comments to flag issues that require future attention or immediate correction. It suggests including an author name for clarity. ```javascript // author name is not required // for future changes // TODO(): blablabla // for changes required in the current pull request // FIXME(): blablabla ```