What are common pitfalls or gotchas with attributes and builders?

When working with attributes and builders in Perl, there are several common pitfalls and gotchas that developers should be aware of to avoid unexpected behavior or bugs in their code.

Common Pitfalls

  • Attribute Initialization: Failing to properly initialize attributes can lead to undefined values and exceptions.
  • Builder Method Order: The order of builder method calls can affect the final output; make sure to call them in the correct sequence.
  • Immutable Attributes: Forgetting that immutable attributes cannot be changed after object construction can lead to frustration.
  • Using `&&` and `||`: Logical operators might lead to unintended short-circuit behavior, especially in complex conditions.

Example Code

# Sample Perl class with attributes and builders use Moose; # Define a class with attributes package MyClass { use Moose; has 'name' => ( is => 'rw', isa => 'Str', builder => '_build_name', clearer => 'clear_name', lazy => 1, ); sub _build_name { return 'Default Name'; } # Additional methods and logic can be added here } # Usage Example my $object = MyClass->new(); print $object->name; # Outputs: Default Name

Perl attributes builders Moose common pitfalls programming