Code standards

From decentraland/unity-explorer · View interactive version

Code standards is an AI agent skill from the GitHub repository decentraland/unity-explorer. C# naming conventions, member ordering, formatting rules, nullable reference types, memory/GC rules, test patterns, and PR standards. Use when writing, reviewing, or modifying non-trivial C# changes in this Unity project — applies to ECS systems, controllers, tests, utilities, and plugins.

How to use this skill

Skill file

Code Standards & Conventions

Sources


Naming Conventions

| Scope | Style | Example |

|-------|-------|---------|

| Namespaces, classes, structs, interfaces, enums, public methods/properties/fields | PascalCase | BillboardSystem, Update() |

| Non-public fields/properties, parameters, locals | camelCase | exposedCameraData, cameraPosition |

| Constants, static readonly | ALL_UPPER_SNAKE_CASE | MINIMUM_DISTANCE_TO_ROTATE_SQR |

| Interfaces | I prefix | IExposedCameraData |

| Async methods | Async suffix | InitializeAsync, LoginAsync |

| Events | Past tense, no On prefix | ViewShowingComplete |

| Unused parameters | _, __, ___ | Update(float _) |

Exception: serialized JSON DTO fields keep their wire-format casing — see Serialized JSON DTOs below.

Names state what the code knows or decides, never what it assumes happens elsewhere. A flag, field or parameter is named for the fact it holds or the behaviour it switches, not for an outcome some other layer may or may not produce. DeployCmd.CreatesProfile overstated what the client can know (it cannot tell whether a deploy creates the profile; it only knows the last fetch found none) and became WasLastProfileMissing; once the condition grew beyond "missing", it was renamed after the behaviour it controls, FillEmptyEmoteWheel. When the meaning of a value changes, rename it with its doc comment and the tests that mention it.

Namespaces are domain names, not folder paths — never suppress a folder-namespace mismatch with // ReSharper disable once CheckNamespace; fix the namespace or leave the warning visible. Full rule: docs/code-style-guidelines.md § Namespaces.

Member Ordering

Within a class, group members in this order:

  1. Enums / delegates
  2. Fields
  3. Properties
  4. Events
  5. Methods
  6. Nested classes

Within each group, order by visibility: public → internal → protected internal → protected → private.

Field ordering within visibility:

  1. const / static readonly
  2. static
  3. readonly
  4. Regular public fields
  5. [SerializeField] fields
  6. Non-public fields

Method ordering:

  1. Constructor / setup
  2. Destructor / Dispose
  3. Public APIs
  4. Unity callbacks
  5. Internal methods
  6. Protected methods
  7. Private helpers (placed after the methods that call them)

Code Example — Member Ordering

From BillboardSystem.cs:

public partial class BillboardSystem : BaseUnityLoopSystem
{
    // 1. Constants first
    private const float MINIMUM_DISTANCE_TO_ROTATE_SQR = 0.25f * 0.25f;

    // 2. Readonly fields
    private readonly IExposedCameraData exposedCameraData;

    // 3. Constructor (internal visibility — see CLAUDE.md §1)
    internal BillboardSystem(World world, IExposedCameraData exposedCameraData) : base(world)
    {
        this.exposedCameraData = exposedCameraData;
    }

    // 4. Override method (Update is the system's main entry point)
    protected override void Update(float t)
    {
        // ...
        UpdateRotationQuery(World, cameraPosition, cameraRotationAxisZ);
    }

    // 5. Private helper — placed after the method that calls it
    [Query]
    private void UpdateRotation(
        [Data] in Vector3 cameraPosition,
        [Data] in Quaternion cameraRotationAxisZ,
        ref TransformComponent transform,
        in PBBillboard billboard)
    {
        // ...
    }
}

Formatting

Memory & GC Rules

Nullable Reference Types

The project is migrating to nullable reference types. ~80 of ~153 assemblies already enable it at the project level; the rest default to disabled.

Rules for New and Modified Files

Annotation Rules

Serialized JSON DTOs (wire-format exceptions)

Deserialized DTO fields follow the wire format, not local conventions:

These exceptions apply only to deserialized DTO fields — never to locals, return types, or non-DTO code. Authoritative rules, edge cases (strengthened contracts, fields absent from the schema), and the reference example: CODE0 § Serialized JSON DTOs.

Comments

Test Conventions

Code Example — AAA Test Pattern

From AvatarLoaderSystemShould.cs:

public class AvatarLoaderSystemShould : UnitySystemTestBase<AvatarLoaderSystem>
{
    [SetUp]
    public void Setup()
    {
        // Setup shared test state
        pbAvatarShape = new PBAvatarShape { BodyShape = BODY_SHAPE_MALE, Name = FAKE_NAME };
        IRealmData realmData = Substitute.For<IRealmData>();
        system = new AvatarLoaderSystem(world);
    }

    [Test]
    public void StartAvatarLoad()
    {
        //Arrange
        Entity entity = world.Create(pbAvatarShape, PartitionComponent.TOP_PRIORITY);

        //Act
        system.Update(0);

        //Assert
        AvatarShapeComponent avatarShapeComponent = world.Get<AvatarShapeComponent>(entity);
        Assert.AreEqual(avatarShapeComponent.BodyShape.Value, BODY_SHAPE_MALE);
        Assert.AreEqual(avatarShapeComponent.Name, FAKE_NAME);
    }

    [Test]
    public void UpdateAvatarLoad()
    {
        //Arrange
        Entity entity = world.Create(pbAvatarShape, PartitionComponent.TOP_PRIORITY);
        system.Update(0);

        //Act
        pbAvatarShape.BodyShape = BODY_SHAPE_FEMALE;
        pbAvatarShape.IsDirty = true;
        system.Update(0);

        //Assert
        ref AvatarShapeComponent avatarShapeComponent = ref world.Get<AvatarShapeComponent>(entity);
        Assert.AreEqual(avatarShapeComponent.BodyShape.Value, BODY_SHAPE_FEMALE);
    }
}

