Skip to content

Commit

Permalink
Code Style Housekeeping
Browse files Browse the repository at this point in the history
- Replaced Any() with Count != 0 for better performance.
- Updated parameter types in TimeTextInfo.cs and EvaluatorTests.cs.
- Simplified assertion syntax in multiple test files.
- Changed Enum.Parse to Enum.TryParse in Address.cs.
- Converted instance methods to static in StringSource.cs.
  • Loading branch information
axunonb committed Jan 16, 2025
1 parent beb82ef commit 217fe4e
Show file tree
Hide file tree
Showing 13 changed files with 41 additions and 45 deletions.
2 changes: 0 additions & 2 deletions src/SmartFormat.Extensions.Time/TimeFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,6 @@ public bool TryEvaluateFormat(IFormattingInfo formattingInfo)
private IList<string>? GetTimeParts(IFormattingInfo formattingInfo)
{
var format = formattingInfo.Format;
var formatterName = formattingInfo.Placeholder?.FormatterName ?? string.Empty;

var current = formattingInfo.CurrentValue;

var options = formattingInfo.FormatterOptions.Trim();
Expand Down
4 changes: 2 additions & 2 deletions src/SmartFormat.Extensions.Time/Utilities/TimeSpanUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,9 @@ internal static IList<string> ToTimeParts(this TimeSpan fromTime, TimeSpanFormat
}

//Determine whether to display this value
if (!ShouldTruncate(value, result.Any(), out var displayThisValue)) continue;
if (!ShouldTruncate(value, result.Count != 0, out var displayThisValue)) continue;

PrepareOutput(value, i == _rangeMin, result.Any(), result, ref displayThisValue);
PrepareOutput(value, i == _rangeMin, result.Count != 0, result, ref displayThisValue);

// Output the value:
if (displayThisValue)
Expand Down
4 changes: 2 additions & 2 deletions src/SmartFormat.Extensions.Time/Utilities/TimeTextInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ public class TimeTextInfo
/// </summary>
public string[] Ptxt_week { get; set;} = Array.Empty<string>();

private static string GetValue(PluralRules.PluralRuleDelegate pluralRule, int value, IReadOnlyList<string> units)
private static string GetValue(PluralRules.PluralRuleDelegate pluralRule, int value, string[] units)
{
// Get the plural index from the plural rule,
// unless there's only 1 unit in the first place:
var pluralIndex = units.Count == 1 ? 0 : pluralRule(value, units.Count);
var pluralIndex = units.Length == 1 ? 0 : pluralRule(value, units.Length);
return string.Format(units[pluralIndex], value);
}

Expand Down
8 changes: 4 additions & 4 deletions src/SmartFormat.Tests/Core/FormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ public void Adding_FormatExtension_With_Existing_Name_Should_Throw()
var firstExtension = new DefaultFormatter();
formatter.AddExtensions(firstExtension);
var dupeExtension = new NullFormatter {Name = firstExtension.Name};
Assert.That(() => formatter.AddExtensions(dupeExtension), Throws.TypeOf(typeof(ArgumentException)));
Assert.That(() => formatter.AddExtensions(dupeExtension), Throws.TypeOf<ArgumentException>());
}

[Test]
Expand Down Expand Up @@ -296,7 +296,7 @@ public void Formatter_GetSourceExtension()
Assert.Multiple(() =>
{
Assert.That(formatter.GetSourceExtensions(), Has.Count.EqualTo(formatter.SourceExtensions.Count));
Assert.That(formatter.GetSourceExtension<DefaultSource>(), Is.InstanceOf(typeof(DefaultSource)));
Assert.That(formatter.GetSourceExtension<DefaultSource>(), Is.InstanceOf<DefaultSource>());
});
;
}
Expand All @@ -308,15 +308,15 @@ public void Formatter_GetFormatterExtension()
Assert.Multiple(() =>
{
Assert.That(formatter.GetFormatterExtensions(), Has.Count.EqualTo(formatter.FormatterExtensions.Count));
Assert.That(formatter.GetFormatterExtension<DefaultFormatter>(), Is.InstanceOf(typeof(DefaultFormatter)));
Assert.That(formatter.GetFormatterExtension<DefaultFormatter>(), Is.InstanceOf<DefaultFormatter>());
});
}

[Test]
public void Not_Existing_Formatter_Name_Should_Throw()
{
var smart = GetSimpleFormatter();
Assert.That(() => smart.Format("{0:not_existing_formatter_name:}", new object()), Throws.Exception.TypeOf(typeof(FormattingException)).And.Message.Contains("not_existing_formatter_name"));
Assert.That(() => smart.Format("{0:not_existing_formatter_name:}", new object()), Throws.Exception.TypeOf<FormattingException>().And.Message.Contains("not_existing_formatter_name"));
}

[Test]
Expand Down
10 changes: 5 additions & 5 deletions src/SmartFormat.Tests/Core/ParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public void Parser_Error_Action_Ignore()
Assert.That(parsed.Items[0].RawText, Is.EqualTo("Hello, I'm "), "Literal text");
Assert.That(parsed.Items[1].RawText, Is.EqualTo(string.Empty), "Erroneous placeholder");
Assert.That(parsed.Items[2].RawText, Is.EqualTo(" "));
Assert.That(parsed.Items[3], Is.TypeOf(typeof(Placeholder)));
Assert.That(parsed.Items[3], Is.TypeOf<Placeholder>());
});
Assert.That(parsed.Items[3].RawText, Does.Contain("{Street}"), "Correct placeholder");
}
Expand All @@ -188,12 +188,12 @@ public void Parser_Error_Action_MaintainTokens(string invalidTemplate, bool last
});
if (lastItemIsPlaceholder)
{
Assert.That(parsed.Items[3], Is.TypeOf(typeof(Placeholder)), "Last item should be Placeholder");
Assert.That(parsed.Items[3], Is.TypeOf<Placeholder>(), "Last item should be Placeholder");
Assert.That(parsed.Items[3].RawText, Does.Contain("{Street}"));
}
else
{
Assert.That(parsed.Items[3], Is.TypeOf(typeof(LiteralText)), "Last item should be LiteralText");
Assert.That(parsed.Items[3], Is.TypeOf<LiteralText>(), "Last item should be LiteralText");
Assert.That(parsed.Items[3].RawText, Does.Contain("{Street"));
}
}
Expand Down Expand Up @@ -458,7 +458,7 @@ public void Missing_Curly_Brace_Should_Throw()
var format = "{0:yyyy/MM/dd HH:mm:ss";

Assert.That(() => parser.ParseFormat(format),
Throws.Exception.InstanceOf(typeof(ParsingErrors)).And.Message
Throws.Exception.InstanceOf<ParsingErrors>().And.Message
.Contains(new Parser.ParsingErrorText()[Parser.ParsingError.MissingClosingBrace]));
}

Expand Down Expand Up @@ -533,7 +533,7 @@ public void Parse_Unicode(string formatString, string unicodeLiteral, int itemIn
var result = parser.ParseFormat(formatString);

var literal = result.Items[itemIndex];
Assert.That(literal, Is.TypeOf(typeof(LiteralText)));
Assert.That(literal, Is.TypeOf<LiteralText>());
Assert.That(literal.BaseString.Substring(literal.StartIndex, literal.Length), Is.EqualTo(unicodeLiteral));

if(isLegal)
Expand Down
2 changes: 1 addition & 1 deletion src/SmartFormat.Tests/EvaluatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ public void Placeholder_To_Span_Using_FormattingInfo()

#region ** Helpers **

private static void ExecuteFormattingAction(SmartFormatter formatter, IFormatProvider? provider, Format formatParsed, IList<object?> args, IOutput output, Action<FormattingInfo> doWork)
private static void ExecuteFormattingAction(SmartFormatter formatter, IFormatProvider? provider, Format formatParsed, List<object?> args, IOutput output, Action<FormattingInfo> doWork)
{
// The first item is the default and will be used for the action,
// but all args go to FormatDetails.OriginalArgs
Expand Down
10 changes: 5 additions & 5 deletions src/SmartFormat.Tests/Extensions/ReflectionSourceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public void Test_Parameterless_Methods()
var smart = GetFormatter();

var args = GetArgs();
Assert.That(() => smart.Format(format, args), Throws.Exception.TypeOf(typeof(FormattingException)).And.Message.Contains("ToLower"));
Assert.That(() => smart.Format(format, args), Throws.Exception.TypeOf<FormattingException>().And.Message.Contains("ToLower"));
}

/// <summary>
Expand All @@ -119,28 +119,28 @@ public void Test_Methods_CaseInsensitive()
var format = "{0} {0.ToLower} {toloWer} {touPPer}";
//var expected = "Zero zero zero ZERO";
var args = GetArgs();
Assert.That(() => smart.Format(format, args), Throws.Exception.TypeOf(typeof(FormattingException)).And.Message.Contains("ToLower"));
Assert.That(() => smart.Format(format, args), Throws.Exception.TypeOf<FormattingException>().And.Message.Contains("ToLower"));
}

