Why in java there is no reset option for variables [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Sometime when we declare and initialize a variable, say we have an int i =10; then after some code this variable would be modified like this code bellow
public class reset {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 10;
int co = 1;
while (co < 10) {
i++;
System.out.println(i + "*" + co + "=" + i * co);
if (i == 99) {
i = 11; //line 11
co++;
}
}
}
}
then at some point (here at line 11) we need to re-initialize then variable, wouldn't it be nice if we had any language feature doing it automatically instead for example
reset:i
I think it's very beneficial for productivity, isn't it?

we need to re-initialize then variable, wouldn't it be nice if we had any language feature doing it automatically instead?
No
I think it's very beneficial for productivity, isn't it?
No
Resetting a variable to its start value is in many cases a sign that the scope of the variable is to large. So with clean code you hardly ever need such feature.
And of course every feature comes at the cost of complicating the language even more.

The initializer line
int i = 10;
simply creates byte code instructions to assign the value 10 to the variable. That assignment is no different than any other assignment.
To implement reset, there would need to be an extra bit of metadata kept for each variable to say what the special, initial value is.. That metadata is not currently kept in the symbol table, since there is no concept in Java for a 'initial value'. The additional overhead would trade off against the utility of the reset command.
Might be a good idea, but you can get the same thing by just declaring a constant, and reassigning to the constant.

What about this code? I can understand your question from a starter's perspective, but usually it requires a bit more practice to see why certain constructs are not required:
public class NoReset {
private static final int X_START = 11;
private static final int X_END = 99;
private static final int Y_START = 1;
private static final int Y_END = 9;
public static void main(String[] args) {
for (int y = Y_START; y <= Y_END; y++) {
for (int x = X_START; x <= X_END; x++) {
final int result = x * y;
System.out.printf("%d * %d = %d%n", x, y, result);
}
}
}
}
Note that you should not nest to many loops, but creating a "hidden loop" is at least as dangerous, it gets very hard to track variables such as i within your code.

If you want to use the current Java language to do what you want to do, then simply provide a function in each class that you want to perform a "reset" like:
private void reset() {
var = xxx;
var2 = yyy;
...
}

Related

Magic number constant name convention for tests ONE, TWO,.. ONE_HUNDRED vs _1 , _2, _100 [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
so I'm doing some code refactoring/sonar fixes, and there are some tests that contain magic numbers, 5, 123, 567 or whatever, i wanted to create a NumberConstant class where we save numbers used in tests, everything is good we have something like this
public static final int ZERO = 0;
public static final int ONE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
public static final int FOUR = 4;
public static final int FIVE = 5;
the problem is when doing the refactoring, the code is "ok" for SonarQube, but something seems off, the code somehow becomes "cluttered",
i mean just compare these two lines
before
private LocalDateTime endtDateOfFiscalYear2018 = LocalDate.of(2018, Month.DECEMBER, 31).atTime(LocalTime.MAX);
after
private LocalDateTime endtDateOfFiscalYear2018 = LocalDate.of(TWO_THOUSAND_EIGHTEEN, Month.DECEMBER, THIRTY_ONE).atTime(LocalTime.MAX);
I thought a good compromise would be :
private LocalDateTime endtDateOfFiscalYear2018 = LocalDate.of(_2018, Month.DECEMBER, _31).atTime(LocalTime.MAX);
and having my NumberConstant class like this
public static final int _0 = 0;
public static final int _1 = 1;
public static final int _2 = 2;
public static final int _3 = 3;
public static final int _4 = 4;
public static final int _5 = 5;
is this a good compromise or is the whole approach incorrect? what is your approach to keeping your test clean and understandable?
I think the whole approach is incorrect.
What do you gain from introducing a named constant where the name just rephrases the value?
Introducing a constant from a literal value generally has some benefits:
Instead of some magic number you see a meaningful name.
It groups together the situations where that very same value has the same meaning. E.g. you might encounter lots of places using the number 10, some as a digit representation radix, some as the base of a logarithm value, some representing the month of October, and so on.
If you find out later that a different value better represents the intended meaning, you can change that at one central place.
All this doesn't work if you replace all occurrences of a literal 10 with a constant named TEN or _10. E.g. you'll hopefully never change TEN to have a value of 20.
So, what's needed is more than just some automated, blind replacement of values. You need to understand what that specific occurrence of the literal means, and then introduce an appropriate name for this concept, replacing all occurences of the same concept with a common name.
The original developer should have done that. If now you just blindly introduce names like TEN, you just hide the deficiency, and it'll never be improved. So I'd rather have Sonar permanently remind me of the problem than to hide it forever.
And sometimes, especially in test cases, I'd even prefer to see a literal 4711 than a constant named SOME_RANDOM_FOUR_DIGIT_NUMBER.

I cannot convert c++ to java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How can I convert this C++ code to Java?
I could not convert parameter &poly_size in method clip.
This code from https://www.geeksforgeeks.org/polygon-clipping-sutherland-hodgman-algorithm-please-change-bmp-images-jpeg-png/
void suthHodgClip(int poly_points[][2], int poly_size, int clipper_points[][2], int clipper_size)
{
for (int i=0; i<clipper_size; i++)
{
int k = (i+1) % clipper_size;
clip(poly_points, poly_size, clipper_points[i][0], clipper_points[i][1], clipper_points[k][0], clipper_points[k][1]);
}
}
void clip(int poly_points[][2], int &poly_size, int x1, int y1, int x2, int y2)
{
int new_points[MAX_POINTS][2], new_poly_size = 0;
// blabla
poly_size = new_poly_size;
for (int i = 0; i < poly_size; i++)
{
poly_points[i][0] = new_points[i][0];
poly_points[i][1] = new_points[i][1];
}
}
First remember that Java isn't C++, so odds are a direct translation is going to be sub-optimal.
With that out of the way, The question is How do you pass an integer by reference in Java? The only reason in C++ you would pass poly_size by reference is if you wanted to change its value inside the function, and that happens at poly_size = new_poly_size;
My Java is tragically rusty, but I'd take advantage of the C++ version of clip not returning anything and make the Java version return new_poly_size;
Java doesn't give you choice over pass-by-value and pass-by-reference. Instead it passes primitives, such as int by value, and objects by reference.
Unfortunately the Java non-primitive Integer (which would be passed by reference) is immutable, so the only ways of doing this would be to either return new_poly_size, or make your own modifiable object containing this value, pass it to the function.

Java, Methods? Or constructors ? I am not sure what to call it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am not sure if you see what I am trying to do here but basically I have a few questions and problems
1)The part that is called public MethodPractice() ... what is this called? is this considered a constructor a method or what?
2)The part named MethodPracticeDiff() . . . is this allowed and if so how do I insert it into the main method for execution...
Do you guys see what I am trying to do here? Basically I want to split the program up into different pieces for example let say I wanted my own space for a calculation method to add to numbers up
and another method to define the numbers like give them a value
and a last method with a for loop making the numbers printout 10times
Any who before I make this more confusing than what it is, my question is how do I make this program execute
public class MethodPractice {
public static void main (String[]args){
MethodPractice add = new MethodPractice();
//MethodPracticeDiff add2 = new MethodPracticeDiff();
}
public MethodPractice() {
int x = 0;
int y = 99 ;
int total = x + y;
System.out.println(total);
}
public void MethodPracticeDiff(){
int z = 10;
int k = 25;
int total = z + k;
System.out.println(total);
}
}
(1) If it's in class MethodPractice, it's a constructor.
(2) Yes, this is allowed. But it's a method not a constructor. Standard practice is to begin it with a lowercase letter.
As follows in the main() method:
MethodPractice add = new MethodPractice();
add.methodPracticeDiff();
MethodPractice() is a constructor -- it has no return value and matches the name of the class.
MethodPracticeDiff() is a method -- it has a return value and does not match the name of a class.
You call methods once you have an instance of the class. e.g.
MethodPractice add = new MethodPractice();
add.MethodPracticeDiff();

