Skip to content

[maintainability] CircuitBuilder::$hasMeasurement duplicates information already derivable from $gates #56

Description

@corgab

Summary

CircuitBuilder maintains a separate private bool $hasMeasurement = false; flag, set to true inside push() whenever a measurement gate is added (line 643). Elsewhere in the same class, gateCount() and depth() independently derive equivalent information by scanning $this->gates and filtering on $gate->isMeasurement() (lines 465-468 and 483-486). The flag and the scan are two ways of tracking the same underlying fact — whether any element of $gates is a measurement gate — kept in sync only by push() remembering to set it.

Where

  • src/Circuit/CircuitBuilder.php:41 ($hasMeasurement declaration)
  • src/Circuit/CircuitBuilder.php:622 (validate() — the sole read site: if (! $this->hasMeasurement))
  • src/Circuit/CircuitBuilder.php:636-647 (push() — the sole write site, line 643)
  • src/Circuit/CircuitBuilder.php:463-469 (gateCount() — independently filters $gates by isMeasurement())

Refactor proposal

Remove the $hasMeasurement field and its assignment in push(); have validate() instead check directly, e.g. array_any($this->gates, fn (Gate $g): bool => $g->isMeasurement()) (or ! empty(array_filter(...)) for the current PHP baseline), matching the pattern gateCount()/depth() already use. This is O(n) instead of O(1), but $gates arrays here are circuit-sized (tens of gates at most), so the cost is immaterial next to removing a hand-maintained invariant.

Severity: low

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

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions