Java Forum / General / March 2006
method parameters const properties in java
marcwentink@hotmail.com - 22 Mar 2006 09:46 GMT Is there a way to distinguish between input en output method function parameters in java, like there is in C# and C++? Something like const in C++?
Marcus Wentink
Timo Stamm - 22 Mar 2006 09:55 GMT marcwentink@hotmail.com schrieb:
> Is there a way to distinguish between input en output method function > parameters in java, like there is in C# and C++? Something like const > in C++? What are "input en output method function parameters"?
Timo
marcwentink@hotmail.com - 22 Mar 2006 10:04 GMT > What are "input en output method function parameters"? I might be unclear, let me explain what I mean with an example. I have a function in the present (old) java code I am working with:
HandleElement( ElementType Elem, NodeType Node) {....}
In C++ code I could have something like
HandleElement( ElementType& Elem, const NodeType& Node) {...}
and I can directly read in the code that most probably Elem is changed with the values from Node and be certain Node will not change. Hence Node goes "in" and Elem comes "out". Is there something simular in java?
(As you might have guessed I have more experience in C++ as in Java)
Timo Stamm - 22 Mar 2006 11:10 GMT marcwentink@hotmail.com schrieb:
>> What are "input en output method function parameters"? > [quoted text clipped - 10 lines] > with the values from Node and be certain Node will not change. Hence > Node goes "in" and Elem comes "out". If you used the principle of "self documenting code", the method could look like this:
handleElement(Node in, Element out) {...}
> Is there something simular in java? No, there is nothing similar to const in java. With final, you can tell the compiler that the given reference is not allowed to change. But you can still call methods on the final object and change it.
Timo
marcwentink@hotmail.com - 22 Mar 2006 11:28 GMT > If you used the principle of "self documenting code", the method could > look like this:
> handleElement(Node in, Element out) {...} Self documenting means you can add it to your code for clearance, but it does not get used by the compiler javac to enforce some rules I presume? Still I think this would have made the code I am reading clearer, so I think I might use that.
> With final, you can tell > the compiler that the given reference is not allowed to change. But you > can still call methods on the final object and change it. Strange. But is not the operator = a method that changes the object which is blocked? Anyway, I know final, that's not what I am exactly looking for. I found const in C++ convenient, but if there is no simular keyword in java, that's life. Probably java has some interesting features that c++ does not have.
Timo Stamm - 22 Mar 2006 11:59 GMT marcwentink@hotmail.com schrieb:
>> If you used the principle of "self documenting code", the method could >> look like this: [quoted text clipped - 4 lines] > it does not get used by the compiler javac to enforce some rules I > presume? Self documenting code basically means that you use meaningfull names for variables and methods.
See http://c2.com/cgi/wiki?SelfDocumentingCode for a lot of info and interesting controversy.
> Still I think this would have made the code I am reading > clearer That's all there is to it.
>> With final, you can tell >> the compiler that the given reference is not allowed to change. But you >> can still call methods on the final object and change it. > > Strange. But is not the operator = a method that changes the object > which is blocked? Yes:
final StringBuilder x = new StringBuilder(); x.append("abc"); // changes the state of object x // const would not allow that x = new StringBuilder(); // error because x is final
marcwentink@hotmail.com - 22 Mar 2006 15:09 GMT > final StringBuilder x = new StringBuilder(); > x.append("abc"); // changes the state of object x > // const would not allow that > x = new StringBuilder(); // error because x is final Ok.., then for primitive types, like int for example, final means the value cannot change. But for object references it just means the reference itself cannot point to another object. Hence final cannot make the object itself, the values contained by the object, unchangeble? Is that correct?
Timo Stamm - 22 Mar 2006 15:49 GMT marcwentink@hotmail.com schrieb:
>> final StringBuilder x = new StringBuilder(); >> x.append("abc"); // changes the state of object x [quoted text clipped - 6 lines] > make the object itself, the values contained by the object, > unchangeble? Is that correct? Absolutely.
marcwentink@hotmail.com - 22 Mar 2006 15:56 GMT > Absolutely. Then a usefull day has passed again, since you thought me something new
:-) Thanks!
Thomas Weidenfeller - 22 Mar 2006 12:06 GMT > Strange. But is not the operator = a method that changes the object
> which is blocked? Anyway, I know final, that's not what I am exactly > looking for. I found const in C++ convenient, but if there is no > simular keyword in java, that's life. Probably java has some > interesting features that c++ does not have. First, one often doesn't need something like const, if an object is properly designed (e.g. is not a mixed bag of otherwise unrelated things), and if it is properly so it itself ensures its internal state is consistent regardless of which methods of it are called. Objects are there to be used, and when passing an object around this is done for a purpose, and there is nothing inherently wrong in using an object. This is more a design and philosophical issue than a coding issue.
Second, if you really, really, badly need to protect a particular object in certain situations, provide an immutable type of it or wrapper. This is still no 100% protection, but often good enough. There are several ways to implement such a mechanism. E.g. for a start with code like
class Thing { int value; void setSomething(int value) { this.value = value; } }
class ImmutableThing extends Thing { void setSomething(int value) { ; // do nothing } }
For a real-world example, see the collection classes, which have synchronized an read-only wrappers.
Alternatively, you could pass a (deep) cloned version of the object around. But that creates new problems (synchronizing the state of the two objects when both are in use).
/Thomas
 Signature The comp.lang.java.gui FAQ: ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/
tom fredriksen - 22 Mar 2006 12:45 GMT > First, one often doesn't need something like const, if an object is > properly designed (e.g. is not a mixed bag of otherwise unrelated [quoted text clipped - 3 lines] > purpose, and there is nothing inherently wrong in using an object. This > is more a design and philosophical issue than a coding issue. The point is to be able to pass read-only data to a method, insuring data can not be changed in that context. Its a simple and valuable mechanism that has its use, especially when designing interfaces and extending classes. You can then make sure the the object has to abide by the rule that the class can only read some of its input data and not change the state of other parts of the system. To me, its an extension of the encapsulation/modularisation principle. That's why I don't understand why its not possible to make an object temporarily immutable by using a const/final on a parameter.
/tom
Thomas Weidenfeller - 22 Mar 2006 14:32 GMT > The point is to be able to pass read-only data to a method, insuring > data can not be changed in that context. Its a simple and valuable > mechanism And here I disagree.
1) IMHO it is not very valuable. I work from the assumption that inside a called method the methods of the objects provided as actual parameters are used for a reason. And it is only up to the implementations of these used methods to decide what to do when called - by whomever.
I do not assume that a called method maliciously or randomly calls the methods of the objects provided as parameters to cause damage or harm.
2) It is not simple. E.g. how should reflection be made aware of the fact that an object, when used in a particular context, is suddenly "const"?
> that has its use, especially when designing interfaces and > extending classes. You can then make sure the the object has to abide by > the rule that the class can only read some of its input data and not > change the state of other parts of the system. You work from the assumption that a called method has to make certain guarantees regarding its usage of the provided parameters. I work from the assumption that when someone provides me with an object, I (the called method) can do with it whatever it likes to do with it. If the caller doesn't want this to happen, he should better not provide me with that object, or should provide a robust object.
> To me, its an extension > of the encapsulation/modularisation principle. Under my assumption, if you want to protect your object, just don't give it to "me". This has nothing to do with encapsulation or modularization.
Encapsulation is information hiding and separation of concerns. A mutable object can still hide as much information as it likes to hide. And it still deal with its particular concerns as much as it likes.
Modularization means you have composed your application of different parts with well defined interfaces. An object supposed to represent a module of your application is still a module, whether mutable or temporarily immutable.
/Thomas
 Signature The comp.lang.java.gui FAQ: ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/
