Skip to content

Code style

Atulin edited this page Sep 10, 2021 · 1 revision

Code style guide

This page talks about preferred code style, reasons behind the particular choices, and sometimes a bit about the philosophy behind it all.

Prefer pattern matching

Equality operators can be overridden, operator is cannot

Good code

if (user is null)
{
  return NotFound();
}
if (user is { } u)
{
  return Ok(u.Name);
}

Bad code

if (user == null)
{
  return NotFound();
}

Prefer early returns

Fail Fast to reduce nesting, cognitive load, and sometimes even performance

Good code

if (thing is null) return NotFound();
thing.Name = newName;
await _context.SaveChangesAsync();
return Ok(thing);

Bad code

if (thing is not null)
{
  thing.Name = newName;
  await _context.SaveChangesAsync();
  return Ok(thing);
}
else
{
  return NotFound();
}
Clone this wiki locally