Skip to content

Commit 72f3630

Browse files
author
Bart Koelman
committed
Use helpers to prevent multiple line breaks in array and list initializers
1 parent 9b544c8 commit 72f3630

File tree

57 files changed

+179
-208
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+179
-208
lines changed

benchmarks/Query/QueryParserBenchmarks.cs

+4-10
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
using System;
2-
using System.Collections.Generic;
32
using System.ComponentModel.Design;
43
using BenchmarkDotNet.Attributes;
4+
using JsonApiDotNetCore;
55
using JsonApiDotNetCore.Configuration;
66
using JsonApiDotNetCore.Middleware;
77
using JsonApiDotNetCore.QueryStrings;
@@ -43,11 +43,8 @@ private static QueryStringReader CreateQueryParameterDiscoveryForSort(IResourceG
4343
JsonApiRequest request, IJsonApiOptions options, FakeRequestQueryStringAccessor queryStringAccessor)
4444
{
4545
var sortReader = new SortQueryStringParameterReader(request, resourceGraph);
46-
47-
var readers = new List<IQueryStringParameterReader>
48-
{
49-
sortReader
50-
};
46+
47+
var readers = sortReader.AsEnumerable();
5148

5249
return new QueryStringReader(options, queryStringAccessor, readers, NullLoggerFactory.Instance);
5350
}
@@ -65,10 +62,7 @@ private static QueryStringReader CreateQueryParameterDiscoveryForAll(IResourceGr
6562
var defaultsReader = new DefaultsQueryStringParameterReader(options);
6663
var nullsReader = new NullsQueryStringParameterReader(options);
6764

68-
var readers = new List<IQueryStringParameterReader>
69-
{
70-
includeReader, filterReader, sortReader, sparseFieldSetReader, paginationReader, defaultsReader, nullsReader
71-
};
65+
var readers = ArrayFactory.Create<IQueryStringParameterReader>(includeReader, filterReader, sortReader, sparseFieldSetReader, paginationReader, defaultsReader, nullsReader);
7266

7367
return new QueryStringReader(options, queryStringAccessor, readers, NullLoggerFactory.Instance);
7468
}

