Skip to content

Commit

Permalink
style: simplify collection initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
Seddryck committed Dec 21, 2023
1 parent d4ca21f commit ef20deb
Show file tree
Hide file tree
Showing 31 changed files with 86 additions and 83 deletions.
2 changes: 1 addition & 1 deletion Expressif.Testing/Functions/ExpressionFactoryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public void Instantiate_RoundMultipleExpressionParameter_Valid()
context.Variables.Add<int>("myVar2", 5);
var subFunction1 = new InputExpressionParameter(new InputExpression(new VariableParameter("myVar1"), new[] { new Function("numeric-to-decrement", Array.Empty<IParameter>()) }));
var subFunction2 = new InputExpressionParameter(new InputExpression(new VariableParameter("myVar2"), new[] { new Function("numeric-to-increment", Array.Empty<IParameter>()) }));
var subFunction3 = new InputExpressionParameter(new InputExpression(new VariableParameter("myVar1"), new[] { new Function("numeric-to-add", new IParameter[] { subFunction1 }), new Function("numeric-to-multiply", new IParameter[] { subFunction2 }) }));
var subFunction3 = new InputExpressionParameter(new InputExpression(new VariableParameter("myVar1"), new[] { new Function("numeric-to-add", [subFunction1]), new Function("numeric-to-multiply", [subFunction2]) }));
var function = new ExpressionFactory().Instantiate(typeof(Round), new[] { subFunction3 }, context);
Assert.That(function, Is.Not.Null);
Assert.That(function, Is.TypeOf<Round>());
Expand Down
10 changes: 5 additions & 5 deletions Expressif.Testing/Functions/Special/SpecialFunctionsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public void AnyToAny_Any(object? value)
[TestCase(typeof(Value))]
public void AnyToAny_SpecialType_Any(Type type)
=> Assert.That(new AnyToAny().Evaluate(
type.GetConstructor(Array.Empty<Type>())!.Invoke(Array.Empty<Type>()))
type.GetConstructor([])!.Invoke(Array.Empty<Type>()))
, Is.EqualTo(new Any()));

[Test]
Expand All @@ -54,7 +54,7 @@ public void ValueToValue_NotNull_Value(object value)
[TestCase(typeof(Value))]
public void ValueToValue_SpecialType_Value(Type type)
=> Assert.That(new ValueToValue().Evaluate(
type.GetConstructor(Array.Empty<Type>())!.Invoke(Array.Empty<Type>()))
type.GetConstructor([])!.Invoke(Array.Empty<Type>()))
, Is.EqualTo(new Value()));

[Test]
Expand All @@ -67,7 +67,7 @@ public void ValueToValue_Null_Null(object? value)
[TestCase(typeof(Null))]
public void ValueToValue_SpecialType_Null(Type type)
=> Assert.That(new ValueToValue().Evaluate(
type.GetConstructor(Array.Empty<Type>())!.Invoke(Array.Empty<Type>()))
type.GetConstructor([])!.Invoke(Array.Empty<Type>()))
, Is.EqualTo(new Null()));

[Test]
Expand All @@ -87,7 +87,7 @@ public void NullToValue_Null_Value(object? value)
[TestCase(typeof(Null))]
public void NullToValue_SpecialType_Null(Type type)
=> Assert.That(new NullToValue().Evaluate(
type.GetConstructor(Array.Empty<Type>())!.Invoke(Array.Empty<Type>()))
type.GetConstructor([])!.Invoke(Array.Empty<Type>()))
, Is.EqualTo(new Value()));

[Test]
Expand All @@ -112,7 +112,7 @@ public void NullToValue_NotNull_Value(object value)
[TestCase(typeof(Value))]
public void NullToValue_SpecialType_Value(Type type)
{
var obj = type.GetConstructor(Array.Empty<Type>())!.Invoke(Array.Empty<Type>());
var obj = type.GetConstructor([])!.Invoke(Array.Empty<Type>());
Assert.That(new NullToValue().Evaluate(obj), Is.EqualTo(obj));
}
}
7 changes: 5 additions & 2 deletions Expressif.Testing/Functions/Temporal/TemporalFunctionsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,10 @@ public void TextToDateThenTimeAndUtcToLocal_Valid(string value, string format, s
var textToDateTime = new TextToDateTime(() => format);
var utcToLocal = new UtcToLocal(() => timeZone);
var result = utcToLocal.Evaluate(textToDateTime.Evaluate(value));
Assert.That(result, Is.EqualTo(expected));
Assert.That(((DateTime)result).Kind, Is.EqualTo(DateTimeKind.Unspecified));
Assert.Multiple(() =>
{
Assert.That(result, Is.EqualTo(expected));
Assert.That(((DateTime)result!).Kind, Is.EqualTo(DateTimeKind.Unspecified));
});
}
}
4 changes: 2 additions & 2 deletions Expressif.Testing/Functions/Text/TextFunctionsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public void WhitespacesToEmpty_Empty(string value)
[TestCase(typeof(Whitespace))]
public void WhitespacesToEmpty_SpecialType_Empty(Type type)
{
var obj = type.GetConstructor(Array.Empty<Type>())!.Invoke(Array.Empty<Type>());
var obj = type.GetConstructor([])!.Invoke(Array.Empty<Type>());
Assert.That(new WhitespacesToEmpty().Evaluate(obj), Is.EqualTo(new Empty()));
}