Finding everything that affects a variable

I'm trying to make a program that will read in a class file and if you give it a variable for example you give it "i" in the following example:
public class Example {
public static void main( String[] args) {
int i = 1;
int j = 5;
int k = 2;
i = i + k;
System.out.println(i);
}
}
Then my program will return
int i = 1;
int k = 2;
i = i + k;
System.out.println(i);
Since these are variables that affect i.
I'm not sure how to do this. So far I've tried using javaparser which takes in the file and finds all the VariableDeclarationExpr using a visitor pattern. However, this won't print out the bottom two cases in the code above.
Can anyone give me any hints to how to find them?
The VariableDeclarationExpr represents only declarations (like in your case int i = 1;). But the other two statements in your code are not declarations. They are assignments (probably AssignmentExpr) and a method call (probably MethodCallExpr). So I would first think about where the variable i can appear and then cover all the cases individually. I hope that helps

What is the purpose of variable duplication in a method?

I see this [below] all over in the Android code (and some other code sources). What is its point or purpose?
class Foo {
int mBar = 1337;
static void main(String... args) {
System.out.println(isFubar());
}
boolean isFubar() {
int ret = mBar; // <--- Focus of attention
if (ret == 666)
return true;
else
return false;
}
}
It seems like a waste of time and resources. mBar clearly isn't being modified. There is no risk of it being modified (in the given context), so why would one duplicate the primitive just to preform a noninvasive check on it and return?
EDIT Specific example from the class CellLayout in the Android Source
public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, RectF dragRect) {
final boolean portrait = mPortrait; <--- Here it is
final int cellWidth = mCellWidth;
final int cellHeight = mCellHeight;
final int widthGap = mWidthGap;
final int heightGap = mHeightGap;
final int hStartPadding = portrait ? mShortAxisStartPadding : mLongAxisStartPadding;
final int vStartPadding = portrait ? mLongAxisStartPadding : mShortAxisStartPadding;
int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
int x = hStartPadding + cellX * (cellWidth + widthGap);
int y = vStartPadding + cellY * (cellHeight + heightGap);
dragRect.set(x, y, x + width, y + height);
}
Perhaps for multi-threading. If the value of mPortrait changed between the following two lines you would have mixed results.
final int hStartPadding = mPortrait ? mShortAxisStartPadding : mLongAxisStartPadding;
final int vStartPadding = mPortrait ? mLongAxisStartPadding : mShortAxisStartPadding;
For example:
final int hStartPadding = true ? mShortAxisStartPadding : mLongAxisStartPadding;
// somehwere else: mPortraint = false
final int vStartPadding = false ? mLongAxisStartPadding : mShortAxisStartPadding;
A few ideas come to mind.
The expression needed to retrieve the class member variable might be really complicated (your example is not), so saving it in a local variable might be more readable.
It is possible that storing it in a local variable is more efficient, especially if the method has to access the value more than once. (Your example does not do this.)
Retrieving the value once gets its value at that moment in time, and not some later value that another thread may have modified in the meantime.
Storing it in a local variable makes it easy to examine with a debugger.
For your particular example, only reason (4) makes any sense.
I use it so i can modify the variable in recursion or loops and not mess with the original one. It also helps with passing the variables between classes and other methods.
Also, if it is changed while the method is running, the method will not mess up, it will continue with the variables it started with. I had this major problem while multi-threading my graphics printing and code. The code would change variables and weird stuff would happen on the screen.
I don't know about hardware or speed, but on the code side, it makes it very simple and flexible in many cases.

Categories