Skip to content

Style: Don't use negative conditions to return early, use positive conditions to execute a subseqent block. #283

Description

@turbocrime

this pattern of using a negative condition to return early and prevent subsequent execution can be excessively verbose and confusing.

example:

private async maybeUpsertAuctionWithNoteCommitment(spendableNoteRecord: SpendableNoteRecord) {
const assetId = spendableNoteRecord.note?.value?.assetId;
if (!assetId) {
return;
}
const metadata = await this.indexedDb.getAssetsMetadata(assetId);
const captureGroups = assetPatterns.auctionNft.capture(metadata?.display ?? '');
if (!captureGroups) {
return;
}
const auctionId = new AuctionId(auctionIdFromBech32(captureGroups.auctionId));
await this.indexedDb.upsertAuction(auctionId, {
noteCommitment: spendableNoteRecord.noteCommitment,
});
}

suggestion:

  private async maybeUpsertAuctionWithNoteCommitment(spendableNoteRecord: SpendableNoteRecord) {
    const assetId = spendableNoteRecord.note?.value?.assetId;
    if (assetId) {
      const metadata = await this.indexedDb.getAssetsMetadata(assetId);
      const captureGroups = assetPatterns.auctionNft.capture(metadata?.display ?? '');
      if (captureGroups) {
        const auctionId = new AuctionId(auctionIdFromBech32(captureGroups.auctionId));
        await this.indexedDb.upsertAuction(auctionId, {
          noteCommitment: spendableNoteRecord.noteCommitment,
        });
      }
    }
  }

this suggestion could still be improved, e.g.

  private async maybeUpsertAuctionWithNoteCommitment({
    note,
    noteCommitment,
  }: SpendableNoteRecord) {
    const assetId = note?.value?.assetId;
    const metadata = assetId && (await this.indexedDb.getAssetsMetadata(assetId));
    const auctionId = metadata && assetPatterns.auctionNft.capture(metadata.display)?.auctionId;
    if (auctionId) {
      await this.indexedDb.upsertAuction(new AuctionId(auctionIdFromBech32(auctionId)), {
        noteCommitment,
      });
    }
  }

there may be linter rules available to discourage the early-void-return pattern.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    refactorImproving existing system with new design

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions