From 4714d2f1c357451ca2037dfb34e0b9428f23cec5 Mon Sep 17 00:00:00 2001 From: smitchamwork <127128500+smitchamwork@users.noreply.github.com> Date: Fri, 20 Oct 2023 19:23:02 -0500 Subject: [PATCH] perf: unnecessary exceptions when checking if a project is versionable (#106) In the case of checking whether a project can be versioned, the invalid operation exception is swallowed because it is not really invalid for that use case. This update only builds the exception for the Create case and so skips the cost of the exception in the more common case --- Versionize/Project.cs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/Versionize/Project.cs b/Versionize/Project.cs index 53c70d6..3d7d3c0 100644 --- a/Versionize/Project.cs +++ b/Versionize/Project.cs @@ -16,7 +16,12 @@ private Project(string projectFile, SemanticVersion version) public static Project Create(string projectFile) { - var version = ReadVersion(projectFile); + var (success,version, error) = ReadVersion(projectFile); + + if (!success) + { + throw new InvalidOperationException(error); + } return new Project(projectFile, version); } @@ -25,8 +30,8 @@ public static bool IsVersionable(string projectFile) { try { - ReadVersion(projectFile); - return true; + var (success, _, _) = ReadVersion(projectFile); + return success; } catch (Exception) { @@ -34,7 +39,7 @@ public static bool IsVersionable(string projectFile) } } - private static SemanticVersion ReadVersion(string projectFile) + private static (bool, SemanticVersion, string) ReadVersion(string projectFile) { var doc = ReadProject(projectFile); @@ -42,16 +47,20 @@ private static SemanticVersion ReadVersion(string projectFile) if (string.IsNullOrWhiteSpace(versionString)) { - throw new InvalidOperationException($"Project {projectFile} contains no or an empty XML Element. Please add one if you want to version this project - for example use 1.0.0"); + return (false, + null, + $"Project {projectFile} contains no or an empty XML Element. Please add one if you want to version this project - for example use 1.0.0" + ); } try { - return SemanticVersion.Parse(versionString); + return (true, SemanticVersion.Parse(versionString),null); } catch (Exception) { - throw new InvalidOperationException($"Project {projectFile} contains an invalid version {versionString}. Please fix the currently contained version - for example use 1.0.0"); + return (false, null, + $"Project {projectFile} contains an invalid version {versionString}. Please fix the currently contained version - for example use 1.0.0"); } }