marcwentink@hotmail.com - 22 Mar 2006 15:33 GMT Thomas:
> I do not assume that a called method maliciously or randomly calls the > methods of the objects provided as parameters to cause damage or harm. Then you are assuming you or another programmer coding the function never make mistakes? A wild compare: You can also do without type checking and assume the calling function should know the type of the parameter and not do something maliciously to damage them. No programmer has this intention, but the damage could happen anyway since no code is ever perfect. Hence the const concept for me is a convenient check I am used to. You can have your own preferences of zuorce
Thomas Weidenfeller - 22 Mar 2006 16:38 GMT > Then you are assuming you or another programmer coding the function > never make mistakes? Programmers make mistakes all the time. This is part of the game. But how often does it happen that one accidentally calls the wrong method of an object which shouldn't be called? And how is that different from any of the other hundreds of mistakes one can make when implementing a desired algorithm?
Why do people only ask for guarantees for that particular mistake, but not for others? You anyhow have to test your code, so what?
> A wild compare: You can also do without type > checking and assume the calling function should know the type of the > parameter and not do something maliciously to damage them. Which is what languages like Perl do. I haven't heard of an outcry from the Perl community to get this changed. And I don't think it has any influence on the quality of Perl programs (there are other big factors ...).
The same for Java. I haven't seen any serious data which can prove that the availability of a const qualifier in Java would in any way improve the average quality of Java applications.
There is also much to rant about the way C/C++ implement const. You can cast it away. How much protection is that? You think a method/function guarantees they it will not touch your object, but your object's state gets silently changed. Great :-(
But don't worry. A few more Java language iterations and Java will be almost indistinguishable from C++. C++ just with a GC. We just got generics (yes, I know, they are not templates, but they are as bad). I bet someone is already working on sneaking operator overloading into Java, and some bored engineer is for sure also thinking about bolting const onto the language. equal bad
/Thomas
 Signature The comp.lang.java.gui FAQ: ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/
