The value of a role’s required attribute is only checked on object creation. This article provides one way of enforcing it when applying the role to an object on the fly.
What is certain about Perl programming is that there's always more to learn, and this article on applying roles in OO Perl is one such example. It's the challenge of ensuring attributes are set in roles applied on the fly.
It’s quite often the case that if people forget to assign a value to an attribute we really want things to die rather than have undef being returned as the value of the attribute.
Here's an example:
and when you run it:It’s quite often the case that if people forget to assign a value to an attribute we really want things to die rather than have undef being returned as the value of the attribute.
Here's an example:
In order to terminate the process so that the script behaves as follows:
all you need to do is make the "name" attribute "required":
This all works fine and dandy until you decide not to apply the role on creation of the object. In this example, it might be that a car can have a brand, or it might be home-made with no brand. At this point you have to remove the role declaration from the class and apply the role to the object:
As you can see from the following output - the "required" modifier isn't applied because that only happens on creation of the object.
No comments:
Post a Comment