[Test]
public void Void_Methods_Should_Just_Be_Ignored()
{
var smart = GetFormatter();
Assert.That(() => smart.Format("{0.Clear}", smart.SourceExtensions), Throws.Exception.TypeOf(typeof(FormattingException)).And.Message.Contains("Clear"));
Assert.That(() => smart.Format("{0.Clear}", smart.SourceExtensions), Throws.Exception.TypeOf<FormattingException>().And.Message.Contains("Clear"));
}

[Test]
public void Methods_With_Parameter_Should_Just_Be_Ignored()
{
var smart = GetFormatter();
Assert.That(() => smart.Format("{0.Add}", smart.SourceExtensions), Throws.Exception.TypeOf(typeof(FormattingException)).And.Message.Contains("Add"));
Assert.That(() => smart.Format("{0.Add}", smart.SourceExtensions), Throws.Exception.TypeOf<FormattingException>().And.Message.Contains("Add"));
}

[Test]
public void Properties_With_No_Getter_Should_Just_Be_Ignored()
{
var smart = GetFormatter();
Assert.That(() => smart.Format("{Misc.OnlySetterProperty}", new { Misc = new MiscObject() }), Throws.Exception.TypeOf(typeof(FormattingException)).And.Message.Contains("OnlySetterProperty"));
Assert.That(() => smart.Format("{Misc.OnlySetterProperty}", new { Misc = new MiscObject() }), Throws.Exception.TypeOf<FormattingException>().And.Message.Contains("OnlySetterProperty"));
}


Expand Down
4 changes: 2 additions & 2 deletions src/SmartFormat.Tests/Extensions/StringSourceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,15 @@ public void TryEvaluate_Should_Fail_For_Unknown_Selector_Name(string selector)
{
var smart = GetSimpleFormatter();
var format = $"{{0.{selector}}}";
Assert.That(() => smart.Format(format, "dummy"), Throws.Exception.TypeOf(typeof(FormattingException)).And.Message.Contains($"selector named \"{selector}\""));
Assert.That(() => smart.Format(format, "dummy"), Throws.Exception.TypeOf<FormattingException>().And.Message.Contains($"selector named \"{selector}\""));
}

[Test]
public void TryEvaluate_Should_Fail_For_Bad_Base64_String()
{
var smart = GetSimpleFormatter();
var format = "{0.FromBase64}";
Assert.That(() => smart.Format(format, "dummy"), Throws.Exception.TypeOf(typeof(FormattingException)));
Assert.That(() => smart.Format(format, "dummy"), Throws.Exception.TypeOf<FormattingException>());
}


