So, I just started learning Java, and I discovered that there's no such thing as "pass by reference". I'm porting an application from C# to Java, and the original application has ints and doubles that are either "ref" or "out" parameters.
At first I thought I could pass in an "Integer" or a "Double", and since that was a Reference type, the value would be changed. But then I learned that those reference types are immutable.
So, then I made a "MutableInteger" class and a "MutableDouble" class, and I passed those into my functions. It works, but I guess I must be going against the original design intentions of the language.
Is "pass by reference" in general bad design? How should I change my way of thinking?
It seems reasonable to have a function like this:
bool MyClass::changeMyAandB(ref int a, ref int b)
{
// perform some computation on a and b here
if (success)
return true;
else return false;
}
Is that bad design?
Object-oriented programming is done best if you structure your code into clean, understandable abstractions.
Numbers, as an abstraction, are immutable and have no identity (i.e. a "five" is always a "five" and there is no such thing as "multiple instances of five").
What you're trying to invent is a "mutable number" which is mutable and has identity. This concept is a bit unwieldy, and you'd probably be better off with modelling your problem with more meaningful abstractions (objects) than that.
Think in objects that represent something and have a specific interface, rather than in individual lumps of values.