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 trialGrigorij Schleifer
10,365 PointsConfused about Refactoring challenge
Why does this code works fine
public void addItem(Product item){
addItem(item, 1);
}
and this code not
public void addItem(Product item){
addItem(1, item);
}
3 Answers
Dan Johnson
40,533 PointsSince the two argument version of addItem has the following signature:
public void addItem(Product item, int quantity)
The arguments you pass in must follow the same order; a Product
first and an int
second.
If there was a subclass of Product
however, you could pass it in the Product
slot, as any subclass will have all the methods of its parent and can act as if it was just a Product
.
Andrew Shook
31,709 PointsI haven't taken this challenge, but my guess is that the problem lies in how you are passing arguments into add item. Most programming languages don't only you to change the order of declared arguments, because the arguments are assigned to a variable specific to that function. Here is a pseudo code example of an exponent function:
function toThePowerOf( base, exponent)
{
result = 1;
for( i = 1; i == exponent; i++){
result = result * base;
}
return result;
}
The above function calculates the value of an exponent, like 2^3 = 8 and returns the value. Notice how inside the function the first value passed in is given the local variable of base, and the second value passed in is given the local variable of exponent. This means the changing the order of the numbers you pass into the function will change its output. For example toThePowerOf(2, 3) will return 8, while toThePowerOf(3, 2) will return you 9.
So my guess is that addItem() requires the item first and an integer value second, and that is why the first example you have above failed to pass.
Alex Goretoy
19,563 PointsBecause you are reversing the order of the parameter and their types. If you wanted to make this work with this order then you can specify names for the parameters, making them named parameters and it will work.