Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAlex Groat
456 Pointsdef calculate_price why?
Brand new here, so am not sure if there was a lesson here I missed out on, but I thought we were writing cleaner code.
When Ken introduces calculate_price he cuts out the equation (num_tickets * TICKET_PRICE) and then uses that same equation to write more code. Well I went in and just made amount_due = (num_tickets * TICKET_PRICE) + SERVICE_CHARGE without defining calculate_price ever and it ran perfectly.
So why define calcuate_price, why not just create the constant and add it to the equation for amount_due? Is there real world application I am missing here? If the code were much larger is that going to be a necessity?
1 Answer
Peter Vann
36,427 PointsHi Alex!
This logic is based on a coding principle called DRY, which stands for Don't Repeat Yourself.
The idea is: anywhere in your code, if you EVER have to REPEAT an operation, then you should create a function, which is what they used to refer to as a SUBROUTINE.
It is more obvious with more complex repeated code, but even for a simple price calculation, it has advantages.
One primary one could/would be:
Say you had to calculate the total ticket price 30 times in your code, then later you have to add tax or a service charge to all those calculations - you can make the change once in the function and it automatically updates every calculation where the function is called/used (saving you from having to comb your code and update each calculation manually).
It's very much like how TICKET_PRICE is a constant set at 10 and used all over the place in the code.
If the ticket price changes, you just update the constant, and the ticket price changes everywhere it is referenced.
Does that make sense?
I hope that helps.
Stay safe and happy coding!
Alex Groat
456 PointsAlex Groat
456 PointsYes, Peter I think I see now.
If you had used the calculation for (num_tickets * TICKET_PRICE) more than once then by defining calculate_price make it a variable and you save yourself time from adjusting the rest of your equations.
I really appreciate the detailed response. The example really helped.
Thanks Peter