I have written a class that takes the 'nth root' of a java BigDecimal, but I am wondering how to structure it.

I need to provide access to a number of the class variables. Obviously, the root itself, and also the 'number of iterations' performed by the root finding algorithm, are 'returned'.

The way i've usually done this, is by declaring the class variables in question as public variables. However, I have come across an algorithm that performs square roots, and it returns a number of variables, but it uses methods to do so.

What is the better way of doing this?? Is the method route preferable over declaring class variables as public?

02-07-2011, 07:34 PM

JosAH

Quote:

Originally Posted by jezza10181

Hi,

I have written a class that takes the 'nth root' of a java BigDecimal, but I am wondering how to structure it.

I need to provide access to a number of the class variables. Obviously, the root itself, and also the 'number of iterations' performed by the root finding algorithm, are 'returned'.

The way i've usually done this, is by declaring the class variables in question as public variables. However, I have come across an algorithm that performs square roots, and it returns a number of variables, but it uses methods to do so.

What is the better way of doing this?? Is the method route preferable over declaring class variables as public?

When you write software only used by you, it doesn't matter much (it still matters though) but think what could happen if your software is going to be used by others: those public variables are defenseless, they are just there stark naked: they can be changed by anyone who doesn't know what s/he is supposed to do and ruins all your clever algorithms etc. Getters and setters are preferable in such situations. Note that that ignorant person might be you.

kind regards,

Jos

02-07-2011, 08:01 PM

codesmuggler

jezza10181:
It's good to program in a way that your code could be reused by someone else. If you are learning Java programming you might not see that keeping fields private and generating setters and getters for them is a proper way (too much code etc.), but you will see advantage in the future.

02-07-2011, 09:54 PM

quad64bit

Quote:

generating setters and getters for them is a proper way

Don't forget IDEs make this simple to do! Both netbeans and eclipse can 'encapsulate' fields which allows you to generate getters/setters for everything with 1 click!