marcwentink@hotmail.com - 22 Mar 2006 16:54 GMT > Which is what languages like Perl do. Exactly!
> I haven't heard of an outcry from > the Perl community to get this changed. So? If they like C type checking they could use C, right? It's just what you are used to, and what your personal flavour is.
> But don't worry. A few more Java language iterations and Java will be > almost indistinguishable from C++. C++ just with a GC. I do not worry, nor do I want Java to be more like C++. There are a few concepts in C++ I am familiar with, and because of that I probably like them. In java there are probably other features and other possibilities which I will start to like if I have programmed in java a little more.
tom fredriksen - 22 Mar 2006 18:20 GMT > The same for Java. I haven't seen any serious data which can prove that > the availability of a const qualifier in Java would in any way improve > the average quality of Java applications. No but it can make code simpler or make it faster to create the code, and that is data you wont have since it is not possible to do java.
/tom
tom fredriksen - 22 Mar 2006 15:40 GMT > And here I disagree. > [quoted text clipped - 5 lines] > I do not assume that a called method maliciously or randomly calls the > methods of the objects provided as parameters to cause damage or harm. Consider the following scenario:
You are designing a library with certain interfaces, some of the objects and its methods need some data of type TypeX and will use some methods on TypeX to get that data. Later on someone comes along and wants to use your library, and comes across the object interfaces which asks for parameters of TypeX. If the programmer sees that the interface method is defined with a const parameter, he immediately knows that the library is not intending to change the object, just read some data. If the interface has both get and set methods and no const, you can not be certain about it. So the choice then is to, either design an object of the type that is immutable or clone the object. Those kind of actions takes time in programming and in runtime. Would it not be easier to just be able to say that for this interface and context certain parameters are const?
In other words there are scenarios where it is valuable, but it can also be solved by other means. Depending on the situation, not necessarily as easy or as good a solution. Of course there might be a possibility that const does not have as much value in java as in C++, I have not decided yet. I am leaning towards it having some value in both languages.
> 2) It is not simple. E.g. how should reflection be made aware of the > fact that an object, when used in a particular context, is suddenly > "const"? Sorry, I meant easy. (language confusion)
The same way it knows if a parameter is final. Its the class using the the object that decides, not the class sending the object. i.e. in class C's declaration of method M, parameter P is const and of TypeX.
/tom
marcwentink@hotmail.com - 22 Mar 2006 15:19 GMT Thomas:
> First, one often doesn't need something like const Hey? You never need const. C++ code without const is compiled to the same object code then comparable source code with const. So all code with const, can be written without const. I just think it's convenient. A sort of extra type checking at compile time. But I can live without it too. It's probably what you are used to, that has your preference.
Timbo - 22 Mar 2006 11:13 GMT >>What are "input en output method function parameters"? > [quoted text clipped - 11 lines] > Node goes "in" and Elem comes "out". Is there something simular in > java? Output parameters, as you want them, don't exist in Java. For example, if you have the following:
HandleElement( ElementType Elem, NodeType Node) { elem = null; }
and then: ElementType elem2 = new ElementType(...); HandleElement(elem2);
The value of 'elem2' after the call to 'HandleElement' is the same as it was before the invocation. The reference pointing to 'elem2' remains the same. You will need to provide an adaptor, or use something like an array for an output parameter.
tom fredriksen - 22 Mar 2006 12:20 GMT > Output parameters, as you want them, don't exist in Java. For example, > if you have the following: [quoted text clipped - 12 lines] > same. You will need to provide an adaptor, or use something like an > array for an output parameter. This means that the reference can not change but the object can, so if you pass in an object you can modify that object and the changes will appear outside the method. That's the only out type parameter there exists in java. You could of course use, similar to what timbo writes, use a sort of double indirection. Which in java basically is a reference to an array or collection. The array or collection can then hold other objects, which you fill with reply data objects if need be.
/tom
Chris Uppal - 22 Mar 2006 11:07 GMT > Is there a way to distinguish between input en output method function > parameters in java, like there is in C# and C++? Something like const > in C++? No.
Indeed, since Java has neither pointers-to-variables, nor what C++ (mis)calls "reference" parameters, it doesn't really have "output" parameters at all.
-- chris
janek - 22 Mar 2006 11:11 GMT marcwentink@hotmail.com napisał(a):
> Is there a way to distinguish between input en output method function > parameters in java, like there is in C# and C++? Something like const > in C++? > > Marcus Wentink final
Timo Stamm - 22 Mar 2006 11:02 GMT janek schrieb:
> marcwentink@hotmail.com napisał(a): >> Is there a way to distinguish between input en output method function [quoted text clipped - 4 lines] >> > final final ist not the equivalent of const
marcwentink@hotmail.com - 22 Mar 2006 11:20 GMT > final I know final but I think that is not what I am looking for. As for as I know final makes a variable unchangeble after his first assignment, and I do not know if you can use it for parameters. (You can use it for functions, but then it has a total different meaning, you cannot override the function.)
With const I can make this code in C++:
MyType MyVar; // changeble variable
Function(MyVar) // where the definition of Function says: Function(const MyVar&) // hence I know in this statement MyVar does not change
MyVar.Change(); // and here I do change is, since I do not define Change() as a const member function.
Bij de weg: Mr. Stamm gave some info on it which was uswble
Marcus Wentink
Thomas Weidenfeller - 22 Mar 2006 11:48 GMT > final Final has nothing to do with const. It is a different concept. You can't protect the object behind a final reference.
/Thomas
 Signature The comp.lang.java.gui FAQ: ftp://ftp.cs.uu.nl/pub/NEWS.ANSWERS/computer-lang/java/gui/faq http://www.uni-giessen.de/faq/archiv/computer-lang.java.gui.faq/
Roedy Green - 22 Mar 2006 20:41 GMT On Wed, 22 Mar 2006 11:48:12 +0100, Thomas Weidenfeller <nobody@ericsson.invalid> wrote, quoted or indirectly quoted someone who said :
>Final has nothing to do with const. It is a different concept. You can't >protect the object behind a final reference. I would hazard a guess that less than 50% of C++ programmers can use const to do that. And the other 50% will just remove it when it stops them from doing what they want.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Roedy Green - 22 Mar 2006 20:29 GMT On 22 Mar 2006 00:46:31 -0800, "marcwentink@hotmail.com" <marcwentink@hotmail.com> wrote, quoted or indirectly quoted someone who said :
>Is there a way to distinguish between input en output method function >parameters in java, like there is in C# and C++? Something like const >in C++? In java, all parameters are input. There is no pass by value. There are no output fields. Only the result is an output.
Unfortunately, there is no way to pass as object to a method temporarily locking all its fields other than by making the object immutable with no accessible modifier methods.
In practice, you can do this by passing an interface reference to your objects with only immutable methods. In theory, the method could cast it back to the corresponding object and change the fields, but that would be malice. You are trying to protect against accidental changes, not malicious ones, most of the time.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Thomas Hawtin - 22 Mar 2006 22:11 GMT > In practice, you can do this by passing an interface reference to your > objects with only immutable methods. In theory, the method could cast > it back to the corresponding object and change the fields, but that > would be malice. You are trying to protect against accidental changes, > not malicious ones, most of the time. I could imagine pre-generics code putting the object into a collection, then casting elements back to the mutable interface.
And of course if there are malicious people like me about, then you might want to protect against abuse.
Tom Hawtin
 Signature Unemployed English Java programmer http://jroller.com/page/tackline/
