Skip to content

Commit

Permalink
Seal private/internal types and make methods static when applicable (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma authored Nov 21, 2024
1 parent bdfa513 commit 7b2b910
Show file tree
Hide file tree
Showing 36 changed files with 74 additions and 70 deletions.
4 changes: 1 addition & 3 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -99,12 +99,10 @@
[CA1720] Identifier 'xxx' contains type name
[CA1725] Overriden parameter name mismatch
[CA1805] Member is explicitly initialized to its default value
[CA1822] Member does not access instance data and can be marked as static
[CA1827] Count() is used where Any() could be used instead to improve performance
[CA1834] Use 'StringBuilder.Append(char)' instead of 'StringBuilder.Append(string)' when the input is a constant unit string
[CA1845] Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
[CA1847] Use 'string.Contains(char)' instead of 'string.Contains(string)' - needs polyfill
[CA1852] Type can be sealed because it has no subtypes in its containing assembly and is not externally visible
[CA1854] Prefer a 'TryGetValue' call over a Dictionary indexer access
[CA1860] Prefer comparing 'Count' to 0 rather than using 'Any()'
[CA1861] Prefer 'static readonly' fields over constant array arguments
Expand All @@ -118,7 +116,7 @@
[SYSLIB0012] 'Assembly.CodeBase' is obsolete
-->
<NoWarn>$(NoWarn);IDE0005;IDE0008;IDE0011;IDE0017;IDE0019;IDE0021;IDE0022;IDE0025;IDE0027;IDE0028;IDE0029;IDE0032;IDE0039;IDE0040;IDE0044;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0059;IDE0060;IDE0061;IDE0063;IDE0074;IDE0078;IDE0083;IDE0090;IDE0100;IDE0130;IDE0160;IDE0200;IDE0260;IDE0270;IDE0290;IDE0300;IDE0305;IDE0301;IDE0330;IDE1005</NoWarn>
<NoWarn>$(NoWarn);CA1200;CA1304;CA1305;CA1310;CA1311;CA1507;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1805;CA1822;CA1827;CA1834;CA1845;CA1847;CA1852;CA1854;CA1860;CA1861;CA1862;CA1865;CA1866;CA1870;CA2249;CA2263;SYSLIB0012</NoWarn>
<NoWarn>$(NoWarn);CA1200;CA1304;CA1305;CA1310;CA1311;CA1507;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1805;CA1827;CA1834;CA1845;CA1847;CA1854;CA1860;CA1861;CA1862;CA1865;CA1866;CA1870;CA2249;CA2263;SYSLIB0012</NoWarn>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

namespace NSwag.AspNet.Owin.Middlewares
{
internal class RedirectToIndexMiddleware : OwinMiddleware
internal sealed class RedirectToIndexMiddleware : OwinMiddleware
{
private readonly string _internalUiRoute;
private readonly string _internalSwaggerRoute;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace NSwag.AspNet.Owin.Middlewares
{
internal class SwaggerUiIndexMiddleware<T> : OwinMiddleware
internal sealed class SwaggerUiIndexMiddleware<T> : OwinMiddleware
where T : OpenApiDocumentGeneratorSettings, new()
{
private readonly string _indexPath;
Expand Down
4 changes: 2 additions & 2 deletions src/NSwag.AspNet.WebApi/JsonExceptionFilterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public override void OnActionExecuted(HttpActionExecutedContext context)
}
}

private int GetStatusCode(Exception exception, HttpActionExecutedContext context)
private static int GetStatusCode(Exception exception, HttpActionExecutedContext context)
{
if (context.ActionContext.ActionDescriptor is ReflectedHttpActionDescriptor actionDescriptor)
{
Expand All @@ -105,7 +105,7 @@ private int GetStatusCode(Exception exception, HttpActionExecutedContext context
return 500;
}

private JsonSerializerSettings CopySettings(JsonSerializerSettings settings)
private static JsonSerializerSettings CopySettings(JsonSerializerSettings settings)
{
var settingsCopy = new JsonSerializerSettings();

Expand Down
4 changes: 2 additions & 2 deletions src/NSwag.AspNetCore.Launcher/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace NSwag.AspNetCore.Launcher
{
internal class Program
internal sealed class Program
{
// Used to load NSwag.Commands into a process running with the app's dependency context
private const string EntryPointType = "NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint";
Expand Down Expand Up @@ -169,7 +169,7 @@ private static bool TryLoadReferencedAssemblies()
return true;
}

private class AssemblyLoadInfo
private sealed class AssemblyLoadInfo
{
public AssemblyLoadInfo(Version minimumRequiredVersion)
{
Expand Down
4 changes: 2 additions & 2 deletions src/NSwag.AspNetCore/JsonExceptionFilterAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public override void OnActionExecuted(ActionExecutedContext context)
}
}

private int GetStatusCode(Exception exception, ActionExecutedContext context)
private static int GetStatusCode(Exception exception, ActionExecutedContext context)
{
if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
{
Expand Down Expand Up @@ -116,7 +116,7 @@ private int GetStatusCode(Exception exception, ActionExecutedContext context)
return 500;
}

private JsonSerializerSettings CopySettings(JsonSerializerSettings settings)
private static JsonSerializerSettings CopySettings(JsonSerializerSettings settings)
{
var settingsCopy = new JsonSerializerSettings();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

namespace NSwag.AspNetCore.Middlewares
{
internal class RedirectToIndexMiddleware
internal sealed class RedirectToIndexMiddleware
{
private readonly RequestDelegate _nextDelegate;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace NSwag.AspNetCore.Middlewares
{
internal class SwaggerUiIndexMiddleware
internal sealed class SwaggerUiIndexMiddleware
{
private readonly RequestDelegate _nextDelegate;
private readonly string _indexPath;
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNetCore/OpenApiConfigureMvcOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace NSwag.AspNetCore
{
internal class OpenApiConfigureMvcOptions : ConfigureOptions<MvcOptions>
internal sealed class OpenApiConfigureMvcOptions : ConfigureOptions<MvcOptions>
{
public OpenApiConfigureMvcOptions()
: base(options => options.Conventions.Add(new OpenApiMvcApplicationModelConvention()))
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNetCore/OpenApiDocumentProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

namespace NSwag.AspNetCore
{
internal class OpenApiDocumentProvider : IDocumentProvider, IOpenApiDocumentGenerator
internal sealed class OpenApiDocumentProvider : IDocumentProvider, IOpenApiDocumentGenerator
{
private readonly IServiceProvider _serviceProvider;
private readonly IEnumerable<OpenApiDocumentRegistration> _documents;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace NSwag.AspNetCore
{
internal class OpenApiMvcApplicationModelConvention : IApplicationModelConvention
internal sealed class OpenApiMvcApplicationModelConvention : IApplicationModelConvention
{
public void Apply(ApplicationModel application)
{
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.AspNetCore/SwaggerUiSettingsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ protected string GetCustomScriptHtml(HttpRequest request)
/// <summary>Generates the additional objects JavaScript code.</summary>
/// <param name="additionalSettings">The additional settings.</param>
/// <returns>The code.</returns>
protected string GenerateAdditionalSettings(IDictionary<string, object> additionalSettings)
protected static string GenerateAdditionalSettings(IDictionary<string, object> additionalSettings)
{
var code = "";
foreach (var pair in additionalSettings)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ public void When_the_generation_of_dto_classes_are_disabled_then_file_is_generat
Assert.DoesNotContain("public partial class ComplexTypeResponse", code);
}

private OpenApiDocument GetOpenApiDocument()
private static OpenApiDocument GetOpenApiDocument()
{
JsonSchema complexTypeSchema = new JsonSchema();
complexTypeSchema.Title = "ComplexType";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost
return null;
}

private async Task CreateDocumentAsync(string filePath)
private static async Task CreateDocumentAsync(string filePath)
{
var document = new NSwagDocument();
document.Path = filePath;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
namespace NSwag.Commands.Generation.AspNetCore
{
/// <summary>In-process entry point for the aspnetcore2swagger command.</summary>
internal class AspNetCoreToOpenApiGeneratorCommandEntryPoint
internal sealed class AspNetCoreToOpenApiGeneratorCommandEntryPoint
{
public static void Process(string commandContent, string outputFile, string applicationName)
{
Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.Commands/Commands/OutputCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public abstract class OutputCommandBase : IOutputCommand

public abstract Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host);

protected Task<OpenApiDocument> ReadSwaggerDocumentAsync(string input)
protected static Task<OpenApiDocument> ReadSwaggerDocumentAsync(string input)
{
if (!IsJson(input) && !IsYaml(input))
{
Expand Down Expand Up @@ -67,12 +67,12 @@ protected Task<OpenApiDocument> ReadSwaggerDocumentAsync(string input)
}
}

protected bool IsJson(string data)
protected static bool IsJson(string data)
{
return data.StartsWith("{");
}

protected bool IsYaml(string data)
protected static bool IsYaml(string data)
{
return !IsJson(data) && data.Contains("\n");
}
Expand Down
4 changes: 2 additions & 2 deletions src/NSwag.Commands/HostApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,13 +181,13 @@ void OnEntryPointExit(Exception exception)
#endif
}

private class NoopHostLifetime : IHostLifetime
private sealed class NoopHostLifetime : IHostLifetime
{
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

private class NoopServer : IServer
private sealed class NoopServer : IServer
{
public IFeatureCollection Features { get; } = new FeatureCollection();
public void Dispose() { }
Expand Down
12 changes: 8 additions & 4 deletions src/NSwag.Commands/NSwagDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -230,11 +230,13 @@ private async Task<string> StartCommandLineProcessAsync(string command)

private string GetDocumentDirectory()
{
var absoluteDocumentPath = PathUtilities.MakeAbsolutePath(Path, System.IO.Directory.GetCurrentDirectory());
var absoluteDocumentPath = PathUtilities.MakeAbsolutePath(Path, Directory.GetCurrentDirectory());
return System.IO.Path.GetDirectoryName(absoluteDocumentPath);
}

#pragma warning disable CA1822
private string GetArgumentsPrefix()
#pragma warning restore CA1822
{
#if NET462

Expand All @@ -252,7 +254,9 @@ private string GetArgumentsPrefix()
return "";
}

#pragma warning disable CA1822
private string GetProgramName()
#pragma warning restore CA1822
{
#if NET462

Expand All @@ -270,7 +274,7 @@ private string GetProgramName()
return "dotnet";
}

private string ReadFileIfExists(string filename)
private static string ReadFileIfExists(string filename)
{
if (filename != null && File.Exists(filename))
{
Expand All @@ -280,15 +284,15 @@ private string ReadFileIfExists(string filename)
return null;
}

private void DeleteFileIfExists(string filename)
private static void DeleteFileIfExists(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
}

internal class CommandLineException : Exception
private sealed class CommandLineException : Exception
{
public CommandLineException(string message, string stackTrace)
: base(message)
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Commands/OperationGenerationModeConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace NSwag.Commands
{
internal class OperationGenerationModeConverter
internal sealed class OperationGenerationModeConverter
{
internal static OperationGenerationMode GetOperationGenerationMode(IOperationNameGenerator operationNameGenerator)
{
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core.Tests/Serialization/PathItemTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public async Task PathItem_With_External_Ref_Can_Be_Serialized()
Assert.True(getOperation.ActualResponses.ContainsKey("200"));
}

private string GetTestDirectory()
private static string GetTestDirectory()
{
var codeBase = Assembly.GetExecutingAssembly().CodeBase;
var uri = new UriBuilder(codeBase);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public async Task When_yaml_schema_has_references_it_works(string relativePath)
Assert.Equal(JsonObjectType.Boolean, document.Definitions["ContractObject"].Properties["bar"].ActualTypeSchema.Type);
}

private string GetTestDirectory()
private static string GetTestDirectory()
{
var codeBase = Assembly.GetExecutingAssembly().CodeBase;
var uri = new UriBuilder(codeBase);
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core/OpenApiDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ public void GenerateOperationIds()
}
}

private string GetOperationNameFromPath(OpenApiOperationDescription operation)
private static string GetOperationNameFromPath(OpenApiOperationDescription operation)
{
var pathSegments = operation.Path.Trim('/').Split('/');
var lastPathSegment = pathSegments.LastOrDefault(s => !s.Contains("{"));
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.Core/OpenApiPathItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ IJsonReference IJsonReferenceBase.Reference
#endregion

// Needed to convert dictionary keys to lower case
internal class OpenApiPathItemConverter : JsonConverter
internal sealed class OpenApiPathItemConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,10 @@ private AspNetCoreOperationProcessorContext GetContext(ApiDescription apiDescrip
return context;
}

private class TestModel { }
private sealed class TestModel { }

#pragma warning disable CA1822
private TestModel SomeAction() => null;
#pragma warning restore CA1822
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ private List<Type> GenerateApiGroups(
return usedControllerTypes;
}

private bool IsOperationDeprecated(ApiDescription apiDescription, ActionDescriptor actionDescriptor, MethodInfo methodInfo)
private static bool IsOperationDeprecated(ApiDescription apiDescription, ActionDescriptor actionDescriptor, MethodInfo methodInfo)
{
if (methodInfo?.GetCustomAttribute<ObsoleteAttribute>() != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

namespace NSwag.Generation.AspNetCore.Processors
{
internal class OperationParameterProcessor : IOperationProcessor
internal sealed class OperationParameterProcessor : IOperationProcessor
{
private const string MultipartFormData = "multipart/form-data";

Expand Down Expand Up @@ -247,23 +247,23 @@ private void ApplyOpenApiBodyParameterAttribute(OpenApiOperationDescription oper
}
}

private void EnsureSingleBodyParameter(OpenApiOperationDescription operationDescription)
private static void EnsureSingleBodyParameter(OpenApiOperationDescription operationDescription)
{
if (operationDescription.Operation.ActualParameters.Count(p => p.Kind == OpenApiParameterKind.Body) > 1)
{
throw new InvalidOperationException($"The operation '{operationDescription.Operation.OperationId}' has more than one body parameter.");
}
}

private void UpdateConsumedTypes(OpenApiOperationDescription operationDescription)
private static void UpdateConsumedTypes(OpenApiOperationDescription operationDescription)
{
if (operationDescription.Operation.ActualParameters.Any(p => p.IsBinary || p.ActualSchema.IsBinary))
{
operationDescription.Operation.TryAddConsumes("multipart/form-data");
}
}

private void RemoveUnusedPathParameters(OpenApiOperationDescription operationDescription, string httpPath)
private static void RemoveUnusedPathParameters(OpenApiOperationDescription operationDescription, string httpPath)
{
operationDescription.Path = "/" + Regex.Replace(httpPath, "{(.*?)(:(([^/]*)?))?}", match =>
{
Expand Down Expand Up @@ -324,7 +324,7 @@ private void AddFileParameter(OperationProcessorContext context, ExtendedApiPara
}
}

private JsonSchema CreateOrGetFormDataSchema(OperationProcessorContext context)
private static JsonSchema CreateOrGetFormDataSchema(OperationProcessorContext context)
{
if (context.OperationDescription.Operation.RequestBody == null)
{
Expand Down Expand Up @@ -501,7 +501,7 @@ private OpenApiParameter CreatePrimitiveParameter(
return operationParameter;
}

private class ExtendedApiParameterDescription
private sealed class ExtendedApiParameterDescription
{
private readonly IXmlDocsSettings _xmlDocsSettings;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ protected override string GetVoidResponseStatusCode()
return "200";
}

private bool IsVoidResponse(Type returnType)
private static bool IsVoidResponse(Type returnType)
{
return returnType == null || returnType.FullName == "System.Void";
}
Expand Down
Loading

0 comments on commit 7b2b910

Please sign in to comment.