Skip to content

Commit 484537f

Browse files
authored
style: enforce null-coalescing operator (#11461)
* Enforce null-coalescing operator instead of null check * Fixes
1 parent fa54f32 commit 484537f

22 files changed

Lines changed: 58 additions & 116 deletions

File tree

.editorconfig

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ dotnet_naming_style.pascal_case.required_suffix =
6363
dotnet_naming_style.pascal_case.word_separator =
6464
dotnet_naming_style.pascal_case.capitalization = pascal_case
6565
dotnet_style_operator_placement_when_wrapping = beginning_of_line
66-
dotnet_style_coalesce_expression = true:suggestion
66+
dotnet_style_coalesce_expression = true:error
6767
dotnet_style_null_propagation = true:suggestion
6868
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
6969
dotnet_style_prefer_auto_properties = true:silent

src/Nethermind/Ethereum.Test.Base/TestLoader.cs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,8 @@ public static IEnumerable<TTest> LoadFromFile<TContainer, TTest>(
5656
{
5757
Assembly assembly = typeof(TTest).Assembly;
5858
string[] resourceNames = assembly.GetManifestResourceNames();
59-
string resourceName = resourceNames.SingleOrDefault(r => r.Contains(testFileName));
60-
if (resourceName is null)
61-
{
62-
throw new ArgumentException($"Cannot find test resource: {testFileName}");
63-
}
64-
59+
string resourceName = resourceNames.SingleOrDefault(r => r.Contains(testFileName))
60+
?? throw new ArgumentException($"Cannot find test resource: {testFileName}");
6561
JsonSerializerOptions jsonOptions = new()
6662
{
6763
PropertyNameCaseInsensitive = true,

src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,11 @@ public Snapshot GetOrCreateSnapshot(long number, Hash256 hash)
112112

113113
// If we're at an checkpoint block, make a snapshot if it's known
114114
BlockHeader? previousHeader = header;
115-
header = _blockTree.FindHeader(hash, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
116-
if (header is null)
117-
{
118-
throw new InvalidOperationException($"Unknown ancestor ({hash}) of {previousHeader?.ToString(BlockHeader.Format.Short)}");
119-
}
115+
header = _blockTree.FindHeader(hash, BlockTreeLookupOptions.TotalDifficultyNotNeeded)
116+
?? throw new InvalidOperationException($"Unknown ancestor ({hash}) of {previousHeader?.ToString(BlockHeader.Format.Short)}");
120117

121-
if (header.Hash is null) throw new InvalidOperationException("Block tree block without hash set");
118+
if (header.Hash is null)
119+
throw new InvalidOperationException("Block tree block without hash set");
122120

123121
Hash256 parentHash = header.ParentHash;
124122
if (IsEpochTransition(number))

src/Nethermind/Nethermind.Consensus/Stateless/WitnessCapturingTrieStore.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,9 @@ public TrieNode FindCachedOrUnknown(Hash256? address, in TreePath path, Hash256
3030
return node;
3131
}
3232

33-
public byte[]? LoadRlp(Hash256? address, in TreePath path, Hash256 hash, ReadFlags flags = ReadFlags.None)
34-
{
35-
byte[]? rlp = TryLoadRlp(address, in path, hash, flags);
36-
if (rlp is null) throw new MissingTrieNodeException("Missing RLP node", address, path, hash);
37-
return rlp;
38-
}
33+
public byte[]? LoadRlp(Hash256? address, in TreePath path, Hash256 hash, ReadFlags flags = ReadFlags.None) =>
34+
TryLoadRlp(address, in path, hash, flags)
35+
?? throw new MissingTrieNodeException("Missing RLP node", address, path, hash);
3936

4037
public byte[]? TryLoadRlp(Hash256? address, in TreePath path, Hash256 hash, ReadFlags flags = ReadFlags.None)
4138
{

src/Nethermind/Nethermind.Core/Container/FallbackToFieldFromApi.cs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,8 @@ public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Fun
8080
IRegistrationBuilder<object, SimpleActivatorData, SingleRegistrationStyle> builder = RegistrationBuilder.ForDelegate(serviceType, (ctx, reg) =>
8181
{
8282
TApi baseT = ctx.Resolve<TApi>();
83-
object? value = property.GetValue(baseT);
84-
if (value is null)
85-
{
86-
throw new MissingFieldException($"Property {property.Name} in {baseT.GetType().Name} is null");
87-
}
88-
return value!;
83+
return property.GetValue(baseT)
84+
?? throw new MissingFieldException($"Property {property.Name} in {baseT.GetType().Name} is null");
8985
})
9086
.WithMetadata(FallbackMetadata, true)
9187
.ExternallyOwned();

src/Nethermind/Nethermind.Era1/EraExporter.cs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -115,11 +115,8 @@ async Task WriteEpoch(long epochIdx)
115115
{
116116
for (long y = startingIndex; y < startingIndex + _era1Size && y <= to; y++)
117117
{
118-
Block? block = blockTree.FindBlock(y, BlockTreeLookupOptions.DoNotCreateLevelIfMissing);
119-
if (block is null)
120-
{
121-
throw new EraException($"Could not find a block with number {y}.");
122-
}
118+
Block? block = blockTree.FindBlock(y, BlockTreeLookupOptions.DoNotCreateLevelIfMissing)
119+
?? throw new EraException($"Could not find a block with number {y}.");
123120

124121
TxReceipt[]? receipts = receiptStorage.Get(block, true, false);
125122
if (receipts is null || (block.Header.ReceiptsRoot != Keccak.EmptyTreeHash && receipts.Length == 0))

src/Nethermind/Nethermind.EraE/Export/EraExporter.cs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,8 @@ public Task Export(string destinationPath, long from, long to, CancellationToken
5656
if (from > to)
5757
throw new ArgumentException($"Start block ({from}) must not be after end block ({to}).");
5858

59-
Block? lastBlock = blockTree.FindBlock(to, BlockTreeLookupOptions.DoNotCreateLevelIfMissing);
60-
if (lastBlock is null)
61-
throw new InvalidOperationException(
62-
$"Block {to} is not available. " +
63-
"EraE export requires all block bodies to be present. " +
64-
"Ensure the node is fully synced before exporting.");
59+
_ = blockTree.FindBlock(to, BlockTreeLookupOptions.DoNotCreateLevelIfMissing)
60+
?? throw new InvalidOperationException($"Block {to} is not available. EraE export requires all block bodies to be present. Ensure the node is fully synced before exporting.");
6561

6662
return DoExport(destinationPath, from, to, cancellation);
6763
}
@@ -139,9 +135,8 @@ async Task WriteEpoch(long epochIdx, CancellationToken cancel)
139135
{
140136
for (long blockNumber = writeFrom; blockNumber <= writeTo; blockNumber++)
141137
{
142-
Block? block = blockTree.FindBlock(blockNumber, BlockTreeLookupOptions.DoNotCreateLevelIfMissing);
143-
if (block is null)
144-
throw new EraException($"Could not find block {blockNumber}. The node may not have finished syncing block bodies for this range.");
138+
Block block = blockTree.FindBlock(blockNumber, BlockTreeLookupOptions.DoNotCreateLevelIfMissing)
139+
?? throw new EraException($"Could not find block {blockNumber}. The node may not have finished syncing block bodies for this range.");
145140

146141
// IsPostMerge is not part of the RLP encoding and defaults to false when read from
147142
// the block store. Restore it from Difficulty (EIP-3675: post-merge Difficulty == 0).

src/Nethermind/Nethermind.Init/Steps/InitializeBlockProducer.cs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,8 @@ public Task Execute(CancellationToken _)
3131
return Task.CompletedTask;
3232
}
3333

34-
IConsensusPlugin? consensusPlugin = _api.GetConsensusPlugin();
35-
if (consensusPlugin is null)
36-
{
37-
throw new NotSupportedException($"Mining in {_api.ChainSpec.SealEngineType} mode is not supported");
38-
}
39-
34+
IConsensusPlugin consensusPlugin = _api.GetConsensusPlugin()
35+
?? throw new NotSupportedException($"Mining in {_api.ChainSpec.SealEngineType} mode is not supported");
4036
IBlockProducerFactory blockProducerFactory = consensusPlugin;
4137
IBlockProducerRunnerFactory blockProducerRunnerFactory = consensusPlugin;
4238

src/Nethermind/Nethermind.Serialization.Rlp/Rlp.cs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1379,14 +1379,9 @@ public byte DecodeByte()
13791379

13801380
public T[] DecodeArray<T>(IRlpValueDecoder<T>? decoder = null, bool checkPositions = true, T defaultElement = default, RlpLimit? limit = null)
13811381
{
1382-
if (decoder is null)
1383-
{
1384-
decoder = GetValueDecoder<T>();
1385-
if (decoder is null)
1386-
{
1387-
throw new RlpException($"{nameof(Rlp)} does not support length of {nameof(T)}");
1388-
}
1389-
}
1382+
decoder ??= GetValueDecoder<T>()
1383+
?? throw new RlpException($"{nameof(Rlp)} does not support length of {nameof(T)}");
1384+
13901385
int positionCheck = ReadSequenceLength() + Position;
13911386
int count = PeekNumberOfItemsRemaining(checkPositions ? positionCheck : null);
13921387
GuardLimit(count, limit);

src/Nethermind/Nethermind.State.Flat/FlatStateReader.cs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,8 @@ public void RunTreeVisitor<TCtx>(ITreeVisitor<TCtx> treeVisitor, BlockHeader? ba
5656
{
5757
StateId stateId = new(baseBlock);
5858

59-
using ReadOnlySnapshotBundle? reader = flatDbManager.GatherReadOnlySnapshotBundle(stateId);
60-
if (reader is null)
61-
{
62-
throw new InvalidOperationException($"State at {baseBlock} not found");
63-
}
59+
using ReadOnlySnapshotBundle reader = flatDbManager.GatherReadOnlySnapshotBundle(stateId)
60+
?? throw new InvalidOperationException($"State at {baseBlock} not found");
6461

6562
ReadOnlyStateTrieStoreAdapter trieStoreAdapter = new(reader);
6663

0 commit comments

Comments
 (0)