Menu
Menu
Contattaci
Il nostro settore richiede uno studio continuo e una forte attenzione all’innovazione. Incentiviamo quindi dei programmi formativi annuali per tutti i componenti del team, con ore dedicate (durante l’orario di lavoro) e serate formative sia online che in presenza. Sponsorizziamo eventi, sia come partner che semplicemente come partecipanti, e scriviamo articoli su quello che abbiamo imparato per essere, a nostra volta, dei divulgatori.
Vai alla sezione TeamQualsiasi sia il software che state sviluppando e qualsiasi sia il linguaggio che usate, gli aspetti più importanti da tenere in considerazione sono sempre gli stessi:
– Minimizzare i bug, che, in fondo, si riduce all’impedire al sistema di entrare in uno stato invalido/inaspettato.
– Minimizzare la complessità del codice, in quanto rende esponenzialmente più difficile comprenderne l’obbiettivo funzionale.
In questo articolo ci concentreremo sulle guardie, tecnica il cui obbiettivo è quello di impedire stati invalidi, e su come implementarle in modo semplice.
public sealed class Address
{
public string Street { get; }
public int Number { get; }
public Address(string street, int number)
{
// Esempio di guardie
if(string.IsNullOrWhiteSpace(street))
{
throw new ArgumentException("Cannot be empty", nameof(street));
}
if(number <= 0)
{
throw new ArgumentException("Must be positive", nameof(number));
}
Street = street;
Number = number;
}
}
public sealed class Address
{
public string Street { get; }
public int Number { get; }
public Address(string street, int number)
{
Street = ThrowIfEmpty(street);
Number = ThrowIfZeroOrNegative(number);
}
}
public sealed class Address
{
public string Street { get; }
public int Number { get; }
public Address(string street, int number)
{
Street = Guard.Against.NullOrWhiteSpace(street);
Number = Guard.Against.NegativeOrZero(number);
}
}
// example enum
public enum Term
{
Weekly,
Monthly,
Quarterly,
Yearly
}
// custom guard clause
public static class CustomGuards
{
public static Term InvalidTerms(
this IGuardClause _,
Term input,
[CallerArgumentExpression("input")] string parameterName = default!
)
{
if (input != Term.Annually && input != Term.Monthly)
{
throw new InvalidEnumArgumentException(parameterName);
}
return input;
}
}
// usage
public void SubscribeUser(Term term)
{
Guard.Against.InvalidTerms(term);
// or
SubscriptionTerm = Guard.Against.InvalidTerms(term);
}
Segui Giuneco sui social