164 points · by jxub · 8y ago · 187 comments
In fact, you can write a swap(x,y) function in Java. It goes something like this:
class foo { int value }
void swap(foo x, foo y} {
int temp = x.value;
x.value = y.value;
y.value = temp;
}
(Yes, I know this isn't valid Java. Cut me a little slack here, OK?)"But that's cheating" you protest. "That's not swapping the value of X and Y, that's swapping the value of a slot in the values of X and Y, which happen to be objects." Well, yeah. So? Compare that to this C code:
struct foo { int value }
void swap(struct foo x, struct foo y) {
[same code as above]
}
The effect of this function will be DIFFERENT. Specifically, the C function will have no effect while the Java function will swap the value slots of X and Y because C lets you pass a structure as a value while Java does not. All Java "values" are (tacit) pointers to objects [1]. Pounding your fist on the table and insisting that Java is pass-by-value because you can't write a swap(x,y) function obscures this crucial difference.[1] OK, it also has ints and floats of various sizes. But that's really it.
Pedantry matters in our profession. Details have consequences.
I didn't say it was. I said that insisting it is pass-by-value isn't helpful.
The real problem here is that we have only two terms which we're using to try to distinguish between three different concepts.
It's still only two concepts, there's just the side effect of Java and friends' implicit pointers that makes things muddier. The Java function
void swap(Object x, Object y) {
Object temp = x;
x = y;
y = temp;
}
is equivalent to the C program void swap(void *x, void *y)
{
void *temp = x;
x = y;
y = temp;
}
and it has the same bug for the same reason. It's only the implicit nature of references in languages like Java that makes it not look like pass by value, but that implicit nature is there in other places as well (eg, the Java code 'Object x = y' is equivalent to the C code 'void *x = y').I think the best approach is to just call it what it is, pass by value, and then also remind people if need be that objects are always pointers so it's passing a pointer by value.
Dog d means "a pointer to a dog object"
By forcing "pass-by-reference" to mean two things you are creating ambiguity that is trivially resolved by correctly interpreting a java type signature.
You are insisting that the definition is changed. Emulating call-by-reference in a call-by-value environment does not change the semantics of the language.
Just accept that the meaning you project to these terms is different from their real meanings. Don't try do redefine them and convince the rest of the world that your meaning is the right one.
Well, if so, even more reason NOT to say "Java is Pass-by-Value".
Instead, you should be a good pedant, and explain the Java passing model, its caveats and edge cases, in its entirety.
If details matter, don't throw some BS blanket statement like "Java is Pass-by-Value" around, that can be misinterpreted in 200 ways, and that doesn't capture the whole nuances of what's going on.
"Pass-by-reference" is simply wrong, as it implies behavior which Java does not exhibit.
[1] https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sh...
Plus, I'd argue it's a lot easier to teach the nuances from the beginning rather than have to break someone's assumptions 4 years down the line (e.g. the traditional time of an undergrad CS education).
Of course, this kind of discussion isn't new to the Python community either. The actual calling convention is somewhere between call by value and call by reference, sometimes called "call by object". This is well worth reading: http://effbot.org/zone/call-by-object.htm
Yes it is. The thing that we talk about when we talk about "the value of foo", in Java, is passed by reference.
> Yes it is.
And this is my point in a nutshell. This argument will never be resolved, and so continuing to argue over it isn't helpful no matter how hard you pound your fist on the table.
Which is exactly what they are.
> But Java doesn't have first-class pointers, it has implicit pointers. The only thing you can do with a Java pointer "value" is to tacitly dereference it.
So? Just because you're not given direct access to the value itself doesn't change the semantics of the language. If you assume "pass-by" is strictly dichotomous and the choices are either value or reference, then Java can only be pass-by-value, its semantics simply don't allow the possibility of it being pass-by-ref.
IIRC the Python community calls it "pass reference by value", sadly they seem to be more or less the only ones doing so. CLU called it "pass by sharing".
> All Java "values" are (tacit) pointers to objects [1]. Pounding your fist on the table and insisting that Java is pass-by-value because you can't write a swap(x,y) function obscures this crucial difference.
Then again that Java's boxed types are boxed seems pretty obvious...
Well, there's your problem right there: pass-by is not "strictly dichotomous." There are (at least) three different argument-passing disciplines in common use. If you insist on using only two words to distinguish among them you will cause unnecessary confusion.
It's not my problem, it's yours.
> pass-by is not "strictly dichotomous."
Which you may have wanted to explain in your essay if you believe it instead of going on worthless rants.
> If you insist on using only two words to distinguish among them you will cause unnecessary confusion.
I don't.
The purpose of teaching new programmers value vs reference is to make them aware of the dangers of mutating objects passed to functions.
public static void main(String[] args) {
MyClass c = new MyClass();
c.Message = "Hello";
c.ID = 1;
mutate(c);
System.out.println(c.Message); // "Goodbye"
System.out.println(c.ID); // 2
}
public void mutate(MyClass c){
c.Message = "Goodbye";
c.ID = 2;
}
public class MyClass{
public String Message;
public Integer ID;
}Suppose we have local variables A0, B0 and A1, B1.
A0 and B0 hold references to objects O and P, respectively.
A1 and B1 also hold references to this same pair of objects, respectively.
Because Java is pass-by-value, you cannot write a function which appears swaps A0 and B0 without also appearing to swap A1 and B1 which are not passed to it. If we swap A0.content with B0.content, then there will be the unintended consequence that A1 and B1 also swap.
Swapping the referenced content isn't the same as swapping the variables; we can tell the difference because the change is not confined to just the specified variables.
Now you could argue that A0 and A1 aren't really different variables. But, undeniably, they are; even if they initially refer to the same object, they can be mutated not to. Or, if the variables are not mutated, perhaps they are initialized to the same object in some instantiations of the lexical scope and to different objects in other instantiations of the scope.
No, that's not true at all. Crucially, you can assign a new value, and that is where the distinction you're calling pedantic makes all the difference.
When assigning to a function parameter, am I assigning to the variable passed as an argument or am I assigning to a copy of that variable?
It's hard to overstate the importance of that question, and that's why these two concepts have long established names: call-by-reference and call-by value.
No, you cannot assign a new value to a pointer. You can assign a new value to a variable whose value is a pointer, and you can assign a new value to the storage location that a pointer points to (in C, though not in Java) but you cannot assign a new value to a pointer. A pointer is just a number.
I think it's obvious that I was talking about assigning to pointer variables because parameters are always variables and never just values.
Also, at the risk of being what you are calling pedantic, dereferencing is not the only thing you can do with an object pointer in Java. You can also check nullity, equality, and cast the object. These are substantive actions with semantics that are outside any particular object's implementation.
Really, the only thing i can think of that you can't do with Java pointers that you can with other languages is pointer arithmetic - and that's due to Java's original reason for being: making portable code where object implementations could be isolated from memory allocation inner workings.
Fair enough (though checking nullity is just a special case of checking for equality).
> the only thing i can think of that you can't do with Java pointers that you can with other languages is pointer arithmetic
Well, yeah, but it's not like pointer arithmetic is some obscure little feature that is hardly ever used. Pointer arithmetic is the thing that distinguishes C-like languages from Lisp-like languages. If you're trying to explain a distinction among programming languages that involves pointers you can't just sweep pointer arithmetic under the rug as if it were a trivial detail.
That's not really convincing given many languages have pointers (as a directly manipulable concept) and actual pass-by-value but no pointer arithmetic unless you call into some sort of unsafe escape hatch.
> If you're trying to explain a distinction among programming languages that involves pointers you can't just sweep pointer arithmetic under the rug as if it were a trivial detail.
Sure you can.
Lots of languages have it as feature, C isn't a special snowflake.
template<class T>
void swap(T& a, T& b) {
T tmp = a;
a = b;
b = tmp;
}
When called as int a=1, b=2;
swap(a, b);
The variables a and b are passed by reference, or you can think of it as an implicit pointer. This is the meaning of pass-by-reference - changes made to the value of a variable directly impact the referred-to variable.Pass-by-reference can be confusing and its inclusion in C++ is useful as immutable non-null pointers, a use which modern languages support in various other ways. Thinking of Java objects as pointers to objects might be a bit confusing at first as well, but it's the correct mental model for what's happening under the hood.
It all goes back to understanding computation in the context of a von Neumann machine with addressable random-access memory, and knowing that values are stored in numbered memory cells, so variables can be either the memory region itself, the memory region's number, which itself can be stored in a memory region whose number can be stored in another ... etc. You can't abstract away the basic properties of the computing architecture we use, so it's a good idea for programmers to have mental models of computer memory and programming language variables that are fundamentally congruent with the von Neumann architecture.
You can easily bind a C++ reference to a null pointer. Your compiler will silently accept it and the behavior will be predictably that &ref == 0 will evaluate true.
E.g.
// if OOM, &ref is null
object &ref = *new (std::nothrow) object(args, ...);
Of course, it's not defined behavior; i.e. wrong on paper.(If only a paper tiger could defend you against a real flesh-and-horn charging rhinoceros, ...)
Whether or not it's defined is moot; the fact is you can commit undefined behavior with references. They are just pointers in disguise: wolves clad in sheepskins.
References inside class/struct objects are real pointers occupying a word. If such an object is out of scope and has been deleted, and you use the reference, it's exactly the same as a use-after-free of a pointer or any other value. Through the bad reference, some wrong object will be accessed or modified.
The only relatively harmless references are the lexicaly scoped ones which go away at compile time, behaving as aliases: { int x = 42, &x_alias = x; }.
Swap is just a convenient example. Ultimately, if rebinding the function argument has no externally visible effect, it's not pass-by-reference, but rather pass-pointer-by-value — In C++ terms, a Java method with signature `foo(T arg)` is akin to C++'s `foo (T * const arg)` rather than `foo(T &arg)`.
??? Pretty sure Java is uniquivocably pass-by-value. Your example of Swap is simply incorrect.
IIRC, in a pass-by reference language, Swap could be written as
swap(int x, int y):
int z = x;
x = y;
y = z;
And then you could call it as: int a = 4;
int b = 5;
swap(a, b); // b now is 4 and a is 5
This can't be done in Java.Also Java's reference types seem to be pretty FCO to me. Just because Java don't have pointer arithmetic is hardly a disqualification.
BTW, I find it interesting that Java's argument passing semantics and Common Lisp's are, so far as I can tell, identical.
Java doesn't do "object assignment" so you cannot say
Foo d = new Foo(...);
Foo c = d;
And get two objects, you have two references to the same object. If you invoke a method on c or d it will be dispatched to the same code. So c.SetVaueX(10) and print d.GetValue(x) will show you the same value of 'x'.In C++ or other pointer languages you could have
*d = *c
which would do an assignment of the bits from one to the other, then manipulating d would manipulate its copy of the bits and manipulating c would manipulate its copy of the bits.Obviously the output will be different the input was different. The equivalent C code would have passed pointers. In that case the behavior would have been identical passed in values not swapped contents swapped. Just because Java only has object references, doesn't mean they aren't references.
If Java had pass-by-reference, you could write one that doesn't.
All values in Java are indeed either primitives or pointers. You cannot define your own values! How is anyone supposed to call this a high-level language?
It's so easy to guess their meaning consistently wrong that people don't brother to look them up. When several people wrongly guess the semantics wrong exactly the same way and talk to each other, new meaning is established.
It's not uncommon to have office debate of the difference where 9 people are sure that they know the right definition and the one person who argues for the right definition can't convince them.
EDIT: there are already at least two comments that argue that the wrong definition is the right definition. These guys feel so strongly that their definition is right that nothing convinces them and people agree. It's a hopeless pursuit to get this right.
https://stackoverflow.com/questions/373419/whats-the-differe...
I find this to be the source of most programmers' confusion about most topics. Sometimes I spend hours arguing trying to convince someone that X works one way, because I've read the spec and the source code, while they believe that X works a different way, because they looked at its name and used it that way last time.
You can't call Java pass-by-reference just because it feels right to you. It is a phrase which means something which some languages are and Java is not.
"Pass boolean by value"
"Pass integer by value"
"Pass reference-to-T by value."
The confusion arises because Java doesn't explicitly distinguish between a and &a; if you write "Foo a = new Foo();" in Java, the behaviour is similar to "Foo *a = new Foo();" in C++. So if we ask how "a" is passed, is the "a" we're talking about the reference or the value?
Seems weird to me to say that Java "passes by value" when all objects being passed are actually references to objects.
void f(Foo x); // pass-by-value
void f(Foo* x); // pass-pointer-by-value
void f(Foo& x); // pass-by-reference
In the last example, you aren't passing in a value, you are essentially creating an alias for some variable in the calling scope.The only real difference between the last two is that the last one shouldn't be sent in as null, isn't it? The test in OPs artictle doesn't really make sense either, because you can switch the values using pointers as well.
C++ just forces you to be explicit about this, as others have pointed out.
In relational algebra a "relation" is what most people know as a "table".
"relation" is maybe a good name in the realm of relational algebra, but a bad name in the realm of users of relational databases.
In this case "pass-by-value" and "pass-by-reference" are good names in the realm of compiler theory ("I'm a compiler guy at heart") but very, very bad names in the context of discussing parameter passing in java & objects.
Sorry, i agree with your point but I felt like being pedantic :3
"Alias" means nothing to a CPU, nor is it an ABI. At the core, passing by reference is usually implemented by providing the "address-of" something to a function (for example). The "address-of" itself, is passed by value. Going by that logic, everything everywhere is passed by value.
But the language isn't defined in terms of a CPU. It's defined in terms of abstract semantic rules. You shouldn't think about implementation, especially at the CPU level, when talking about semantics.
The idea is that the alias is implicit in pass-by-reference. It isn't implicit in pass-by-value. How you implement that alias is irrelevant for discussion at this level.
I disagree. I submit the whole reason we pass objects by reference or by value in the first place, has much more to do with conserving computational resources/reducing runtime, than with providing abstract programming semantics for software developers.
(With the exception of primitives. I guess that's the real rub -- Java's special casing of primitive values.)
By the way, there is at least one additional difference in languages like Python and JavaScript with dynamic variable (not value) scope. In those languages, you can `delete` a variable, which removes the binding from the scope. Pass-by-reference would mean that you could delete a variable from a non-local scope if the variable were passed by reference. (This is not the case; `delete` in these languages merely deleted the local variable binding, as it ought, given that they are pass-by-value.)
Who died and made you secretary of the Académie anglaise? Language is defined by consensus; a word means x only to the extent that it is understood to mean x by both the sender and the receiver. This whole thread makes it pretty clear that "pass-by-reference" does not draw the distinction that you think it draws; if you want to draw those distinctions, find words that clearly draw those distinctions. Words are tools for communication, not ends in themselves.
C# is somewhat more clear to me because it lets you do either, which VB kinda did too.
The key point here is reference types vs value types, which is distinct from pass by reference and pass by value.
Java is pass by value only with reference types and primitive value types.
C# has reference types and value types and pass by value default with pass by reference optional.
passing a reference type by reference is passing a pointer to a pointer.
See: https://docs.microsoft.com/en-us/dotnet/csharp/programming-g...
It doesn't matter too much IMO. Most people intuitively understand how object references work in modern programming languages, and these discussions don't add a lot to their knowledge.
static void foo(Object x) {
x = null;
}
would have an effect visible to the caller. This is exactly the case with C++ references, and C and Lisp macros, which are call-by-reference. (C++, C, Lisp, and the term "call-by-reference" all having existed prior to Java, by the way, so Java and its users do not get to redefine it.)But the above function does nothing in Java. Hence, Java is not call-by-reference.
Wikipedia has a nice quote [1] from Barbara Liskov (the namesake of the Liskov substitution principle), made when she invented the passing style used in Java in 1974, for use in her language CLU:
"In particular it is not call by value because mutations of arguments performed by the called routine will be visible to the caller. And it is not call by reference because access is not given to the variables of the caller, but merely to certain objects."
She settled on the term "call-by-sharing". Maybe we should all just agree on that.
[1] https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sh...
What makes you say this? You can't do pointer arithmetic on Java references, and the internal memory model is completely obscured. C++ and Java references look similar to and are accessed like variables. The major difference is that Java references can be reassigned, like a pointer, which is necessary in a language without true pointers.
In Java, a reference is a value, it can be stored in an ArrayList like a normal value, you can operate on the reference itself (reseating it, comparing two of them, comparing to null), there is not always a referent.
I fail to see what possible value this has.
When actually communicating with people for the purpose of conveying ideas (not just for fun), it's best to avoid terminology where not everyone has the same understanding of the definition. Open discussions about terminology are also a good way to identify these types of ambiguous terms and possibly come up with technical terms that everyone agrees on.
It is a funny language feature to have when you think about it; it just so happens to be useful. References and pointers are distinct in languages that have both (C++), so not mixing the terms between languages is helpful. If Java programmers started referring to their variables as "pointers," because internally, that's more representative of what they are, I'd be a bit irked.
It's that the phrase "pass by reference" is a term of art in compiler design, and all language theorists including those who work on Java agree on what it means, and what it means is the thing the article says it means, and Java doesn't do it.
What gets passed by value in Java? Well, sometimes it's a reference-as-Java-means-it! But that reference is always passed by value, never passed by reference.
1. The way parameters are actually passed in Java, primitives by value, object references by value.
2. How to call this mechanism.
My guess is that many fail on item 1. Once understanding of item 1 is achieved, item 2 isn't terribly interesting.
Create-copy - Copies the data into a new memory location, so modifying this variable will not modify the original variable.
Create-alias - Creates a new name for the same memory location, so modifying one variable will also modify the other variable.
Having spent too much time in Powershell, which defaults to create-copy, it was jarring to switch to Javascript and the seemingly-non-deterministic behavior of create-alias on setting a new variable equal to an array. From an algebraic perspective, when I modify "foo", I expect "bar" to remain the same.
Pass-reference-by-value is just a special case of a shallow copy.
let a = [1, 2, 3];
let b = a;
b[1] = 5; // will modify a
b = [1, 6, 3]; // will not modify a
In languages like C++, there's a way to make it so that last line _would_ modify a, which is why there's a need to use different words for the different phenomenon.In other words, "C-style" pass-by-reference means this function would have an undesirable side-effect:
void foo(Thing x){ x = null; }
Ned Batchelder - Facts and Myths about Python names and values - PyCon 2015: https://www.youtube.com/watch?v=_AEJHKGk9ns
Dog d = new Dog("fido"); d = alterDog(d);
public Dog alterDog(Dog d) { d.name="arfybark"; return d; }
It's not quite a pure function since it changes it in place, but at least the parameters and return types reflect the method. I ran across a term for this practice in the past but don't remember what it's called.
That syntax loosely implies that removing the second d assignment would allow me to create new-but-altered dogs with alterDog(Dog), which isn't the case. If I wanted to use assignments like that, I would try to go fully immutable with factory methods that help me make slightly different, new dogs on the fly, and return them.
In Java with no explicit pointers available to its users, the way objects are handled are explained better with the pass-by-reference concept than (whooosh!, magic in) pointers (and out) passed-by-value reality. Pointer is a foreign concept to Java, so it really makes more sense to its users that object variables start referring to other objects when they are reassigned, instead of the old object being changed in-place. Things get funky with equality comparison via == operator, but still, it is better than pointers.
I also wonder, does C++ really pass-by-reference when parameters have &'s behind their identifier declarations, or does it internally pass a reference by value and dereference it every time it is used within that scope? Are 4/8 bytes allocated for the reference variable or not?
I don't know what you mean by "really pass-by-reference". There is no such concept of a "reference" at the CPU level; nor is that relevant to language semantics. If you were to look at the generated assembly it would look identical to as if pointer referencing and dereferencing were used.
I was wondering if `int &a2 = a;` allocates memory in stack to make `a2` refer to `&a`, or does `a2` somehow truly become an alias for `a` in symbol table. As you've said that the assembly would look the same as pointers being dereferenced, then I suppose C++'s reference types are just a syntax sugar around the C's way of achieving the pass-by-reference concept through passing the address and then dereferencing it.
However, outside of function signatures, if you write:
int a = 2; int &aref = a; int b = aref;
I'd assume that the compiler is smart enough to optimize away &aref.
int dosomething(int * & array) {}
That * & is just complete voodoo magic.
FWIW, I don't use pass-by-value or pass-by-reference to refer to languages like Java, Python, Lua, etc... Instead, I use "pass-by-object-identity" (aka "call-by-sharing", "call-by-object") to refer to the semantics of those languages. It avoids the association many people have between the term "by-value" and copying behaviour.
Also part of the problem: many beginning and intermediate programmers don't understand the difference between rebinding and mutation. This leads to people interpreting the following snippet:
def foo(a, b):
a = 2
b.append(3)
x = 1
y = []
foo(x, y)
print(x, y) #1, [3]
... as meaning that ints are passed by value and lists by reference, while in fact both are passed by object identity, and it is the fact that a is rebound while b is mutated that made the difference.Dog someDog = new Dog("Fifi");
foo(someDog);
System.out.println(someDog.getName()); // name will be Max