Structure constructor with an empty body silently discards its arguments

ID

vbnet.correctness.struct_empty_constructor

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Type Design

Language

VB.NET

Description

Reports a Structure whose constructor accepts parameters yet has an empty body, so none of the arguments the caller supplies is stored in a field.

Rationale

A structure’s fields are always zero-initialised, and an empty constructor adds nothing to that. Every argument passed to it is silently discarded: New Point(3, 4) yields the same value as New Point(), with X and Y both 0. Because a structure is a value type there is no Nothing to fail fast on - the caller receives a fully formed value that simply holds defaults, so the mistake does not raise an error where it is made. It surfaces later and somewhere else, as a coordinate at the origin, a zero-length span, a rectangle that measures nothing, or a record that compares equal to every other default-constructed instance. The constructor signature actively hides the bug, because it advertises that the values are being captured.

The following code illustrates the pattern detected by this rule:

Namespace Geometry

    ' FLAGGED: Structure constructor with an empty body silently discards its arguments
    Public Structure Point

        Private _x As Integer
        Private _y As Integer

        Public Sub New(ByVal x As Integer, ByVal y As Integer)
        End Sub

Remediation

Assign every parameter to its field in the constructor body. If the parameters really are not needed, delete the constructor - callers then get the implicit default value, and the removal makes it obvious at each call site that no data was being captured.

' Before: New Point(3, 4) is (0, 0)
Public Sub New(ByVal x As Integer, ByVal y As Integer)
End Sub

' After
Public Sub New(ByVal x As Integer, ByVal y As Integer)
    _x = x
    _y = y
End Sub

Configuration

This detector does not need any configuration.