diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index ced24c18da..f6e6743632 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -46,7 +46,7 @@ This document provides guidelines for using GitHub Copilot to contribute to the * Use file-scoped namespaces to reduce code verbosity. * Write comments only to explain **why** (a non-intuitive decision, a platform quirk or workaround, code that looks out of scope); never to explain **what** the code does. Use descriptive names instead. * Avoid using the **!** null forgiving operator. -* Follow naming conventions for enums and property names. +* Follow the Naming Conventions section below, and the naming guidelines for enums and property names. * Code that reads or formats with **CurrentCulture** or takes a **CultureInfo** must be tested in Turkish (tr-TR, az-Latn-AZ) and the other notorious cultures; see `.github/instructions/culture.instructions.md`. * Handler lifecycle: confirmed in .NET MAUI 11.0.10, `CreatePlatformView` runs once per handler in a real app; do not ask for guards against a second call; see `.github/instructions/handler-lifecycle.instructions.md`. @@ -71,9 +71,35 @@ StyleCop rules SA1201, SA1202, SA1204, SA1214, and SA1215 are reported as **buil ### Enums * Always use `Unknown` at index 0 for return types that may have a value that is not known * Always use `Default` at index 0 for option types that can use the system default option -* Follow naming guidelines for tense... `SensorSpeed` not `SensorSpeeds` +* Follow naming guidelines for number (singular, not plural)... `SensorSpeed` not `SensorSpeeds` * Assign values (0,1,2,3) for all enums, if not marked with a `Flags` attribute. This is to ensure that the enum can be serialized and deserialized correctly across platforms. +### Naming Conventions + +Names tell the story of the code, so it needs no comment that says *what* it does. Apply these rules to code you add or change. Don't rename code you aren't otherwise changing. + +* **Methods, `Action`s and `Func`s are verbs** that describe both the action they do and the result they return. + * `GetOrCreate(view, property)`, not `For(view, property)` + * `StartAnimationAndGetOriginalValue(currentValue)`, not `Start(currentValue)` + * A method that handles an event keeps the .NET `On` form, such as `OnRegexPropertyChanged`. A callback passed as a parameter is still a verb: `handleFrame`, not `onFrame`. +* **Past tense is only for events.** A method that records that something happened still starts with a verb. + * `RecordHandOverToApp(animationId)`, not `HandedOverToApp(animationId)` +* **A method that returns a `bool` to say whether it succeeded follows the [Try-Parse pattern](https://learn.microsoft.com/dotnet/standard/design-guidelines/exceptions-and-performance#try-parse-pattern).** + * Start its name with `Try` and return `true` on success. + * Return any other result through an `out` parameter. The parameter is `null` when the method returns `false`, and `[NotNullWhen(true)]` tells the compiler it isn't `null` when the method returns `true`. + * A method that only answers a question, such as `IsLatest(animationId)`, is not a `Try` method. + + ```csharp + public bool TryGetTracker(VisualElement view, [NotNullWhen(true)] out AnimatedPropertyTracker? tracker) + ``` + +* **Properties, fields and local variables are nouns.** A `bool` is a question. + * `public bool DidAnimationComplete { get; private set; }` + * `var wasTranslationInterrupted = ...`, not `var translationWasInterrupted = ...` + * A `Task` or `TaskCompletionSource` ends with what it is: `peakReachedTask` and `animationEndedSource`, not `peakReached` and `animationEnded`. +* **Events are past-tense verbs** that describe what happened. + * `MediaFailed`, `MediaEnded` + ### Property Names * Include units only if one of the platforms includes it in their implementation. For instance HeadingMagneticNorth implies degrees on all platforms, but PressureInHectopascals is needed since platforms don't provide a consistent API for this. @@ -102,7 +128,7 @@ if (canRetry) // Prefer - a comment that explains why // AVPlayerItem reports an indefinite duration until its asset has loaded, so wait for ReadyToPlay before reading it -await readyToPlay.Task.WaitAsync(token); +await readyToPlaySource.Task.WaitAsync(token); ``` ### Pattern matching diff --git a/.github/instructions/codestyle.instructions.md b/.github/instructions/codestyle.instructions.md index 279df6dd85..939de64898 100644 --- a/.github/instructions/codestyle.instructions.md +++ b/.github/instructions/codestyle.instructions.md @@ -23,13 +23,39 @@ This guide provides a set of best practices and coding standards for writing C# // Good: the comment explains why // AVPlayerItem reports an indefinite duration until its asset has loaded, so wait for ReadyToPlay before reading it - await readyToPlay.Task.WaitAsync(token); + await readyToPlaySource.Task.WaitAsync(token); // Avoid: the comment repeats the code // Check whether the user can retry if (attempts < 3 && !isCancelled) ``` +## Naming Conventions: + +Names tell the story of the code, so it needs no comment that says *what* it does. Apply these rules to code you add or change. Don't rename code you aren't otherwise changing. + +- **Methods, `Action`s and `Func`s are verbs** that describe both the action they do and the result they return. + - `GetOrCreate(view, property)`, not `For(view, property)` + - `StartAnimationAndGetOriginalValue(currentValue)`, not `Start(currentValue)` + - A method that handles an event keeps the .NET `On` form, such as `OnRegexPropertyChanged`. A callback passed as a parameter is still a verb: `handleFrame`, not `onFrame`. +- **Past tense is only for events.** A method that records that something happened still starts with a verb. + - `RecordHandOverToApp(animationId)`, not `HandedOverToApp(animationId)` +- **A method that returns a `bool` to say whether it succeeded follows the [Try-Parse pattern](https://learn.microsoft.com/dotnet/standard/design-guidelines/exceptions-and-performance#try-parse-pattern).** + - Start its name with `Try` and return `true` on success. + - Return any other result through an `out` parameter. The parameter is `null` when the method returns `false`, and `[NotNullWhen(true)]` tells the compiler it isn't `null` when the method returns `true`. + - A method that only answers a question, such as `IsLatest(animationId)`, is not a `Try` method. + + ```csharp + public bool TryGetTracker(VisualElement view, [NotNullWhen(true)] out AnimatedPropertyTracker? tracker) + ``` + +- **Properties, fields and local variables are nouns.** A `bool` is a question. + - `public bool DidAnimationComplete { get; private set; }` + - `var wasTranslationInterrupted = ...`, not `var translationWasInterrupted = ...` + - A `Task` or `TaskCompletionSource` ends with what it is: `peakReachedTask` and `animationEndedSource`, not `peakReached` and `animationEnded`. +- **Events are past-tense verbs** that describe what happened. + - `MediaFailed`, `MediaEnded` + ## Type Definitions: - Prefer records for data types: ```csharp @@ -219,12 +245,10 @@ This guide provides a set of best practices and coding standards for writing C# _ => ImageSource.FromResource(value, Application.Current?.GetType().Assembly) }; - // Method never returns null [return: NotNull] public static string EnsureNotNull(string? input) => input ?? string.Empty; - // Parameter must not be null when method returns true public static bool TryParse(string? input, [NotNullWhen(true)] out string? result) { result = null; @@ -252,14 +276,11 @@ This guide provides a set of best practices and coding standards for writing C# ```csharp public interface IOrderRepository { - // Explicitly shows that null is a valid return value Task FindByIdAsync(OrderId id, CancellationToken ct = default); - // Method will never return null [return: NotNull] Task> GetAllAsync(CancellationToken ct = default); - // Parameter cannot be null Task SaveAsync([NotNull] Order order, CancellationToken ct = default); } ``` @@ -349,8 +370,8 @@ This guide provides a set of best practices and coding standards for writing C# // Good: Using Try methods in LINQ with pattern matching var validNumbers = strings - .Select(s => (Success: int.TryParse(s, out var num), Value: num)) - .Where(x => x.Success) + .Select(s => (WasParsed: int.TryParse(s, out var num), Value: num)) + .Where(x => x.WasParsed) .Select(x => x.Value); ``` @@ -435,11 +456,11 @@ This guide provides a set of best practices and coding standards for writing C# - Use TaskCompletionSource correctly: ```csharp // Good: Using RunContinuationsAsynchronously - private readonly TaskCompletionSource _tcs = + private readonly TaskCompletionSource orderSource = new(TaskCreationOptions.RunContinuationsAsynchronously); // Avoid: Default TaskCompletionSource can cause deadlocks - private readonly TaskCompletionSource _tcs = new(); + private readonly TaskCompletionSource orderSource = new(); ``` - Always dispose CancellationTokenSources: ```csharp @@ -630,15 +651,3 @@ Within a class, struct, or interface, elements should be positioned in the follo 11. Records 12. Structs 13. Classes - -### Try Pattern - -When a method name begins with `Try` and returns a variable, ensure it adheres to the Try Pattern. - -Here Key Components of the Try Pattern: -1. Method Name: Begins with Try (e.g., TryParse, TryGetValue). -2. Return Type: bool (indicating success or failure). -3. Out Parameter: An out parameter to return the result if successful. -4. Null Analysis Attribute: [NotNullWhen(true)] (or [MaybeNullWhen(false)]) informs the compiler that if the method returns true, the out parameter is guaranteed to be non-null. - -This pattern allows for high-performance retrieval or parsing without throwing exceptions for expected failures. It also allows cleaner call sites by eliminating the need for null-checking the output variable within the if block, as seen in Dictionary.TryGetValue. diff --git a/.github/prompts/dotnet/codestyle.prompt.md b/.github/prompts/dotnet/codestyle.prompt.md index 6846af63ec..2005716541 100644 --- a/.github/prompts/dotnet/codestyle.prompt.md +++ b/.github/prompts/dotnet/codestyle.prompt.md @@ -1,6 +1,32 @@ # Coding Style Guide This guide provides a set of best practices and coding standards for writing C# code with GitHub Copilot. It covers various aspects of C# programming, including naming conventions, code structure, control flow, nullability, safe operations, asynchronous programming, and symbol references. +## Naming Conventions: + +Names tell the story of the code, so it needs no comment that says *what* it does. Apply these rules to code you add or change. Don't rename code you aren't otherwise changing. + +- **Methods, `Action`s and `Func`s are verbs** that describe both the action they do and the result they return. + - `GetOrCreate(view, property)`, not `For(view, property)` + - `StartAnimationAndGetOriginalValue(currentValue)`, not `Start(currentValue)` + - A method that handles an event keeps the .NET `On` form, such as `OnRegexPropertyChanged`. A callback passed as a parameter is still a verb: `handleFrame`, not `onFrame`. +- **Past tense is only for events.** A method that records that something happened still starts with a verb. + - `RecordHandOverToApp(animationId)`, not `HandedOverToApp(animationId)` +- **A method that returns a `bool` to say whether it succeeded follows the [Try-Parse pattern](https://learn.microsoft.com/dotnet/standard/design-guidelines/exceptions-and-performance#try-parse-pattern).** + - Start its name with `Try` and return `true` on success. + - Return any other result through an `out` parameter. The parameter is `null` when the method returns `false`, and `[NotNullWhen(true)]` tells the compiler it isn't `null` when the method returns `true`. + - A method that only answers a question, such as `IsLatest(animationId)`, is not a `Try` method. + + ```csharp + public bool TryGetTracker(VisualElement view, [NotNullWhen(true)] out AnimatedPropertyTracker? tracker) + ``` + +- **Properties, fields and local variables are nouns.** A `bool` is a question. + - `public bool DidAnimationComplete { get; private set; }` + - `var wasTranslationInterrupted = ...`, not `var translationWasInterrupted = ...` + - A `Task` or `TaskCompletionSource` ends with what it is: `peakReachedTask` and `animationEndedSource`, not `peakReached` and `animationEnded`. +- **Events are past-tense verbs** that describe what happened. + - `MediaFailed`, `MediaEnded` + ## Type Definitions: - Prefer records for data types: ```csharp @@ -33,10 +59,10 @@ This guide provides a set of best practices and coding standards for writing C# - Prefer range indexers over LINQ: ```csharp - // Good: Using range indexers with clear comments - var lastItem = items[^1]; // ^1 means "1 from the end" - var firstThree = items[..3]; // ..3 means "take first 3 items" - var slice = items[2..5]; // take items from index 2 to 4 (5 exclusive) + // Good: Using range indexers + var lastItem = items[^1]; + var firstThree = items[..3]; + var slice = items[2..5]; // Avoid: Using LINQ when range indexers are clearer var lastItem = items.LastOrDefault(); @@ -209,12 +235,10 @@ This guide provides a set of best practices and coding standards for writing C# _ => ImageSource.FromResource(value, Application.Current?.GetType().Assembly) }; - // Method never returns null [return: NotNull] public static string EnsureNotNull(string? input) => input ?? string.Empty; - // Parameter must not be null when method returns true public static bool TryParse(string? input, [NotNullWhen(true)] out string? result) { result = null; @@ -254,14 +278,11 @@ This guide provides a set of best practices and coding standards for writing C# ```csharp public interface IOrderRepository { - // Explicitly shows that null is a valid return value Task FindByIdAsync(OrderId id, CancellationToken ct = default); - // Method will never return null [return: NotNull] Task> GetAllAsync(CancellationToken ct = default); - // Parameter cannot be null Task SaveAsync([NotNull] Order order, CancellationToken ct = default); } ``` @@ -316,8 +337,8 @@ This guide provides a set of best practices and coding standards for writing C# // Good: Using Try methods in LINQ with pattern matching var validNumbers = strings - .Select(s => (Success: int.TryParse(s, out var num), Value: num)) - .Where(x => x.Success) + .Select(s => (WasParsed: int.TryParse(s, out var num), Value: num)) + .Where(x => x.WasParsed) .Select(x => x.Value); ``` @@ -402,11 +423,11 @@ This guide provides a set of best practices and coding standards for writing C# - Use TaskCompletionSource correctly: ```csharp // Good: Using RunContinuationsAsynchronously - private readonly TaskCompletionSource _tcs = + private readonly TaskCompletionSource orderSource = new(TaskCreationOptions.RunContinuationsAsynchronously); // Avoid: Default TaskCompletionSource can cause deadlocks - private readonly TaskCompletionSource _tcs = new(); + private readonly TaskCompletionSource orderSource = new(); ``` - Always dispose CancellationTokenSources: ```csharp diff --git a/AGENTS.md b/AGENTS.md index 4e37f95aec..0e96d19fcd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,13 @@ Every change to the four packages must keep them fully trim-safe and NativeAOT-s Interim, until CommunityToolkit/Maui#3438 (nightly bump bot) lands: when you review or change a device test workflow, check its Android API level, iOS runtime, Xcode and Windows runner against the newest GA releases and recommend a bump. The list is in [.github/instructions/trimming-aot.instructions.md](.github/instructions/trimming-aot.instructions.md#newest-os-versions-interim). +## Naming + +* Methods, `Action`s and `Func`s are verbs that say the action and the result: `GetOrCreate`, not `For`. Past tense is only for events. A method that handles an event keeps the .NET `On` form (`OnRegexPropertyChanged`); a callback parameter is a verb (`handleFrame`). +* A method that returns a `bool` to say whether it succeeded starts with `Try` and returns any other result through a `[NotNullWhen(true)] out` parameter. A method that only answers a question, such as `IsLatest`, is not a `Try` method. +* Properties, fields and locals are nouns; a `bool` is a question (`DidAnimationComplete`). A `Task` ends with `Task` and a `TaskCompletionSource` with `Source` (`peakReachedTask`, `animationEndedSource`). +* Apply this to code you add or change. Don't rename code you aren't otherwise changing. Full rules: [CONTRIBUTING.md](CONTRIBUTING.md#naming-conventions). + ## Instructions * [.github/copilot-instructions.md](.github/copilot-instructions.md): general rules for contributors and agents diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4a1cd12a84..8e17a68596 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -190,7 +190,7 @@ if (canRetry) // Prefer - a comment that explains why // AVPlayerItem reports an indefinite duration until its asset has loaded, so wait for ReadyToPlay before reading it -await readyToPlay.Task.WaitAsync(token); +await readyToPlaySource.Task.WaitAsync(token); var duration = playerItem.Duration; ``` @@ -209,9 +209,35 @@ var duration = playerItem.Duration; * Always use `Unknown` at index 0 for return types that may have a value that is not known * Always use `Default` at index 0 for option types that can use the system default option -* Follow naming guidelines for tense... `SensorSpeed` not `SensorSpeeds` +* Follow naming guidelines for number (singular, not plural)... `SensorSpeed` not `SensorSpeeds` * Assign values (0,1,2,3) for all enums +### Naming Conventions + +Names tell the story of the code, so it needs no comment that says *what* it does. Apply these rules to code you add or change. Don't rename code you aren't otherwise changing. + +* **Methods, `Action`s and `Func`s are verbs** that describe both the action they do and the result they return. + * `GetOrCreate(view, property)`, not `For(view, property)` + * `StartAnimationAndGetOriginalValue(currentValue)`, not `Start(currentValue)` + * A method that handles an event keeps the .NET `On` form, such as `OnRegexPropertyChanged`. A callback passed as a parameter is still a verb: `handleFrame`, not `onFrame`. +* **Past tense is only for events.** A method that records that something happened still starts with a verb. + * `RecordHandOverToApp(animationId)`, not `HandedOverToApp(animationId)` +* **A method that returns a `bool` to say whether it succeeded follows the [Try-Parse pattern](https://learn.microsoft.com/dotnet/standard/design-guidelines/exceptions-and-performance#try-parse-pattern).** + * Start its name with `Try` and return `true` on success. + * Return any other result through an `out` parameter. The parameter is `null` when the method returns `false`, and `[NotNullWhen(true)]` tells the compiler it isn't `null` when the method returns `true`. + * A method that only answers a question, such as `IsLatest(animationId)`, is not a `Try` method. + + ```csharp + public bool TryGetTracker(VisualElement view, [NotNullWhen(true)] out AnimatedPropertyTracker? tracker) + ``` + +* **Properties, fields and local variables are nouns.** A `bool` is a question. + * `public bool DidAnimationComplete { get; private set; }` + * `var wasTranslationInterrupted = ...`, not `var translationWasInterrupted = ...` + * A `Task` or `TaskCompletionSource` ends with what it is: `peakReachedTask` and `animationEndedSource`, not `peakReached` and `animationEnded`. +* **Events are past-tense verbs** that describe what happened. + * `MediaFailed`, `MediaEnded` + ### Property Names * Include units only if one of the platforms includes it in their implementation. For instance HeadingMagneticNorth implies degrees on all platforms, but PressureInHectopascals is needed since platforms don't provide a consistent API for this. diff --git a/samples/CommunityToolkit.Maui.Sample/Pages/Behaviors/AnimationBehaviorPage.xaml b/samples/CommunityToolkit.Maui.Sample/Pages/Behaviors/AnimationBehaviorPage.xaml index 783a2a602f..4ad1b12055 100644 --- a/samples/CommunityToolkit.Maui.Sample/Pages/Behaviors/AnimationBehaviorPage.xaml +++ b/samples/CommunityToolkit.Maui.Sample/Pages/Behaviors/AnimationBehaviorPage.xaml @@ -12,7 +12,7 @@ x:DataType="vm:AnimationBehaviorViewModel" x:TypeArguments="vm:AnimationBehaviorViewModel"> - +