Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best strategies when calling a method that should modify more than one variable

Tags:

java

variables

I am pretty new to Java, I have to convert C/C++ code to Java and I am running into obstacles. Because of the way variables are passed to the methods, their modification in the method is not straightforward, and I have no idea what is the most reasonable approach to take. Sorry for the pseudocode examples, I hope they will clearly explain what I am talking about without delving into unnecessary details.

I need something that would be equivalent to C

ModifyMyString(type1 &t1,type2 &t2);

(return type doesn't matter, it can be void) as I need the function to modify both t1 and t2.

I can easily modify one of the variables, say t1, by declaring in Java

type1 modifyMyString(type1 t1, type2 t2);    

and assigning the returned value to

t1 = modifyMyString(t1,t2);

but it is only half of a success, as the new value of t2 is lost.

I can declare new class

class JustToPassTwoVariables {
    type1 t1;
    type2 t2;
    JustToPassTwoVariables(type1 tt1, type2 tt2) { t1 = tt1; t2 = tt2; }
}

and do something like

JustToPassTwoVariables jtptv = modifyMyString(JustToPassTwoVariables(t1,t2));

but I feel like it is clumsy and makes the code unreadable.

In desperation I could also resign the idea of using a modifyMyString method, and repeat all the code locally in each place I would call modifyMyString - but it makes even less sense than using JustToPassTwoVariables class.

Is there a correct (or at least widely used, accepted as a standard, whatever) strategy to code such things in Java?

like image 238
Borek Avatar asked Dec 04 '22 08:12

Borek


2 Answers

The recommended way in java is (in some people's opinion the clumsy way) to create a class containing the two fields and return an instance of that class.

I feel that it is much less clumsy if you stop and think about what the method is actually doing, and taking care to properly name both the method and the class returning the two values.

like image 144
Buhb Avatar answered May 30 '23 10:05

Buhb


The simple answer is no. This sort of feature is not allowed in Java.

The correct way to do it is to pass in the object to be modified not the two variables. After all in virtually all cases those variables are already wrapped in an object, in cases where they aren't they often easily can be.

Either split the function into two functions and call it once for each variable, or wrap the variables into an object and pass that object into the function.

Don't forget Java allows Inner Classes which makes this sort of thing less painful.

like image 30
Tim B Avatar answered May 30 '23 10:05

Tim B