Variable assigned to itself

ID

apex.correctness.variables_self_assigned

Severity

high

Remediation Complexity

trivial

Remediation Risk

medium

Remediation Effort

low

Resource

Dead Code

Language

Apex

Description

Reports an assignment whose right-hand side is the same variable or field as its left-hand side.

Rationale

The statement has no effect, so it is always a mistake about which name was meant. In Apex the common form is inside a constructor or a setter - name = name; where this.name = name; was intended - and the consequence is a field that stays null while the code reads as if it were initialized. The failure then appears somewhere else entirely, as a null dereference on an object that looked correctly built.

The following code illustrates the pattern detected by this rule:

public class SelfAssign {
    private String name;
    private Integer count;

    public SelfAssign(String name) {
        // FLAGGED: Variable assigned to itself
        name = name;
    }

    public void update(Integer count) {
        // FLAGGED: Variable assigned to itself
        this.count = this.count;
        System.debug(count);
    }

    public void ok(String name, Integer count) {
        this.name = name;
        this.count = count + 1;
    }

    public Account build() {
        Account a = new Account(Name = 'Acme');
        Opportunity o = new Opportunity(Name = 'Deal', StageName = 'Prospecting');
        System.debug(a.Name + o.Name);
        return new Account(Name = 'Acme', BillingCity = 'Madrid');
    }
}

Remediation

Qualify the field with this. if the intent was to assign a parameter to a field, or correct the name on whichever side is wrong. If the statement really is redundant, delete it.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved