From 217fe4e4f452253b020952e5ecfd706a22d82539 Mon Sep 17 00:00:00 2001 From: axunonb Date: Thu, 16 Jan 2025 23:08:36 +0100 Subject: [PATCH] Code Style Housekeeping - 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. --- .../TimeFormatter.cs | 2 -- .../Utilities/TimeSpanUtility.cs | 4 ++-- .../Utilities/TimeTextInfo.cs | 4 ++-- src/SmartFormat.Tests/Core/FormatterTests.cs | 8 ++++---- src/SmartFormat.Tests/Core/ParserTests.cs | 10 +++++----- src/SmartFormat.Tests/EvaluatorTests.cs | 2 +- .../Extensions/ReflectionSourceTests.cs | 10 +++++----- .../Extensions/StringSourceTests.cs | 4 ++-- .../Extensions/ValueTupleSourceTests.cs | 2 +- .../Pooling/PoolPolicyTests.cs | 2 +- src/SmartFormat.Tests/TestUtils/Address.cs | 14 ++++++------- src/SmartFormat/Core/Parsing/SplitList.cs | 4 ++-- src/SmartFormat/Extensions/StringSource.cs | 20 +++++++++---------- 13 files changed, 41 insertions(+), 45 deletions(-) diff --git a/src/SmartFormat.Extensions.Time/TimeFormatter.cs b/src/SmartFormat.Extensions.Time/TimeFormatter.cs index 23cad2cf..68cfe36b 100644 --- a/src/SmartFormat.Extensions.Time/TimeFormatter.cs +++ b/src/SmartFormat.Extensions.Time/TimeFormatter.cs @@ -166,8 +166,6 @@ public bool TryEvaluateFormat(IFormattingInfo formattingInfo) private IList? GetTimeParts(IFormattingInfo formattingInfo) { var format = formattingInfo.Format; - var formatterName = formattingInfo.Placeholder?.FormatterName ?? string.Empty; - var current = formattingInfo.CurrentValue; var options = formattingInfo.FormatterOptions.Trim(); diff --git a/src/SmartFormat.Extensions.Time/Utilities/TimeSpanUtility.cs b/src/SmartFormat.Extensions.Time/Utilities/TimeSpanUtility.cs index 32dfb8b8..828a1424 100644 --- a/src/SmartFormat.Extensions.Time/Utilities/TimeSpanUtility.cs +++ b/src/SmartFormat.Extensions.Time/Utilities/TimeSpanUtility.cs @@ -139,9 +139,9 @@ internal static IList 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) diff --git a/src/SmartFormat.Extensions.Time/Utilities/TimeTextInfo.cs b/src/SmartFormat.Extensions.Time/Utilities/TimeTextInfo.cs index d04bcdae..e33725c2 100644 --- a/src/SmartFormat.Extensions.Time/Utilities/TimeTextInfo.cs +++ b/src/SmartFormat.Extensions.Time/Utilities/TimeTextInfo.cs @@ -83,11 +83,11 @@ public class TimeTextInfo /// public string[] Ptxt_week { get; set;} = Array.Empty(); - private static string GetValue(PluralRules.PluralRuleDelegate pluralRule, int value, IReadOnlyList 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); } diff --git a/src/SmartFormat.Tests/Core/FormatterTests.cs b/src/SmartFormat.Tests/Core/FormatterTests.cs index b3866556..ad27174c 100644 --- a/src/SmartFormat.Tests/Core/FormatterTests.cs +++ b/src/SmartFormat.Tests/Core/FormatterTests.cs @@ -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()); } [Test] @@ -296,7 +296,7 @@ public void Formatter_GetSourceExtension() Assert.Multiple(() => { Assert.That(formatter.GetSourceExtensions(), Has.Count.EqualTo(formatter.SourceExtensions.Count)); - Assert.That(formatter.GetSourceExtension(), Is.InstanceOf(typeof(DefaultSource))); + Assert.That(formatter.GetSourceExtension(), Is.InstanceOf()); }); ; } @@ -308,7 +308,7 @@ public void Formatter_GetFormatterExtension() Assert.Multiple(() => { Assert.That(formatter.GetFormatterExtensions(), Has.Count.EqualTo(formatter.FormatterExtensions.Count)); - Assert.That(formatter.GetFormatterExtension(), Is.InstanceOf(typeof(DefaultFormatter))); + Assert.That(formatter.GetFormatterExtension(), Is.InstanceOf()); }); } @@ -316,7 +316,7 @@ public void Formatter_GetFormatterExtension() 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().And.Message.Contains("not_existing_formatter_name")); } [Test] diff --git a/src/SmartFormat.Tests/Core/ParserTests.cs b/src/SmartFormat.Tests/Core/ParserTests.cs index 2452c9ce..8a752354 100644 --- a/src/SmartFormat.Tests/Core/ParserTests.cs +++ b/src/SmartFormat.Tests/Core/ParserTests.cs @@ -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()); }); Assert.That(parsed.Items[3].RawText, Does.Contain("{Street}"), "Correct placeholder"); } @@ -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(), "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(), "Last item should be LiteralText"); Assert.That(parsed.Items[3].RawText, Does.Contain("{Street")); } } @@ -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().And.Message .Contains(new Parser.ParsingErrorText()[Parser.ParsingError.MissingClosingBrace])); } @@ -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()); Assert.That(literal.BaseString.Substring(literal.StartIndex, literal.Length), Is.EqualTo(unicodeLiteral)); if(isLegal) diff --git a/src/SmartFormat.Tests/EvaluatorTests.cs b/src/SmartFormat.Tests/EvaluatorTests.cs index c58415eb..194a3e04 100644 --- a/src/SmartFormat.Tests/EvaluatorTests.cs +++ b/src/SmartFormat.Tests/EvaluatorTests.cs @@ -282,7 +282,7 @@ public void Placeholder_To_Span_Using_FormattingInfo() #region ** Helpers ** - private static void ExecuteFormattingAction(SmartFormatter formatter, IFormatProvider? provider, Format formatParsed, IList args, IOutput output, Action doWork) + private static void ExecuteFormattingAction(SmartFormatter formatter, IFormatProvider? provider, Format formatParsed, List args, IOutput output, Action doWork) { // The first item is the default and will be used for the action, // but all args go to FormatDetails.OriginalArgs diff --git a/src/SmartFormat.Tests/Extensions/ReflectionSourceTests.cs b/src/SmartFormat.Tests/Extensions/ReflectionSourceTests.cs index 82fd138f..94857e46 100644 --- a/src/SmartFormat.Tests/Extensions/ReflectionSourceTests.cs +++ b/src/SmartFormat.Tests/Extensions/ReflectionSourceTests.cs @@ -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().And.Message.Contains("ToLower")); } /// @@ -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().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().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().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().And.Message.Contains("OnlySetterProperty")); } diff --git a/src/SmartFormat.Tests/Extensions/StringSourceTests.cs b/src/SmartFormat.Tests/Extensions/StringSourceTests.cs index e96dae22..8442ce22 100644 --- a/src/SmartFormat.Tests/Extensions/StringSourceTests.cs +++ b/src/SmartFormat.Tests/Extensions/StringSourceTests.cs @@ -70,7 +70,7 @@ 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().And.Message.Contains($"selector named \"{selector}\"")); } [Test] @@ -78,7 +78,7 @@ 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()); } diff --git a/src/SmartFormat.Tests/Extensions/ValueTupleSourceTests.cs b/src/SmartFormat.Tests/Extensions/ValueTupleSourceTests.cs index e91857c6..dbe2772b 100644 --- a/src/SmartFormat.Tests/Extensions/ValueTupleSourceTests.cs +++ b/src/SmartFormat.Tests/Extensions/ValueTupleSourceTests.cs @@ -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()); } } diff --git a/src/SmartFormat.Tests/Pooling/PoolPolicyTests.cs b/src/SmartFormat.Tests/Pooling/PoolPolicyTests.cs index 8ebf39b9..2a9a2fee 100644 --- a/src/SmartFormat.Tests/Pooling/PoolPolicyTests.cs +++ b/src/SmartFormat.Tests/Pooling/PoolPolicyTests.cs @@ -11,7 +11,7 @@ public class PoolPolicyTests public void Illegal_Pool_Size_Should_Throw() { Assert.That(() => new PoolPolicy { MaximumPoolSize = 0 }, - Throws.InstanceOf(typeof(PoolingException)) + Throws.InstanceOf() .And .Property(nameof(PoolingException.PoolType)) .EqualTo(typeof(object))); diff --git a/src/SmartFormat.Tests/TestUtils/Address.cs b/src/SmartFormat.Tests/TestUtils/Address.cs index 7b9109eb..a3b5e7cc 100644 --- a/src/SmartFormat.Tests/TestUtils/Address.cs +++ b/src/SmartFormat.Tests/TestUtils/Address.cs @@ -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(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 @@ -289,4 +287,4 @@ public static bool TryFindAbbreviation(string abbreviation, bool igno return false; } -} \ No newline at end of file +} diff --git a/src/SmartFormat/Core/Parsing/SplitList.cs b/src/SmartFormat/Core/Parsing/SplitList.cs index 0889cd1d..06da87e7 100644 --- a/src/SmartFormat/Core/Parsing/SplitList.cs +++ b/src/SmartFormat/Core/Parsing/SplitList.cs @@ -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; @@ -189,4 +189,4 @@ IEnumerator IEnumerable.GetEnumerator() } #endregion -} \ No newline at end of file +} diff --git a/src/SmartFormat/Extensions/StringSource.cs b/src/SmartFormat/Extensions/StringSource.cs index 583ca0ce..861d4b1c 100644 --- a/src/SmartFormat/Extensions/StringSource.cs +++ b/src/SmartFormat/Extensions/StringSource.cs @@ -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; @@ -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; @@ -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; @@ -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; @@ -210,4 +210,4 @@ private static CultureInfo GetCulture(FormatDetails formatDetails) return CultureInfo.CurrentUICulture; } -} \ No newline at end of file +}