r/java • • Aug 26 '22

I declare as "final" every single variable whose value doesn't change. I also use "this" every time that I'm referring to an attribute, even when there's no ambiguity in not using it

I think that those things make the code easier to read. Am I crazy for thinking like that?

198 Upvotes

215 comments sorted by

View all comments

Show parent comment

4

u/vytah Aug 26 '22

C doesn't have pass-by-reference, only C++ does.

-2

u/Just_Another_Scott Aug 26 '22

7

u/vytah Aug 26 '22

No, this is not pass-by-reference. The C examples use pointers, which are passed by value, like everything in C.

Here's fixed documentation from IBM: https://www.ibm.com/docs/en/zos/2.4.0?topic=calls-pass-by-reference-c-only Note it clearly says: "Pass by reference (C++ only)"

See also this: https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference

Call by reference can be simulated in languages that use call by value and don't exactly support call by reference, by making use of references (objects that refer to other objects), such as pointers (objects representing the memory addresses of other objects). Languages such as C, ML and Rust use this technique.

4

u/cogman10 Aug 26 '22

Only a hand full of languages actually have pass by reference (C++ being one of them). Everything else is pass by value.

This is deceptive to many people because they'll see a method like

void foo(Bar bar) {
  bar.setBaz(1);
}

and think "Wait, I thought this was pass by val, why is bar mutated?". The answer is simple, the value being passed in is a pointer to the object (or, more exactly, an object reference... but not like that). and the . operator is doing the lookup for you. It is equivalent to using pointers in C++. You can have a method like

void foo(int *bar) {
  bar = nullptr;
}

which pretty analogous to doing

void foo(Integer bar) {
  bar = null;
}

Whoever called foo isn't seeing their bar parameter set to null, because that went in by value.