Anti-Patterns (common in AI-authored code)

Reviewers have flagged these patterns as AI-generated code smells. The underlying rule is: don't add structure until it pays for itself. Splits, interfaces, and indirections must buy polymorphism, reuse, or test isolation — not exist "for SRP" alone.

1. Bridge / wrapper classes on the same abstraction layer

If class B exists only to forward calls to class A, with one caller, no polymorphism, and no test seam, delete B and call A directly.

// WRONG — RemoteReactionReceiver is a bridge that only exists to hand
// results to SituationalRemoteTarget via a delegate.
public class RemoteReactionReceiver
{
    private readonly Action<ReceivedReaction> onReceived;
    public RemoteReactionReceiver(Action<ReceivedReaction> onReceived)
        => this.onReceived = onReceived;

    public void Tick(float dt) { /* ... */ onReceived(reaction); }
}

// RIGHT — return the value, let the parent process it.
public class RemoteReactionReceiver
{
    public void Tick(float dt, List<ReceivedReaction> reusableBuffer) { /* ... */ }
}

2. Delegate-wrapped properties

Don't wrap every property of a config in its own Func<T>. Pass the object.

// WRONG
new SituationalRemoteTarget(
    getMaxDistance: () => reactionsConfig.MaxDistance,
    getSpawnRadius: () => reactionsConfig.SpawnRadius,
    getLifetime:    () => reactionsConfig.Lifetime);

// RIGHT
new SituationalRemoteTarget(reactionsConfig);

If you only need to capture one changing value (e.g. messageId), store it as a field on the consumer, not as a closure threaded through constructors.

3. Interfaces with one implementation and no test coverage

Delete the interface. The concrete class is the contract.

4. Defensive null-checks against non-null annotations

// WRONG — field is declared as MessageReactionsView (non-null)
private MessageReactionsView reactionsView;

public void Refresh()
{
    if (reactionsView == null) return;   // can never fire
    reactionsView.UpdateCount(5);
}

If the declared type is T (not T?), don't null-check it. Every redundant check misleads the reader about what can actually happen at runtime.

If a value can be null, change the type to T?. If it can't, delete the guard.

5. Debug/mock code inside production paths

// WRONG — runs on every reaction update in retail builds
int displayCount = messageConfig.DebugRandomizeReactionCounts
    ? Random.Range(1, 100)
    : count;

// RIGHT — editor-only, zero cost in production
int displayCount = count;
#if UNITY_EDITOR
    if (messageConfig.DebugRandomizeReactionCounts)
        displayCount = Random.Range(1, 100);
#endif

Runtime bool flags do not count as "debug-only" — the branch still compiles and executes. Use #if UNITY_EDITOR, or extract debug logic to an editor-only companion system that doesn't run in player builds.

6. Retry loops without a termination condition

A loop that re-queues unresolved items will spin forever when the upstream source consistently returns nothing. Always have a "give up" predicate — max attempts, a known-bad sentinel, or a timeout.

The same goes for scans over a collection: termination must be evident from the loop header, not something the reader has to prove. Put the bound in a for header and leave the search predicate to a break, rather than a while whose condition mixes the bound with the predicate and an increment buried in the body.

// WRONG — terminates, but the reader has to check that every path increments i
var i = 0;
while (i < freeRegions.Count && freeRegions[i].StartIndex < slice.StartIndex)
    i++;

// RIGHT — bounded by construction
int i;
for (i = 0; i < freeRegions.Count; i++)
    if (freeRegions[i].StartIndex >= slice.StartIndex)
        break;

7. Extracting when you should merge

If X does nothing useful without Y, and there is no second consumer of X, merge them. Splits must pay for themselves in polymorphism, reuse, or test isolation.

8. Accessing `Option<T>.Value` without checking `Has`

Option<T>.Value (Utility/Types/Result.cs) is default — null for reference types — when Has is false. A blind read silently propagates an invalid value far from its source.

// WRONG — Value is default/null when Has is false
UserId userId = UserId.New(raw).Value;

// WRONG in production — Unwrap() hides the absence case instead of modeling it
UserId userId = UserId.New(raw).Unwrap();

// RIGHT — branch on Has when the input may be invalid
Option<UserId> userId = UserId.New(raw);
if (!userId.Has) return;
Use(userId.Value);

// RIGHT — a factory that is valid by construction needs no Option at all
UserId userId = UserId.NewRandom();

// RIGHT in tests only — Unwrap() for known-valid constants; it throws loudly at the source
UserId userId = UserId.New(KNOWN_CONSTANT).Unwrap();

In production code, handle None explicitly (early return, propagation) or use a by-construction-valid factory. Unwrap() is a test-only affordance — and in tests, known-valid constants go through Unwrap(), never bare .Value.

9. Committing one-shot development tooling

Code written to help build a feature is not part of the feature. This covers editor [MenuItem] scaffolders that generate a greybox prefab, API probes and spike scripts (Assets/DCL/Playgrounds/...), throwaway editor assemblies (*.Editor.asmdef + csc.rsp) created only to host such a tool, temporary DecentralandUrlsSource localhost pointers, and hand-rolled test harnesses that are not NUnit tests. Once the generated asset or the answer exists, the tool has no consumer and it ships nothing.

// WRONG: a one-shot generator committed next to the feature it bootstrapped
[MenuItem("Decentraland/UI/Scaffold BugReportView Prefab")]
private static void Scaffold() { /* builds a greybox and saves the prefab */ }

Rules:

PR Standards

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.