Roedy Green - 23 Mar 2006 02:16 GMT On Wed, 22 Mar 2006 21:11:35 +0000, Thomas Hawtin <usenet@tackline.plus.com> wrote, quoted or indirectly quoted someone who said :
>I could imagine pre-generics code putting the object into a collection, >then casting elements back to the mutable interface. That could be completely legit. You just don't want the container mucking about with your objects in any way.
This topic of just how much computers should block you from your folly reminds me of a scene in the movie The Gods Must be Crazy where a man manages by misadventure to winch his Land Rover high into a tree. His trusting, faithful sidekick comes over and asks, "Boss, why did you do that?"
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
marcwentink@hotmail.com - 23 Mar 2006 09:41 GMT > In practice, you can do this by passing an interface reference to your > objects with only immutable methods. Thanks, that is a very interesting suggestion. Brilliant I must say. Hence I define a method that excepts an immutable interface (implemented by the object-class), and in calling the named method I cast (if that is the word in java) the object to the immutable interface to pass it to the method. Right?
Jean-Baptiste Nizet - 23 Mar 2006 14:47 GMT You don't even have to cast it since the object implements the interface.
Example:
/** * Immutable interface */ public interface Foo { int getBar(); }
/** * Implementation of Foo. The objects are mutable, but when they are passed as * instances of the immutable interface, the receivers don't know that they are and can't * modify the state of the object without knowing the implementation and casting. Only * malicious code would do that */ public class FooImpl implements Foo { private int bar; public int getBar() { return this.bar; } public void setBar(int bar) { this.bar = bar; } }
/** * Class to be extended. It can pass instances of FooImpl as Foo instances without * problem, since the subclass will only have access to the immutable interface of the * mutable object */ public abstract class ClassToBeExtended { protected abstract void overrideMe(Foo f);
public void blah() { FooImpl f = new FooImpl(); overrideMe(f); } }
Roedy Green - 23 Mar 2006 18:38 GMT On 23 Mar 2006 00:41:08 -0800, "marcwentink@hotmail.com" <marcwentink@hotmail.com> wrote, quoted or indirectly quoted someone who said :
>> In practice, you can do this by passing an interface reference to your >> objects with only immutable methods. [quoted text clipped - 4 lines] >cast (if that is the word in java) the object to the immutable >interface to pass it to the method. Right? There is no cast necessary. You just pass raw references of either type ThatInterface or SomeTypeThatImplementsThatInterface to the method.
The method declares the parameter to be of type ThatInterface. Then so long as it does not cheat with a cast to something else that has mutability methods, it can't accidentally modify the object.
This is standard procedure, documented at http://mindprod.com/jgloss/immutable.html
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|