Expand All @@ -111,7 +111,7 @@ public void WhitespacesToEmpty_NotEmpty(string value)
[TestCase(typeof(Null))]
public void WhitespacesToEmpty_SpecialType_NotEmpty(Type type)
{
var obj = type.GetConstructor(Array.Empty<Type>())!.Invoke(Array.Empty<Type>());
var obj = type.GetConstructor([])!.Invoke(Array.Empty<Type>());
Assert.That(new WhitespacesToEmpty().Evaluate(obj), Is.Not.EqualTo(new Empty()));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void Locate_ExpressifAssembly_SomeAliases()

foreach (var info in Infos)
{
Debug.WriteLine($"{info.Name}: {(info.Aliases.Any() ? info.Aliases.ElementAt(0) : string.Empty)}");
Debug.WriteLine($"{info.Name}: {(info.Aliases.Length!=0 ? info.Aliases.ElementAt(0) : string.Empty)}");
foreach (var alias in info.Aliases)
Assert.That(info.Aliases.ElementAt(0), Is.Not.Null.Or.Empty);
}
Expand All @@ -54,7 +54,7 @@ public void Locate_ExpressifAssembly_SomeAliases()
[Test]
public void Locate_ExpressifAssembly_NoDuplicateAlias()
{
var infos = Infos.Where(x => x.Aliases.Any());
var infos = Infos.Where(x => x.Aliases.Length!=0);

foreach (var info in infos)
Assert.That(infos.Count(x => x.Aliases.Contains(info.Aliases.ElementAt(0))), Is.EqualTo(1));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public void Locate_ExpressifAssembly_NameEqualClass()
[Test]
public void Locate_ExpressifAssembly_NoDuplicateAlias()
{
var infos = Infos.Where(x => x.Aliases.Any());
var infos = Infos.Where(x => x.Aliases.Length != 0);
foreach (var info in infos)
Assert.That(infos.Count(x => x.Aliases.Contains(info.Aliases.ElementAt(0))), Is.EqualTo(1));
}
Expand Down
2 changes: 1 addition & 1 deletion Expressif.Testing/Values/IntervalBuilderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ public void Create_TwoSameValidType_Valid(string lowerBound, string upperBound,
[TestCase("-7.25", "")]
[TestCase("2020-12-16", "4.12355")]
public void Create_MixedValidType_Invalid(string lowerBound, string upperBound)
=> Assert.That(() => new IntervalBuilder().Create(']', lowerBound, upperBound, '['), Throws.ArgumentException);
=> Assert.That(() => new IntervalBuilder().Create(']', lowerBound, upperBound, '['), Throws.InvalidOperationException);
}
6 changes: 3 additions & 3 deletions Expressif/ExpressionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ public ExpressionBuilder Chain(Function function)
public IFunction Build()
{
IFunction? function = null;
if (!Pile.Any())
if (Pile.Count == 0)
throw new InvalidOperationException();

while (Pile.Any())
while (Pile.Count != 0)
{
var member = Pile.Dequeue() switch
{
Expand All @@ -88,7 +88,7 @@ public IFunction Build()

public string Serialize()
{
if (!Pile.Any())
if (Pile.Count == 0)
throw new InvalidOperationException();

return Serializer.Serialize(Pile.ToArray());
Expand Down
14 changes: 7 additions & 7 deletions Expressif/Functions/BaseExpressionFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ protected internal ConstructorInfo GetMatchingConstructor(Type type, int paramCo

protected Delegate InstantiateScalarDelegate(IParameter parameter, Type scalarType, Context context)
{
var instantiate = typeof(BaseExpressionFactory).GetMethod(nameof(InstantiateScalarResolver), BindingFlags.Static | BindingFlags.NonPublic, new[] { typeof(IParameter), typeof(Context) })
var instantiate = typeof(BaseExpressionFactory).GetMethod(nameof(InstantiateScalarResolver), BindingFlags.Static | BindingFlags.NonPublic, [typeof(IParameter), typeof(Context)])
?? throw new InvalidProgramException(nameof(InstantiateScalarResolver));
var instantiateGeneric = instantiate.MakeGenericMethod(scalarType);
var resolver = instantiateGeneric.Invoke(null, new object[] { parameter, context })!;
Expand All @@ -69,10 +69,10 @@ protected Delegate InstantiateScalarDelegate(IParameter parameter, Type scalarTy
private static IScalarResolver<T> InstantiateScalarResolver<T>(IParameter parameter, Context context)
=> parameter switch
{
LiteralParameter l => InstantiateScalarResolver<T>(typeof(LiteralScalarResolver<T>), new object[] { l.Value }),
VariableParameter v => InstantiateScalarResolver<T>(typeof(VariableScalarResolver<T>), new object[] { v.Name, context.Variables }),
ObjectPropertyParameter item => InstantiateScalarResolver<T>(typeof(ObjectPropertyResolver<T>), new object[] { item.Name, context.CurrentObject }),
ObjectIndexParameter index => InstantiateScalarResolver<T>(typeof(ObjectIndexResolver<T>), new object[] { index.Index, context.CurrentObject }),
LiteralParameter l => InstantiateScalarResolver<T>(typeof(LiteralScalarResolver<T>), [l.Value]),
VariableParameter v => InstantiateScalarResolver<T>(typeof(VariableScalarResolver<T>), [v.Name, context.Variables]),
ObjectPropertyParameter item => InstantiateScalarResolver<T>(typeof(ObjectPropertyResolver<T>), [item.Name, context.CurrentObject]),
ObjectIndexParameter index => InstantiateScalarResolver<T>(typeof(ObjectIndexResolver<T>), [index.Index, context.CurrentObject]),
_ => throw new ArgumentOutOfRangeException(nameof(parameter))
};

Expand All @@ -86,7 +86,7 @@ protected Delegate InstantiateIntervalDelegate(IParameter parameter, Type type,

var interval = new IntervalBuilder().Create(i.Value.LowerBoundType, i.Value.LowerBound, i.Value.UpperBound, i.Value.UpperBoundType);

var instantiate = typeof(BaseExpressionFactory).GetMethod(nameof(InstantiateScalarResolver), BindingFlags.Static | BindingFlags.NonPublic, new[] { typeof(Type), typeof(object[]) })
var instantiate = typeof(BaseExpressionFactory).GetMethod(nameof(InstantiateScalarResolver), BindingFlags.Static | BindingFlags.NonPublic, [typeof(Type), typeof(object[])])
?? throw new InvalidProgramException(nameof(InstantiateScalarResolver));
var instantiateGeneric = instantiate.MakeGenericMethod(type);

Expand All @@ -108,7 +108,7 @@ protected Delegate InstantiateInputExpressionDelegate(InputExpressionParameter e

var arg = InstantiateScalarDelegate(exp.Expression.Parameter, typeof(object), context);

var instantiate = typeof(BaseExpressionFactory).GetMethod(nameof(InstantiateScalarResolver), BindingFlags.Static | BindingFlags.NonPublic, new[] { typeof(Type), typeof(object[]) })
var instantiate = typeof(BaseExpressionFactory).GetMethod(nameof(InstantiateScalarResolver), BindingFlags.Static | BindingFlags.NonPublic, [typeof(Type), typeof(object[])])
?? throw new InvalidProgramException(nameof(InstantiateScalarResolver));
var instantiateGeneric = instantiate.MakeGenericMethod(type);

Expand Down
4 changes: 2 additions & 2 deletions Expressif/Functions/BaseTypeMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ namespace Expressif.Functions;

public abstract class BaseTypeMapper
{
private IDictionary<string, Type>? _mapping;
protected IDictionary<string, Type> Mapping { get => _mapping ??= Initialize(); }
private IDictionary<string, Type>? mapping;
protected IDictionary<string, Type> Mapping { get => mapping ??= Initialize(); }

public Type Execute(string functionName)
{
Expand Down
6 changes: 3 additions & 3 deletions Expressif/Functions/Introspection/BaseIntrospector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ public abstract class BaseIntrospector
protected record class AttributeInfo<T>(Type Type, T Attribute) { }
private ITypesProbe Probe { get; }

private Type[]? _types;
protected Type[] Types { get => _types ??= Probe.Locate().ToArray(); }
private Type[]? types;
protected Type[] Types { get => types ??= Probe.Locate().ToArray(); }

protected BaseIntrospector(ITypesProbe probe)
=> Probe = probe;
Expand Down Expand Up @@ -44,7 +44,7 @@ protected IEnumerable<ParameterInfo> BuildParameters(CtorInfo[] ctorInfos)

public class AssemblyTypesProbe : ITypesProbe
{
public Assembly[] Assemblies { get; } = new[] { typeof(Expression).Assembly };
public Assembly[] Assemblies { get; } = [typeof(Expression).Assembly];

public AssemblyTypesProbe()
{ }
Expand Down
18 changes: 9 additions & 9 deletions Expressif/Functions/Introspection/DocumentationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ public static CtorInfo[] GetInfoConstructors(this Type type)
{
var ctorNodes = XmlFromPattern(type, 'M', "#ctor");

if (ctorNodes == null || !ctorNodes.Any())
return Array.Empty<CtorInfo>();
if (ctorNodes == null || ctorNodes.Length==0)
return [];

var ctorInfos = new List<CtorInfo>();
foreach (var ctorNode in ctorNodes)
Expand Down Expand Up @@ -137,12 +137,12 @@ private static XmlElement[] XmlFromPattern(this Type type, char prefix, string p
/// <summary>
/// A cache used to remember Xml documentation for assemblies.
/// </summary>
private static readonly Dictionary<Assembly, XmlDocument> Cache = new();
private static readonly Dictionary<Assembly, XmlDocument> cache = [];

/// <summary>
/// A cache used to store failure exceptions for assembly lookups.
/// </summary>
private static readonly Dictionary<Assembly, Exception> FailCache = new();
private static readonly Dictionary<Assembly, Exception> failCache = [];

/// <summary>
/// Obtains the documentation file for the specified assembly.
Expand All @@ -153,19 +153,19 @@ private static XmlElement[] XmlFromPattern(this Type type, char prefix, string p
/// the XML file is not loaded and parsed on every single lookup.</remarks>
public static XmlDocument XmlFromAssembly(this Assembly assembly)
{
if (FailCache.TryGetValue(assembly, out var value))
if (failCache.TryGetValue(assembly, out var value))
throw value;

try
{
if (!Cache.ContainsKey(assembly))
Cache[assembly] = XmlFromAssemblyNonCached(assembly);
if (!cache.ContainsKey(assembly))
cache[assembly] = XmlFromAssemblyNonCached(assembly);

return Cache[assembly];
return cache[assembly];
}
catch (Exception exception)
{
FailCache[assembly] = exception;
failCache[assembly] = exception;
throw;
}
}
Expand Down
4 changes: 2 additions & 2 deletions Expressif/Functions/Temporal/LengthFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ protected override object EvaluateInteger(int value)
/// </summary>
public class LengthOfMonth : BaseTemporalLengthFunction
{
private static readonly int[] LongMonths = { 1, 3, 5, 7, 8, 10, 12 };
protected static readonly int[] LongMonths = [1, 3, 5, 7, 8, 10, 12];
protected override object EvaluateDateTime(DateTime value)
=> EvaluateYearMonth(new YearMonth(value.Year, value.Month));

protected override object EvaluateYearMonth(YearMonth yearMonth)
=> (yearMonth.Month == 2)
? 28 + (DateTime.IsLeapYear(yearMonth.Year) ? 1 : 0)
: 30 + (LongMonths.Contains(yearMonth.Month) ? 1 : 0);
}
}
6 changes: 3 additions & 3 deletions Expressif/Functions/Temporal/TemporalFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public class PreviousYear : BaseTemporalFunction
/// <summary>
/// Returns the value of an argument dateTime, unless it is before min (in which case it returns min), or after max (in which case it returns max).
/// </summary>
[Function(prefix: "dateTime", aliases:new []{"dateTime-to-clip"})]
[Function(prefix: "dateTime", aliases:["dateTime-to-clip"])]
public class Clamp : BaseTemporalFunction
{
public Func<DateTime> Min { get; }
Expand Down Expand Up @@ -258,7 +258,7 @@ protected override object EvaluateDateTime(DateTime value)
/// <summary>
/// Returns a dateTime that adds the timestamp passed as parameter to the argument. If times is specified this operation is reproduced.
/// </summary>
[Function(prefix: "dateTime", aliases: new[] {"dateTime-to-add"})]
[Function(prefix: "dateTime", aliases: ["dateTime-to-add"])]
public class Forward : BaseTemporalFunction
{
public Func<int> Times { get; }
Expand All @@ -280,7 +280,7 @@ protected override object EvaluateDateTime(DateTime value)
/// <summary>
/// Returns a dateTime that subtract the timestamp passed as parameter to the argument. If times is specified this operation is reproduced.
/// </summary>
[Function(prefix: "dateTime", aliases: new[] { "dateTime-to-subtract" })]
[Function(prefix: "dateTime", aliases: ["dateTime-to-subtract"])]
public class Backward : Forward
{
/// <param name="timeSpan">The value to be subtracted to the argument value.</param>
Expand Down
4 changes: 2 additions & 2 deletions Expressif/Functions/Temporal/WeekdayFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ protected override object EvaluateDate(DateOnly date)
/// <summary>
/// Returns a new date value corresponding to the date passed as the argument, counting forward the business days (being weekdays different of Saturday and Sunday) specified as the parameter. It always returns a business day, as such if the date passed as the argument is a weekend, it considers that this date was the Friday before the argument value.
/// </summary>
[Function(aliases: new[] { "next-business-day", "add-business-days" })]
[Function(aliases: ["next-business-day", "add-business-days"])]
public class NextBusinessDays : BaseTemporalWeekdayFunction
{
internal Func<int> Count { get; }
Expand Down Expand Up @@ -151,7 +151,7 @@ protected virtual DateOnly BasicStrategy(DateOnly date, int direction)
/// <summary>
/// Returns a new date value corresponding to the date passed as the argument, counting backward the business days (being weekdays different of Saturday and Sunday) specified as the parameter. It always returns a business day, as such if the date passed as the argument is a weekend, it considers that this date was the Friday before the argument value.
/// </summary>
[Function(aliases: new[] { "previous-business-day", "subtract-business-days" })]
[Function(aliases: ["previous-business-day", "subtract-business-days"])]
public class PreviousBusinessDays : NextBusinessDays
{
/// <param name="count">The count of business days to move forward.</param>
Expand Down
2 changes: 1 addition & 1 deletion Expressif/Functions/Text/CountingFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public abstract class BaseTextCountingFunction : BaseTextFunction
/// <summary>
/// Returns the length of the argument value. If the value is `null` or `empty` then it returns `0`. If the value is `blank` then it returns `-1`.
/// </summary>
[Function(prefix: "", aliases: new[] { "count-chars" })]
[Function(prefix: "", aliases: ["count-chars"])]
public class Length : BaseTextCountingFunction
{
protected override object EvaluateSpecial(string value) => -1;
Expand Down
6 changes: 3 additions & 3 deletions Expressif/Functions/Text/TextFunctions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ protected virtual object EvaluateHighLevelString(string value)
if (new Whitespace().Equals(value))
return EvaluateBlank();

if (value.StartsWith("(") && value.EndsWith(")"))
if (value.StartsWith('(') && value.EndsWith(')'))
return EvaluateSpecial(value);

return EvaluateString(value);
Expand All @@ -62,7 +62,7 @@ protected virtual object EvaluateHighLevelString(string value)
/// <summary>
/// Returns the argument value except if this value only contains white-space characters then it returns `empty`.
/// </summary>
[Function(prefix:"", aliases: new[] {"blank-to-empty"})]
[Function(prefix:"", aliases: ["blank-to-empty"])]
public class WhitespacesToEmpty : BaseTextFunction
{
protected override object EvaluateBlank() => new Empty().Keyword;
Expand All @@ -72,7 +72,7 @@ public class WhitespacesToEmpty : BaseTextFunction
/// <summary>
/// Returns the argument value except if this value only contains white-space characters then it returns `null`.
/// </summary>
[Function(prefix: "", aliases: new[] { "blank-to-null" })]
[Function(prefix: "", aliases: ["blank-to-null"])]
public class WhitespacesToNull : BaseTextFunction
{
protected override object EvaluateBlank() => new Null().Keyword;
Expand Down
2 changes: 1 addition & 1 deletion Expressif/Functions/Text/Tokenizer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public string[] Execute(string value)
}
else
{
return Array.Empty<string>();
return [];
}
}
}
Loading

0 comments on commit ef20deb

Please sign in to comment.