# Thread: Formulas in methods or constructors?

1. Member Join Date
Nov 2010
Posts
9
Rep Power
0

## Formulas in methods or constructors?

Hi all. I've just started learning how to program and I have some very basic questions that I would be grateful if anyone could answer for me.

So, in my Java textbook there is a problem that asks me to implement a class that accepts the diameter and height of a cylinder in its constructor and has two methods that find volume and surface area, respectively. The class was actually very easy to implement but I checked the website for my textbook that has solutions to selected exercises and their answer was slightly different than mine.

Namely, they had used volume and surface area as their instance variables whereas I had used radius and height. Also, I had defined volume and surface area within my methods that returned volume and surface area where they had defined volume and area within the constructor. i.e. their getSurfaceArea method simply returned surface area.

My questions are, was the book's program more efficient or sound than mine? What exactly does it matter what you define as an instance variable and is it better to create formulas (in this case mathematical formulas) in a constructor?  Reply With Quote

2. Senior Member Join Date
Feb 2010
Location
Waterford, Ireland
Posts
748
Rep Power
11

##   Reply With Quote

3. Member Join Date
Nov 2010
Posts
9
Rep Power
0

## My code:

public class SodaCan
{
public SodaCan(double h, double d)
{
height = h;
}
public double getVolume()
{
return volume;
}
public double getSurfaceArea()
{
double surfaceA = (2 * PI * radius * radius) + (2 * PI * radius * height);
return surfaceA;
}
final double PI = Math.PI;
private double height;
}

Book's code:

public class SodaCan
{
{
double height = aHeight;
double radius = diameter / 2;
volume = Math.PI * Math.pow(radius, 2) * height;
surfaceArea = 2 * Math.PI * radius * height;
}

public double getVolume()
{
return volume;
}

public double getSurfaceArea()
{
return surfaceArea;
}

double volume;
double surfaceArea;
}  Reply With Quote

4. Senior Member Join Date
Feb 2010
Location
Waterford, Ireland
Posts
748
Rep Power
11

## Does your program do what you want it to do? or does it do what the textbook says to do? more importantly have you learned either way about classes, I do not care either way long as you know how classes work...Most important thing is you learned how classes work (assuming this is your chapter).  Reply With Quote

5. Senior Member Join Date
Feb 2010
Location
Waterford, Ireland
Posts
748
Rep Power
11

## back to your final question In my opinion the efficiencty is neglible, but you might get better answers. Better to code the way you feel and know what is going on than code blind from a book so I would say keep doing it your own way. you will learn more. hope this is helpful.  Reply With Quote

6. Member Join Date
Nov 2010
Posts
9
Rep Power
0

## OK, thank you for your help.  Reply With Quote

7. Senior Member Join Date
Feb 2010
Location
Waterford, Ireland
Posts
748
Rep Power
11

## Efficiency should always be the last thing on your mind, make the thing work first, then you can review, that is my own personal opinion and I doubt anybody here will disagree.  Reply With Quote

8. Moderator   Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

## was the book's program more efficient or sound than mine?

Both programs are sound in the sense that they will both give correct output in any test of the getXXX() methods.

It's not really possible to answer the question about efficiency since that depends on the context within which the class is used. If a program created zillions of soda cans but very rarely wanted to know about their surface area, it would seem a waste of time to calculate that value in the constructor. But if a program were making a great many lists of cans and wanted them sorted by volume then it would be sensible perhaps to do the calculation once and for all when the can was constructed.