src/Examples/ReportsExample/Services/ReportService.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,12 @@ public Task<IReadOnlyCollection<Report>> GetAsync(CancellationToken cancellation
2121
{
2222
_logger.LogInformation("GetAsync");
2323

24-
IReadOnlyCollection<Report> reports = GetReports().ToList();
24+
var reports = GetReports();
2525

2626
return Task.FromResult(reports);
2727
}
2828

29-
private IEnumerable<Report> GetReports()
29+
private IReadOnlyCollection<Report> GetReports()
3030
{
3131
return new List<Report>
3232
{

src/JsonApiDotNetCore/ArrayFactory.cs

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
namespace JsonApiDotNetCore
2+
{
3+
internal static class ArrayFactory
4+
{
5+
public static T[] Create<T>(params T[] items)
6+
{
7+
return items;
8+
}
9+
}
10+
}

src/JsonApiDotNetCore/Configuration/ServiceCollectionExtensions.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public static IServiceCollection AddJsonApi<TDbContext>(this IServiceCollection
4242
IMvcCoreBuilder mvcBuilder = null)
4343
where TDbContext : DbContext
4444
{
45-
return AddJsonApi(services, options, discovery, resources, mvcBuilder, new[] {typeof(TDbContext)});
45+
return AddJsonApi(services, options, discovery, resources, mvcBuilder, typeof(TDbContext).AsArray());
4646
}
4747

4848
private static void SetupApplicationBuilder(IServiceCollection services, Action<JsonApiOptions> configureOptions,

src/JsonApiDotNetCore/Configuration/ServiceDiscoveryFacade.cs

+4-1
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,10 @@ private void AddResourceDefinitions(Assembly assembly, ResourceDescriptor resour
187187

188188
private void RegisterImplementations(Assembly assembly, Type interfaceType, ResourceDescriptor resourceDescriptor)
189189
{
190-
var genericArguments = interfaceType.GetTypeInfo().GenericTypeParameters.Length == 2 ? new[] { resourceDescriptor.ResourceType, resourceDescriptor.IdType } : new[] { resourceDescriptor.ResourceType };
190+
var genericArguments = interfaceType.GetTypeInfo().GenericTypeParameters.Length == 2
191+
? ArrayFactory.Create(resourceDescriptor.ResourceType, resourceDescriptor.IdType)
192+
: ArrayFactory.Create(resourceDescriptor.ResourceType);
193+
191194
var result = TypeLocator.GetGenericInterfaceImplementation(assembly, interfaceType, genericArguments);
192195
if (result != null)
193196
{

src/JsonApiDotNetCore/Controllers/CoreJsonApiController.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ protected IActionResult Error(Error error)
1313
{
1414
ArgumentGuard.NotNull(error, nameof(error));
1515

16-
return Error(new[] {error});
16+
return Error(error.AsEnumerable());
1717
}
1818

1919
protected IActionResult Error(IEnumerable<Error> errors)

src/JsonApiDotNetCore/Errors/JsonApiException.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public JsonApiException(Error error, Exception innerException = null)
2424
{
2525
ArgumentGuard.NotNull(error, nameof(error));
2626

27-
Errors = new[] {error};
27+
Errors = error.AsArray();
2828
}
2929

3030
public JsonApiException(IEnumerable<Error> errors, Exception innerException = null)

src/JsonApiDotNetCore/Hooks/Internal/Discovery/HooksDiscovery.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ private void DiscoverImplementedHooks(Type containerType)
5656

5757
var implementedHooks = new List<ResourceHook>();
5858
// this hook can only be used with enabled database values
59-
var databaseValuesEnabledHooks = new List<ResourceHook> { ResourceHook.BeforeImplicitUpdateRelationship };
59+
var databaseValuesEnabledHooks = ResourceHook.BeforeImplicitUpdateRelationship.AsList();
6060
var databaseValuesDisabledHooks = new List<ResourceHook>();
6161
foreach (var hook in _allHooks)
6262
{

src/JsonApiDotNetCore/Hooks/Internal/Execution/HookExecutorHelper.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,15 @@ public IResourceHookContainer GetResourceHookContainer(RightType targetResource,
5656

5757
// if there was a container, first check if it implements the hook we
5858
// want to use it for.
59-
List<ResourceHook> targetHooks;
59+
IEnumerable<ResourceHook> targetHooks;
6060
if (hook == ResourceHook.None)
6161
{
6262
CheckForTargetHookExistence();
6363
targetHooks = _targetedHooksForRelatedResources;
6464
}
6565
else
6666
{
67-
targetHooks = new List<ResourceHook> { hook };
67+
targetHooks = hook.AsEnumerable();
6868
}
6969

7070
foreach (ResourceHook targetHook in targetHooks)
@@ -91,7 +91,7 @@ public IEnumerable LoadDbValues(LeftType resourceTypeForRepository, IEnumerable
9191
.MakeGenericMethod(resourceTypeForRepository, idType);
9292
var cast = ((IEnumerable<object>)resources).Cast<IIdentifiable>();
9393
var ids = TypeHelper.CopyToList(cast.Select(i => i.GetTypedId()), idType);
94-
var values = (IEnumerable)parameterizedGetWhere.Invoke(this, new object[] { ids, relationshipsToNextLayer });
94+
var values = (IEnumerable)parameterizedGetWhere.Invoke(this, ArrayFactory.Create<object>(ids, relationshipsToNextLayer));
9595
if (values == null)
9696
{
9797
return null;

src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs

+6-6
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public void BeforeRead<TResource>(ResourcePipeline pipeline, string stringId = n
4343
{
4444
var hookContainer = _executorHelper.GetResourceHookContainer<TResource>(ResourceHook.BeforeRead);
4545
hookContainer?.BeforeRead(pipeline, false, stringId);
46-
var calledContainers = new List<LeftType> { typeof(TResource) };
46+
var calledContainers = typeof(TResource).AsList();
4747

4848
// @formatter:wrap_chained_method_calls chop_always
4949
// @formatter:keep_existing_linebreaks true
@@ -134,7 +134,7 @@ public IEnumerable<TResource> OnReturn<TResource>(IEnumerable<TResource> resourc
134134

135135
Traverse(_traversalHelper.CreateNextLayer(node), ResourceHook.OnReturn, (nextContainer, nextNode) =>
136136
{
137-
var filteredUniqueSet = CallHook(nextContainer, ResourceHook.OnReturn, new object[] { nextNode.UniqueResources, pipeline });
137+
var filteredUniqueSet = CallHook(nextContainer, ResourceHook.OnReturn, ArrayFactory.Create<object>(nextNode.UniqueResources, pipeline));
138138
nextNode.UpdateUnique(filteredUniqueSet);
139139
nextNode.Reassign();
140140
});
@@ -151,7 +151,7 @@ public void AfterRead<TResource>(IEnumerable<TResource> resources, ResourcePipel
151151

152152
Traverse(_traversalHelper.CreateNextLayer(node), ResourceHook.AfterRead, (nextContainer, nextNode) =>
153153
{
154-
CallHook(nextContainer, ResourceHook.AfterRead, new object[] { nextNode.UniqueResources, pipeline, true });
154+
CallHook(nextContainer, ResourceHook.AfterRead, ArrayFactory.Create<object>(nextNode.UniqueResources, pipeline, true));
155155
});
156156
}
157157

@@ -311,7 +311,7 @@ private void FireNestedBeforeUpdateHooks(ResourcePipeline pipeline, NodeLayer la
311311
currentResourcesGroupedInverse = ReplaceKeysWithInverseRelationships(currentResourcesGrouped);
312312

313313
var resourcesByRelationship = CreateRelationshipHelper(resourceType, currentResourcesGroupedInverse, dbValues);
314-
var allowedIds = CallHook(nestedHookContainer, ResourceHook.BeforeUpdateRelationship, new object[] { GetIds(uniqueResources), resourcesByRelationship, pipeline }).Cast<string>();
314+
var allowedIds = CallHook(nestedHookContainer, ResourceHook.BeforeUpdateRelationship, ArrayFactory.Create<object>(GetIds(uniqueResources), resourcesByRelationship, pipeline)).Cast<string>();
315315
var updated = GetAllowedResources(uniqueResources, allowedIds);
316316
node.UpdateUnique(updated);
317317
node.Reassign();
@@ -392,7 +392,7 @@ private void FireForAffectedImplicits(Type resourceTypeToInclude, Dictionary<Rel
392392

393393
var inverse = implicitAffected.ToDictionary(kvp => _resourceGraph.GetInverseRelationship(kvp.Key), kvp => kvp.Value);
394394
var resourcesByRelationship = CreateRelationshipHelper(resourceTypeToInclude, inverse);
395-
CallHook(container, ResourceHook.BeforeImplicitUpdateRelationship, new object[] { resourcesByRelationship, pipeline});
395+
CallHook(container, ResourceHook.BeforeImplicitUpdateRelationship, ArrayFactory.Create<object>(resourcesByRelationship, pipeline));
396396
}
397397

398398
/// <summary>
@@ -512,7 +512,7 @@ private void FireAfterUpdateRelationship(IResourceHookContainer container, IReso
512512
// For the nested hook we need to replace these attributes with their inverse.
513513
// See the FireNestedBeforeUpdateHooks method for a more detailed example.
514514
var resourcesByRelationship = CreateRelationshipHelper(node.ResourceType, ReplaceKeysWithInverseRelationships(currentResourcesGrouped));
515-
CallHook(container, ResourceHook.AfterUpdateRelationship, new object[] { resourcesByRelationship, pipeline });
515+
CallHook(container, ResourceHook.AfterUpdateRelationship, ArrayFactory.Create<object>(resourcesByRelationship, pipeline));
516516
}
517517

518518
/// <summary>

src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutorFacade.cs

+11-16
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public void BeforeReadSingle<TResource, TId>(TId id, ResourcePipeline pipeline)
3737
public void AfterReadSingle<TResource>(TResource resource, ResourcePipeline pipeline)
3838
where TResource : class, IIdentifiable
3939
{
40-
_resourceHookExecutor.AfterRead(ToList(resource), pipeline);
40+
_resourceHookExecutor.AfterRead(resource.AsList(), pipeline);
4141
}
4242

4343
public void BeforeReadMany<TResource>()
@@ -55,37 +55,37 @@ public void AfterReadMany<TResource>(IReadOnlyCollection<TResource> resources)
5555
public void BeforeCreate<TResource>(TResource resource)
5656
where TResource : class, IIdentifiable
5757
{
58-
_resourceHookExecutor.BeforeCreate(ToList(resource), ResourcePipeline.Post);
58+
_resourceHookExecutor.BeforeCreate(resource.AsList(), ResourcePipeline.Post);
5959
}
6060

6161
public void AfterCreate<TResource>(TResource resource)
6262
where TResource : class, IIdentifiable
6363
{
64-
_resourceHookExecutor.AfterCreate(ToList(resource), ResourcePipeline.Post);
64+
_resourceHookExecutor.AfterCreate(resource.AsList(), ResourcePipeline.Post);
6565
}
6666

6767
public void BeforeUpdateResource<TResource>(TResource resource)
6868
where TResource : class, IIdentifiable
6969
{
70-
_resourceHookExecutor.BeforeUpdate(ToList(resource), ResourcePipeline.Patch);
70+
_resourceHookExecutor.BeforeUpdate(resource.AsList(), ResourcePipeline.Patch);
7171
}
7272

7373
public void AfterUpdateResource<TResource>(TResource resource)
7474
where TResource : class, IIdentifiable
7575
{
76-
_resourceHookExecutor.AfterUpdate(ToList(resource), ResourcePipeline.Patch);
76+
_resourceHookExecutor.AfterUpdate(resource.AsList(), ResourcePipeline.Patch);
7777
}
7878

7979
public void BeforeUpdateRelationship<TResource>(TResource resource)
8080
where TResource : class, IIdentifiable
8181
{
82-
_resourceHookExecutor.BeforeUpdate(ToList(resource), ResourcePipeline.PatchRelationship);
82+
_resourceHookExecutor.BeforeUpdate(resource.AsList(), ResourcePipeline.PatchRelationship);
8383
}
8484

8585
public void AfterUpdateRelationship<TResource>(TResource resource)
8686
where TResource : class, IIdentifiable
8787
{
88-
_resourceHookExecutor.AfterUpdate(ToList(resource), ResourcePipeline.PatchRelationship);
88+
_resourceHookExecutor.AfterUpdate(resource.AsList(), ResourcePipeline.PatchRelationship);
8989
}
9090

9191
public void BeforeDelete<TResource, TId>(TId id)
@@ -94,7 +94,7 @@ public void BeforeDelete<TResource, TId>(TId id)
9494
var temporaryResource = _resourceFactory.CreateInstance<TResource>();
9595
temporaryResource.Id = id;
9696

97-
_resourceHookExecutor.BeforeDelete(ToList(temporaryResource), ResourcePipeline.Delete);
97+
_resourceHookExecutor.BeforeDelete(temporaryResource.AsList(), ResourcePipeline.Delete);
9898
}
9999

100100
public void AfterDelete<TResource, TId>(TId id)
@@ -103,13 +103,13 @@ public void AfterDelete<TResource, TId>(TId id)
103103
var temporaryResource = _resourceFactory.CreateInstance<TResource>();
104104
temporaryResource.Id = id;
105105

106-
_resourceHookExecutor.AfterDelete(ToList(temporaryResource), ResourcePipeline.Delete, true);
106+
_resourceHookExecutor.AfterDelete(temporaryResource.AsList(), ResourcePipeline.Delete, true);
107107
}
108108

109109
public void OnReturnSingle<TResource>(TResource resource, ResourcePipeline pipeline)
110110
where TResource : class, IIdentifiable
111111
{
112-
_resourceHookExecutor.OnReturn(ToList(resource), pipeline);
112+
_resourceHookExecutor.OnReturn(resource.AsList(), pipeline);
113113
}
114114

115115
public IReadOnlyCollection<TResource> OnReturnMany<TResource>(IReadOnlyCollection<TResource> resources)
@@ -128,16 +128,11 @@ public object OnReturnRelationship(object resourceOrResources)
128128

129129
if (resourceOrResources is IIdentifiable)
130130
{
131-
var resources = ToList((dynamic)resourceOrResources);
131+
var resources = ObjectExtensions.AsList((dynamic)resourceOrResources);
132132
return Enumerable.SingleOrDefault(_resourceHookExecutor.OnReturn(resources, ResourcePipeline.GetRelationship));
133133
}
134134

135135
return resourceOrResources;
136136
}
137-
138-
private static List<TResource> ToList<TResource>(TResource resource)
139-
{
140-
return new List<TResource> {resource};
141-
}
142137
}
143138
}

src/JsonApiDotNetCore/Hooks/Internal/Traversal/TraversalHelper.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public RootNode<TResource> CreateRootNode<TResource>(IEnumerable<TResource> root
6767
/// <param name="rootNode">Root node.</param>
6868
public NodeLayer CreateNextLayer(IResourceNode rootNode)
6969
{
70-
return CreateNextLayer(new[] { rootNode });
70+
return CreateNextLayer(rootNode.AsEnumerable());
7171
}
7272

7373
/// <summary>
@@ -159,7 +159,7 @@ private Dictionary<RightType, List<KeyValuePair<RelationshipProxy, List<IIdentif
159159
if (proxy.IsContextRelation || uniqueRightResources.Any())
160160
{
161161
AddToRelationshipGroup(rightResourcesGrouped, proxy, uniqueRightResources);
162-
AddToRelationshipGroup(leftResourcesGrouped, proxy, new[] { leftResource });
162+
AddToRelationshipGroup(leftResourcesGrouped, proxy, leftResource.AsEnumerable());
163163
}
164164
}
165165
}
@@ -170,7 +170,7 @@ private Dictionary<RightType, List<KeyValuePair<RelationshipProxy, List<IIdentif
170170
{
171171
var type = kvp.Key.RightType;
172172
var list = TypeHelper.CopyToList(kvp.Value, type);
173-
processResourcesMethod.MakeGenericMethod(type).Invoke(this, new object[] { list });
173+
processResourcesMethod.MakeGenericMethod(type).Invoke(this, ArrayFactory.Create<object>(list));
174174
}
175175

176176
return (leftResourcesGrouped, rightResourcesGrouped);

src/JsonApiDotNetCore/Middleware/ExceptionHandler.cs

+4-10
Original file line numberDiff line numberDiff line change
@@ -73,21 +73,15 @@ protected virtual ErrorDocument CreateErrorDocument(Exception exception)
7373
var errors = exception is JsonApiException jsonApiException
7474
? jsonApiException.Errors
7575
: exception is OperationCanceledException
76-
? new[]
77-
{
78-
new Error((HttpStatusCode) 499)
76+
? new Error((HttpStatusCode) 499)
7977
{
8078
Title = "Request execution was canceled."
81-
}
82-
}
83-
: new[]
84-
{
85-
new Error(HttpStatusCode.InternalServerError)
79+
}.AsArray()
80+
: new Error(HttpStatusCode.InternalServerError)
8681
{
8782
Title = "An unhandled error occurred while processing this request.",
8883
Detail = exception.Message
89-
}
90-
};
84+
}.AsArray();
9185

9286
foreach (var error in errors)
9387
{
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System.Collections.Generic;
2+
3+
namespace JsonApiDotNetCore
4+
{
5+
internal static class ObjectExtensions
6+
{
7+
public static IEnumerable<T> AsEnumerable<T>(this T element)
8+
{
9+
yield return element;
10+
}
11+
12+
public static T[] AsArray<T>(this T element)
13+
{
14+
return new[] {element};
15+
}
16+
17+
public static List<T> AsList<T>(this T element)
18+
{
19+
return new List<T> {element};
20+
}
21+
}
22+
}

src/JsonApiDotNetCore/Queries/Expressions/ResourceFieldChainExpression.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public ResourceFieldChainExpression(ResourceFieldAttribute field)
1616
{
1717
ArgumentGuard.NotNull(field, nameof(field));
1818

19-
Fields = new[] {field};
19+
Fields = field.AsArray();
2020
}
2121

2222
public ResourceFieldChainExpression(IReadOnlyCollection<ResourceFieldAttribute> fields)

src/JsonApiDotNetCore/Queries/Internal/Parsing/IncludeParser.cs

+1-4
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,7 @@ protected IncludeExpression ParseInclude(int? maximumDepth)
3939
ResourceFieldChainExpression firstChain =
4040
ParseFieldChain(FieldChainRequirements.IsRelationship, "Relationship name expected.");
4141

42-
var chains = new List<ResourceFieldChainExpression>
43-
{
44-
firstChain
45-
};
42+
var chains = firstChain.AsList();
4643

4744
while (TokenStack.Any())
4845
{

src/JsonApiDotNetCore/Queries/Internal/Parsing/SortParser.cs

+1-4
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,7 @@ protected SortExpression ParseSort()
3838
{
3939
SortElementExpression firstElement = ParseSortElement();
4040

41-
var elements = new List<SortElementExpression>
42-
{
43-
firstElement
44-
};
41+
var elements = firstElement.AsList();
4542

4643
while (TokenStack.Any())
4744
{

0 commit comments

Comments
 (0)