dotnet-tips
GUIDs
Guid.CreateVersion7()
prevents fragmentation in DB indexing -
it keeps first 7 digits sequential making it a sortable Guid.
Collection Initializers (C#12)
Array, Lists, Dictionaries can be nightmare to initialize before C#12
Now use [] and compiler will figure out how to initialize.
Dictionary<string, int> = []
CancellationToken
Use them in APIs to allow cancellating a task - add them to your methods and pass them down to all IO operations (data-store, http, etc)
Primary Constructors
Don't allow to pass readonly in the fiels, and they aren't readonly backing fields
Attributes
[StringSyntax(json, date, number, etc..)] - we can use this in a method parameter so that who passes this parameter has a formatted callee.
Logger
log.LogInformation("messageTemplate", params...)
Don't use string interpolation mistakes because you lose how to filter logs and will create many many strings bad for GC.
Descriminated Union
OneOf<T1, T2, T3>
This is useful because you state what you are returning:
Consider OneOf<Movie, NotFound, ValidationFailure> and you have to act on each of them. Consumer is forced to interact with this strict contract.
Result Type, Option Type and FluentResults
Result - Allows to know if you are a Success or a Failure. In case of a failure, you have errors. In case of Sucess you have the Type.
Option - allows to have something or nothing but you. This is to remove the NULL possibilities in your application avoiding NullReferenceException.
FluentResults - A library that allows to create many results fluently.
Domain Driven Design
- Use it when you have clearly defined logical boundaries.
- Create an aggregate which MUST always be in an valid state.
- You create private fields and expose only necessary copies of your aggregate data.
- Create Methods to mutate state and add validation if required.
- Constructor should create a valid instance.
- Can use a Factory method to create your aggregate.
- Perfect for command operations (data is valid ready to go to the store).
- The aggregate is composed by everything being valid including his internal fields.
- If your domain is simple avoid this and use CRUD.