Answer the question
In order to leave comments, you need to log in
How to use OOP correctly?
Hello. I recently sat down to learn Perl, but that's not the point. I'm self-taught in programming, and I have a problem, I don't really understand how to use OOP correctly.
Here is an example, there is a pricer.pm module that has a set of methods for calculating any price values for an item.
For example, the calc_total() function.
The question torments me is how to use this module correctly.
By creating a new object that is like this $obj = pricer->new( $item_id );
$obj->calc_total();<br/>
or $obj = pricer->new( );
$obj->calc_total( item_id => $item_id )
I ask you not to kick much, but to help a novice programmer.
In theory, the first option is correct, but the second is also not so bad?
Thanks in advance.
Answer the question
In order to leave comments, you need to log in
I don't write in Perl, more in Java, but I'll give you a hint.
If you use only one item_id, then both options are valid, but the first one is definitely more elegant.
If you have a lot of item_id, then the second option is preferable if you need to calculate the sum of the results for the item_id set. In order not to produce a lot of pricer objects.
If I'm not mistaken in my assumptions about your task.
If your pricer module is tied to item_id, or if half of its methods require this id, then the first option is fine. If the ID requires only the calc_total method, then it is better to use the second option.
Depends on the essence you want to invest.
For example, if this object is a "model" and gives access to operations in the database with all sorts of items, then the second option is out. And if an object can work with only one item, then it is logical to initialize it with it (the first option).
Perl has a rule/expression - There Is More Than One Way To Do It!
Your example demonstrates this well :-)
My opinion: Correct and so and so!
Judging by the fact that you care about such a question, your module is relatively small, and both options are acceptable for it. When/if your pricer.pm gets big enough that there is a need for OOP, the right option will become obvious to you.
In general, it would be better to do this:
$item->calc_total_price();
my $item = shift;
return $pricer->calc_total( item_id => $item->{id});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question