Expand Down
2 changes: 1 addition & 1 deletion src/SmartFormat.Tests/Extensions/ValueTupleSourceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public void Format_With_Null_Values_In_ValueTuples(string format, bool shouldSuc
else
{
Assert.That(() => formatter.Format(format, (dict1, dict2, addr)),
Throws.Exception.TypeOf(typeof(FormattingException)));
Throws.Exception.TypeOf<FormattingException>());
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/SmartFormat.Tests/Pooling/PoolPolicyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class PoolPolicyTests
public void Illegal_Pool_Size_Should_Throw()
{
Assert.That(() => new PoolPolicy<object> { MaximumPoolSize = 0 },
Throws.InstanceOf(typeof(PoolingException))
Throws.InstanceOf<PoolingException>()
.And
.Property(nameof(PoolingException.PoolType))
.EqualTo(typeof(object)));
Expand Down
14 changes: 6 additions & 8 deletions src/SmartFormat.Tests/TestUtils/Address.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,18 +91,16 @@ public static string GetStateAbbreviation(States state)
public static States ParseState(string state)
{
// See if the abbreviation matches one of the states:
States result = States.Unknown;
var result = States.Unknown;
if (AbbreviationAttribute.TryFindAbbreviation<States>(state, true, ref result))
return result;

// Try to parse the full state name:
try {
return (States)Enum.Parse(typeof(States), state, true);
} catch {
// Couldn't parse the full state name!
return States.Unknown;
}
if (Enum.TryParse(state, out result))
return result;

// Couldn't parse the full state name!
return States.Unknown;
}
#endregion

Expand Down Expand Up @@ -289,4 +287,4 @@ public static bool TryFindAbbreviation<TBaseType>(string abbreviation, bool igno
return false;
}

}
}
4 changes: 2 additions & 2 deletions src/SmartFormat/Core/Parsing/SplitList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public Format this[int index]
{
get
{
if (index > _splits.Count) throw new ArgumentOutOfRangeException(nameof(index));
if (index > _splits.Count) throw new ArgumentOutOfRangeException(nameof(index)); //NOSONAR - ArgumentOutOfRangeException.ThrowIfGreaterThan < net5.0

if (_splits.Count == 0) return _format;

Expand Down Expand Up @@ -189,4 +189,4 @@ IEnumerator IEnumerable.GetEnumerator()
}

#endregion
}
}
20 changes: 10 additions & 10 deletions src/SmartFormat/Extensions/StringSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public override bool TryEvaluateSelector(ISelectorInfo selectorInfo)
return method.Invoke(selectorInfo, currentValue);
}

private bool Length(ISelectorInfo selectorInfo, string currentValue)
private static bool Length(ISelectorInfo selectorInfo, string currentValue)
{
selectorInfo.Result = currentValue.Length;
return true;
Expand All @@ -100,7 +100,7 @@ private bool ToUpper(ISelectorInfo selectorInfo, string currentValue)
return true;
}

private bool ToUpperInvariant(ISelectorInfo selectorInfo, string currentValue)
private static bool ToUpperInvariant(ISelectorInfo selectorInfo, string currentValue)
{
selectorInfo.Result = currentValue.ToUpperInvariant();
return true;
Expand All @@ -112,30 +112,30 @@ private bool ToLower(ISelectorInfo selectorInfo, string currentValue)
return true;
}

private bool ToLowerInvariant(ISelectorInfo selectorInfo, string currentValue)
private static bool ToLowerInvariant(ISelectorInfo selectorInfo, string currentValue)
{
selectorInfo.Result = currentValue.ToLowerInvariant();
return true;
}

private bool Trim(ISelectorInfo selectorInfo, string currentValue)
private static bool Trim(ISelectorInfo selectorInfo, string currentValue)
{
selectorInfo.Result = currentValue.Trim();
return true;
}

private bool TrimStart(ISelectorInfo selectorInfo, string currentValue)
private static bool TrimStart(ISelectorInfo selectorInfo, string currentValue)
{
selectorInfo.Result = currentValue.TrimStart();
return true;
}

private bool TrimEnd(ISelectorInfo selectorInfo, string currentValue)
private static bool TrimEnd(ISelectorInfo selectorInfo, string currentValue)
{
selectorInfo.Result = currentValue.TrimEnd();
return true;
}
private bool ToCharArray(ISelectorInfo selectorInfo, string currentValue)
private static bool ToCharArray(ISelectorInfo selectorInfo, string currentValue)
{
selectorInfo.Result =currentValue.ToCharArray();
return true;
Expand Down Expand Up @@ -190,13 +190,13 @@ private bool CapitalizeWords(ISelectorInfo selectorInfo, string currentValue)
return true;
}

private bool ToBase64(ISelectorInfo selectorInfo, string currentValue)
private static bool ToBase64(ISelectorInfo selectorInfo, string currentValue)
{
selectorInfo.Result = Convert.ToBase64String(Encoding.UTF8.GetBytes(currentValue));
return true;
}

private bool FromBase64(ISelectorInfo selectorInfo, string currentValue)
private static bool FromBase64(ISelectorInfo selectorInfo, string currentValue)
{
selectorInfo.Result = Encoding.UTF8.GetString(Convert.FromBase64String(currentValue));
return true;
Expand All @@ -210,4 +210,4 @@ private static CultureInfo GetCulture(FormatDetails formatDetails)

return CultureInfo.CurrentUICulture;
}
}
}

0 comments on commit 217fe4e

Please sign in to comment.