1

Assume there is a class Shape. The class has two functions area() and perimeter().

Let's say Circle and Square inherit from Shape and override these methods. Obviously the results are going to be fractional.

What is the best way to set a precision value for the results. Say the user says PRECISION=2 or PRECISION=3 and the results returned by the functions of Circle and Square class are returned accordingly. Where should I define this functionality? I was wondering how do libraries like numpy handle this situation.

One approach can be to add an optional parameter to these functions and round the results accordingly.

getArea(radius, prec=2) {

}

2 Answers 2

5

Within the confines of JavaScript, do not allow the precision to be specified. Just return the Number, and let the caller determine the precision they need. This likely is due to displaying the area to the end user, and a 16 digit decimal point is hard to read. Most times rounding the precision is a concern of the presentation layer of the application. For this, the Number class already has the functionality: Number#toFixed or Number#toPrecision.

0

Using optional arguments as you suggested is a nice option, and convenient to the user if they want to use a different precision at each call.

Another good option is to have a precision field on your class. The user can then set the precision on class creation or change it later according to their needs. This is better for consistent behavior because the caller does not need to remember to set the precision everywhere.

Either way is fine, the choice will depend on your usage needs and modeling intention.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.