Since, in the case you are considering, there is no context (it's just a textbook question) then there is no answer. For what it's worth I would have written the class the way you did.

I'll risk al_Marshy_1981's (and others') disapproval by disagreeing, well, just a little bit. It's good to note a difference of approach. And it's good to wonder why. If you agree with my observation that it matters how often the getters will be called then, facing this situation in the future, you would choose from the possible approaches that which is most appropriate.

Even then efficiency wouldn't be the first thing on your mind: soundness would be. Followed by less easily definable things like "simplicity", "clarity", "elegance" etc. My disagreement is limited to thinking that it needn't be the last thing on your mind either.

(Writing this, it occurs to me that our minds don't really work like that: from first to last. Sometimes ideas just hang about in the background rather than standing regimented in line. Efficiency might be like that: never driving the process but always lurking as a question and suggesting possibilities.)

If volume and surface area were really expensive to calculate (which they aren't) "efficiency" might raise its head from the programming book it's reading to suggest something like:

Java Code:
```public class SodaCan
{
private double volume = -1;
private double surfaceArea = -1;
private double height;

public SodaCan(double height, double diameter)
{
this.height = height;
}

public double getVolume()
{
if(volume < 0)
{
}
return volume;
}

public double getSurfaceArea()
{
if(surfaceArea < 0)
{
surfaceArea = 2 * Math.PI * radius * height;
}
return surfaceArea;
}
}```  Reply With Quote

9. Member Join Date
Nov 2010
Posts
9
Rep Power
0

## Thank you for your reply! I guess I asked the question about efficiency because the textbook mentioned it a few times but I'm just trying to get as in-depth an amount of knowledge about Java, and I guess programming in general, that I possibly can. If I just get a program to run, that's not as valuable to me as knowing why it successfully ran. Along those lines...

I did another exercise in the book which was more difficult for me than the soda can one and I think my question here will have a more straightforward answer.

The problem from the book:

Implement a class Balloon that models a spherical balloon that is being filled with air. The
constructor constructs an empty balloon. Supply these methods:
· double getVolume() gets the current volume
· double getSurfaceArea() gets the current surface area

public class Balloon
{
public Balloon()
{
volume = 0;
}
{
volume += amount;
radius = Math.sqrt(volume / (4 * PI));
}
public double getVolume()
{
return volume;
}
public double getSurfaceArea()
{
return surfaceA;
}
{
}
final double PI = Math.PI;
private double volume;
}
Tester class:

public class BalloonTester
{
public static void main(String[] args)
{
Balloon balloon = new Balloon();

System.out.println(balloon.getSurfaceArea());
}
}

This code seems to work well, but when I started out I tried to put my radius = Math.sqrt(volume / (4 * PI)) expression in the constructor. Then I tried to put it in the getRadius method. In both cases the program returned 0.0 for getSurfaceArea. Ultimately it only worked when I put the expression in the addAir method, as it is now. I can only hypothesize that the reason has to do with the explicit parameters of the constructors and methods. In SodaCan I could write out formulas in the constructor and they would be carried over to all of the methods. Since my Balloon constructor has no explicit parameters, it kept reading volume as 0.0. In addAir, conversely, "amount" is the explicit parameter which modifies volume each time air is added, so "volume" in my formula is correctly used in my formula to find radius. Am I right or is something else wrong in my code?

Sorry for all my questions.  Reply With Quote

10. Moderator   Join Date
Feb 2009
Location
New Zealand
Posts
4,716
Rep Power
18

## Yes I think you've got the right idea.

In SodaCan height/radius are being set in the constructor and volume/surface area are being calculated. (It doesn't matter much where they are calculated as you found.) Height and radius totally describe the can while volume and surface area need to be calculated. Height and radius make up the state of the can.

In Balloon things are a little different. Either the volume or the radius could be used to totally describe the balloon (that is either can be calculated from the other) but you have decided to have both as instance variables. That's fine, but when one changes you must be sure to change the other. That is you must keep the state consistent. This is only an issue for the balloon because the state of the can never changed.

The place where the balloon changes state is the addAir() method. So that is where you must keep the state consistent by calculating the radius ready to be used in either getRadius() or getSurfaceArea(). More jargon: addAir() is known as a mutator method because it alters the state of the balloon and a typical task of a mutator method is to keep the state consistent as you do by recalculating the radius.

-----------------

A little point: the volume of a sphere (which is the shape of balloons in textbooks) is (4/3)*pi*r^3. So if you know the volume V the radius r will be given by r=cube_root(3*V/(4*pi)). Whereas you have r=sq_root(V/(4*pi)).

I don't know if the Math class offers a cube root. You will have to look that up in the Math API docs and/or get creative.  Reply With Quote

11. Senior Member Join Date
Nov 2010
Posts
210
Rep Power
11

## Math.cbrt() exists, but for the fourth root (for example) you could do Math.pow(x, 0.25).  Reply With Quote

12. ##  Originally Posted by Iron Lion Math.cbrt() exists, but for the fourth root (for example) you could do Math.pow(x, 0.25).
Not that it matters much here, but I like this implementation.

kind regards,

Jos  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•