Operator new factories - Java SE (Archived)

Proposal:
Add support for overloading the operator new. This proposal specifically rejects general operator overloading.
Rationale:
Many systems start small and grow large over time. Often, the initial phases have relatively little formal architecture or design, thus the most simple approach is taken. For example, object creation is performed using new
Person person = new Person();
As the system grows, architecture can become more advanced, requirements can change, and there may be a need to change a class to a singleton, or pool instances, or otherwise share. But the only way to do this at present is to change everywhere where new is used to a static factory method.
Person person = Person.createPerson();
This is a potentially huge change, and either involves messy deprecation, or breaking the code. The JDK has examples of this - consider new Boolean().
Change:
The Java language should be changed to support operator overloading of the new keyword, that can return an alternative object instead of instantiating one if required. Thus:
Person person = new Person();
is changed by the compiler to
Person person = Person.new();
if there is a static method called new()
Note that the method name new() must return a non-null object of the type Person. If 'new Person()' is called in there then the compiler substitution does not occur.
Summary:
General operator overloading is evil as you can change + to be - or some such. Operator new factories is a much more restricted case that deals with a common, and hard to work around, business scenario.

So has no one had a problem needing to change instantiation to factories?

It seems you would need some sort of restriction.  PErson itself would have to become uninstantiatable.  If its not, consider this code someone could write:
public class Person {
    public static Person new() {
        return new Person();  // This causes infinite loop!
    }
}
Instead, one should be forced to delcare Person as abstract so that the commented line above would never compile.
But then what of interfaces?  You wisely state how one could evolve form having as simple Person object to needing a framework, so we'd need a static new method in the base class [b]or interface[/b] for Person.  I don't think static methods are allowed in interfaces today.  Personally, I think they should be; however, even in this case, one could make a narrow rule for allowing static "new" methods in interfaces.

-1
If you use a decent IDE (e.g. IDEA), it can create the factory upon user request and converts all calls to the constructor to use that factory.
Tom

The new Person() within the static new() method creates a 'new' Person exactly as now, calling the constructor.

That assumes that you have access to all the code that calls your code. In large-scale enterprise systems you often don't, because you've distributed your API.

They are not but it can be good feature if we have way to  enforce class to implement static method.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4093687

Changing from instances to a singleton and expecting the code which uses it to still work even with the above means you have probably never made such a change or you made it a singleton for very wrong reasons.
Simply said; if you made an API change as large as this; you will most certainly make code break since the basic behavior will change.  Its best to let the code stop compiling as well.

Well, from time to time, API changes are necessary. This is called Refactoring and a very important part of any project.
I don't think, Java should be changed in that way, that you don't need to change your API.
IMHO, there are only two reasons for changing Java:
- catch often occuring errors at compile time (e.g. const or notnull references) and
- make your intention more clear (e.g. enhanced for-loop in Java 5)
--
Tom

tsinger - I almost agree, but there's other subtle reasons.
A language change may be needed to implement general, simple, straightforward things that you have to write over and over again. Like the enhanced-for loop. Or generics - you're always casting, over and over again.
Also, a language change may make these general, simple, straightforward things simpler (which also makes your intention clear). My favorite pet peeve in java is that whole get/set thing. I wish you could just declare properties. (This may be basically the same as your "make your intention more clear" item).

Just use AspectJ. You know you want to.

+1 
When I was a newbee I looked very hard for an equivalent of the "readResolve" for serialization, but applicable to constructors  ;-)
Cheers
JD

Related

Great idea?  Stupid idea?  You decide

Suppose we added the following rules to the language spec:
If a generic function or a constructor of a generic class has an argument of type Class<T>, where T is one of the type-parameters, that argument become optional, unless doing so would cause an ambiguity with an overloaded function. Any optional function-arguments that are omitted by the calling code are replaced by the compiler with the class object of the type-argument.
Why would we do such a thing? Basically, I want to replace the type-token pattern.      public static <T> T f(Class<T> clazz) { ... }Most of the time, having the programmer specify the type object is redundant. For example:     String s = f(String.class);Even without the String.class, the compiler infers that T means String, it just cannot communicate that fact at runtime to f(). Under my proposal, the programmer could write     String s = f();and it would be the compiler's job to write the same code as the other call.
The upsides are:
1. most of the complaints about type-erasure are resolved
2. existing code using the type-token pattern (the current way of solving type-erasure problem) become easier to use
3. if a calling function wanted to use the type-token, it could:     String s = f(Object.class);which would be equivalent to      String s = MyClass.<Object>f();The downsides are:
1. the implementing code still has to use a type-token; there might be some less burdensome way of conveying the same information.
2. the JavaDocs become a little more complicated
3. I don't know how to handle the nested-generic case, i.e.:     List<String> ls = f();Anyway, comments? 
Given the choice between stupid and great I would not choose great. Then again I have no idea what you are trying to accomplish. You have a default argument when and only when a method parameter is of type Class and it appears in the generic type list for the method. The default value is T.class. Can you explain the purpose? It looks like you want to grant Class arguments magic powers if also specified in the generic type list: namely a default value. 
Given the choice between stupid and great I would not choose great.Hmm, that doesn't leave a lot of choices.
Then again I have no idea what you are trying to accomplish.Then I explained it badly. I am trying to
1. provide a way to record the results of the compiler's type-inference mechanism somewhere it can be found at run-time
2. support a low-rent RTTI (run-time type identification) for generic types
3. fill in some of the holes left by erasure
I think those are really different ways to say the same thing. Let me take a simple, near-real-life example, (from Eckel, at http://www.mindview.net/WebLog/log-0059):public class GenericArrayWithTypeToken<T> {
  private T[] array;
  public GenericArrayWithTypeToken(Class<T> type, int sz) {
    array = (T[])Array.newInstance(type, sz);
  }
  public void put(int index, T item) {
    array[index] = item;
  }
  public T get(int index) {
    return array[index];
  }
}That's fine, except the construction of the object is clumsy:GenericArrayWithTypeToken<String> gas = new GenericArrayWithTypeToken<String>(String.class, 5);Now there's just no need for that String.class. The compiler already knows that T has to be String and the only object that implements Class<String> is String. I'm just saying, the programmer shouldn't have to tell the compiler anything it already knows. So in my system, the code would read:GenericArrayWithTypeToken<String> gas = new GenericArrayWithTypeToken<String>(5);Although I guess we could now pick a more appropriate name for the class.
Notice that I haven't changed the implementation of the class at all, just the rules for calling the constructor.
It looks like you want to grant Class arguments magic powers if also specified in the generic type list: namely a default value.That's the means not the end. But yes, I am saying that since there is (usually) only one possible legal value, just have the compiler use that value as the default.
(The exception to "usually" is in certain kind of type-inference when the Class argument could be T or an ancestor. Among those rare cases, it rarely makes a difference, and even more rarely would the programmer expect anything but the actual behavior.) 
The example Bruce Eckel provides appears to be a technique to work around for the inability to instantiate generic arrays. The first problem I have is that the syntax does not appear clumsy. The second problem is the example you gave is an extremely specialized case. Furthremore, there are all sorts of heuristics that a compiler could apply to provide default arguments but we humans might have trouble trying to analyze programs written in such a language. Finally, you can always use annotations to supply RTTI for norts -- non-reifiable types. 
The example Bruce Eckel provides appears to be a
technique to work around for the inability to
instantiate generic arrays. Yes. But that's irrelevant. It's an example of the Type Token pattern, which is so common with generics that it's in pretty much every tutorial.
The first problem I
have is that the syntax does not appear clumsy. You don't find this clumsy? Perhaps you have a 30" wide display :)
GenericArrayWithTypeToken<String> gas = new GenericArrayWithTypeToken<String>(String.class, 5);Seriously though, this line of code mentions String 3 times. The first two are necessary but the 3rd is purely a workaround for limitations introduced with erasure. If we can remove the need to specify it, surely we should consider it? (It's the Don't Repeat Yourself principle)
The
second problem is the example you gave is an
extremely specialized case. No, it isn't. Type tokens are depressingly common.
Furthremore, there are
all sorts of heuristics that a compiler could apply
to provide default arguments but we humans might have
trouble trying to analyze programs written in such a
a language. In general, yes. In this case, no. It's blindingly obvious which type should be inferred.
Finally, you can always use annotations
to supply RTTI for norts -- non-reifiable types.???
How are annotations going to supply RTTI telling me what class a generic type was instantiated with? The line of code above can't even be annotated.
Please give an example.
Personally, I think this idea has merit. Unless someone can show some horrible problems it causes? 
Type Token patternInteresting. I will have to look that up. I have not used generics much so even have no exposure to even some of the more common idioms.
The first two are necessary but ...Kinda my point: adding one extra string does not make it clumsy syntax.
If we can remove the need to specify it, surely we should consider it? Yes but not if the code is not obvious. In other words I personally would rather have explicit self-documenting code than have the compiler make decisions using rules that are not immediately obvious. 
Finally, you can always use annotations
to supply RTTI for norts -- non-reifiable types.Not true. What is being requested is a way for the compiler to supply the RTTI because in a lot of cases it does know the value, its just that the language has no way to specify that we want it passed through. What is important is that the RTTI can be different at every call site, BUT annotations could only usefully specify it on the implementation side. That is you cannot annotate a method invocation (or any) expression, only declarations so annotations are not an option here.
I think of this request as "On Demand" RTTI. That is, the method / constructor demands that RTTI information is required and the compiler supplies it, if the programmer does not supply it specifically.
Most of the arguments I've seen against RTTI are against ubiqitous RTTI. But the fact is we don't normally need RTTI. In the cases where we do need it, passing a Class<T> sort of does the job. Its not complete or pure (you can't pass Map<String,Integer>.class) but normally that doesn't matter because the RTTI is generally used internally with reflection and (in this case) Map.class will do the job for us there, such as constructing an array of the correct type.
Possibly one of the reasons that this sort of automatic generation of a Class<T> argument doesn't get much traction is that with generic methods, the type inference algorithm can infer types that cannot be represented by a Class object. Intersection types are one of these I think. So any such mechanism here would not always work.
That doesn't mean that I don't identify with the "need / want". I just don't think it will happen in the language at least not until it can be done properly, and at the moment it can't be done properly.
One interesting development now on the horizon that may affect how we approach these sort of language needs is project jackpot (see http://weblogs.java.net/blog/tball/archive/2005/06/project_jackpot.html and
http://www.artima.com/weblogs/viewpost.jsp?thread=116895)
Currently jackpot seems to be a static refactoring tool but I imagine that in the future, features that we would now think of as part of the language / compiler, will in fact be features we load into our editor / IDE. The stored source code (which the compiler digests) will be language standard code, but the editor / IDE will recognize patterns in the code and replace it with a simplified view, sort of an enhanced language. You can actually write the code in the enhanced language but when it is saved, it is transformed back into long (pure) form. Each person could have their own set of language enhancements so that the actual code is viewed through their own enhancements. Good enhancements (like good libraries) would become de-facto standards, and might then move into some core set.
Each transformation needs to be lossless and bi-directional, (which quickly rules out all the silly ideas before they see the light of day)
This idea is not new. About a decade ago Richard Gabriel said
In fact, there is no reason that the shorthand mismatch[i]
expression could not be simply an abbreviation for the longhand common pattern.
The programmer could decide which to see and could change either one.
Then if the common pattern version strays too far, it will no longer be abbreviated
(because it can�t be).
http://www.dreamsongs.com/NewFiles/PatternsOfSoftware.pdf page 29
Jackpot might just be the thing that tips the scales and moves this through the continuum from possible to practical and beyond practical to preferable, thereby changing the way we think about language enhancement.
I look forward to that day with anticipation. 
I agree that it would be nice to have a solution to this issue but I'm not sure how this would work.
What would the declaration of the method f() look like in your proposal? Are you saying that there would be some added syntactical sugar that would add a implied parameter clazz? 
What would the declaration of the method f() look like in your proposal?It would look the same:public static <T> T f(Class<T> clazz)It is just that the compiler would recognize the special case and consider the following two lines as identical:String s = f(String.class);
String s = f();M. 
What would the declaration of the method f() looklike in your proposal?
It would look the same:public static <T> T
f(Class<T> clazz)It is just that the compiler
would recognize the special case and consider the
following two lines as identical:String s =
f(String.class);
String s = f();M.Hmmm. If you could somehow identify the parameter as 'implied', I'd be fully on-board. I'm a little leery of invisble code. I know there is already a lot of it in Java, I just think it needs to be very clean if it's added. This seem a little obfuscated.
Again, though, I agree that this is something that should be resolved and this is in the right direction.
Got any ideas for how to declare self-types? e.g. Comparable. 
It would look the same:>> public static <T> T f(Class<T> clazz)Hmmm. If you could somehow identify the parameter as
'implied', I'd be fully on-board. public static <T> T f(#Implied Class<T> clazz) { ... }Welcome aboard.
But I'm not sure if I am. Even tho' I was once, I have a few doubts, but they're mostly purist ones. The pragmatist in me is keen. 
I had another thought. Instead of doing this in certain situations, what if methods and classes were set up to always have the Class Object of the parametric type available. As suggested in this thread, the compiler could generate the code to do this. Then we could use T.class or whatever in the code.
I'm sure this has been thought of before and there is probably a technical of philisophical or practical reason not to do this but it's a thought. 
what if methods and classes were set up to always have the Class Object
of the parametric type available.IIRC I mentioned this to Neal a long time ago, and he said they did try it but it introduced too much overhead. ie, it ran very slowly.
(I'm curious as to why - to me it doesn't sound like it would be much more expensive than the hidden references added to inner classes, or the ubiquitous "this" reference - but what would I know - I didn't actually try it).
That's one reason I like this proposal. It gives much of the benefit, but only when the programmer explicitly asks for it by including a Class<T> parameter. 
what if methods and classes were set up to alwayshave the Class Object
of the parametric type available.IIRC I mentioned this to Neal a long time ago, and he
said they did try it but it introduced too much
overhead. ie, it ran very slowly.Probabably because things like String.class turn into Class.forName calls. You'd think that would be implemented with a HashMap behind the scenes and after the initial classloading, it would be very fast.
(I'm curious as to why - to me it doesn't sound like
it would be much more expensive than the hidden
references added to inner classes, or the ubiquitous
"this" reference - but what would I know - I didn't
actually try it).I'm of the same mind. It may be that we are unaware of something that would be required to implement this.
That's one reason I like this proposal. It gives much
of the benefit, but only when the programmer
explicitly asks for it by including a Class<T>
parameter.What if the code to do this was only created when the T.class call was actually used? 
what if methods and classes were set up to always
have the Class Object
of the parametric type available.thats the ubiquitous solution
IIRC I mentioned this to Neal a long time ago, and he
said they did try it but it introduced too much
overhead. ie, it ran very slowly.and it isn't worth it, BUT that doesn't mean we should "throw the baby out with the bath water".
If we decided this was worth persuing, and we could commit some time to it, there is the licencing and infrastructure available for us to have a bash at implementing it.
But I see a number of difficulties in making this work in the general case.
That does not necessarily mean that a there is not some restricted solution that meets the pragmatic requirements and avoids the difficulties, but I am not convinced.
Here are the difficulties I see at the moment.
1. The compiler knows a Type for T at the call site, but there are many cases where that type is not an instance of Class<?>.
2. - 1.could partly be solved by making the formal parameter (for receiving the type of T) a Type instead of a Class<T>, but Type is not self parameterized as Class is. Type<T> would be useful, but that is not how it is defined, and there might be good reasons for that.
3. Consider this case
class B {
    public static <T> T f(#Implicit Class<T> clazz) { ... }
}
class A<V> {
    V instance;
    A() {}
    void someMethod() {
        instance = B.f();
    }
}B.f() is our example method from the O.P. but I've put it inside a class.
At the call site to B.f() the compiler does infer the type parameter T of the B.f() method, BUT that type is V (the type parameter of A), and so the compiler cannot create a Class<T> in this case, because A doesn't know what Class<V> is.
So what should happen in this case? A compiler error saying that B.f() can only be called when assigning to types not involving type parameters?
But what if A's constructor had an #Implicit Class<V> parameter? we could maybe do it. But just because we have a parameter in the constructor, the compiler doesn't necessarily know if that value is stored in a field, unless the compiler generates that field and the code to store the Class<V> value into it. But if the compiler generates the field, how does the programmer get access to it? (maybe via a V.class syntax?)
4. Even if we limit the #Implicit Class<T> mechanism to constructors, then we would need to enforce that all non private constructors had this parameter (which would then effectively also force this requirement on all generic subclasses)
So I am convinced there is a can of worms here. Whether the can is finite or can be made finite is still an open issue. The fact that the existing Class<T> mechanism used explicitly doesn't "explode" gives me some hope.
If the can is finite, then the question becomes whether such a language feature is justified given that all it really does is reduce the amount of source code? Maybe just using Class<T> parameters explicitly when required as we already do is in fact the best answer.
Anyway, its time I stopped sitting on this fence, my butt is starting to hurt.
Bruce

A question regarding STATIC member.

Hi ya
I just need some clarification regarding 'Static' methods.
A call to a static method is made, independent to the object
being created
My question is:
If static methods have the advantage of not creating/instantiating
the object to which they belong ,why not then create all an entire application using
static methods only.?
Why create classes,instantiate them and call their concerned
interfaces/methods?
Can anyone please answer my question or am I missing out on some point? 
Well, since it effectively removes all the possible advantages of Object Oriented Programming, people don't tend to do that.
If you want to do it like that, write C. 
If static methods have the advantage of not creating/instantiatingthe object to which they belong ,why not then create all an entire application using
static methods only.?
- You could do it, but your application would not be object-oriented; it would be similar to an old-style C or Fortran application.
- Nowadays even C programs are written in object-oriented fashion, and use complicated structures to compensate for the fact that the language does not offer directly object-orientation. For instance, check the code of the OpenSSL library ( a crypto library in http://www.openssl.org ) ; it is written in C but requires you to understand object orientation for using and maintaining it correctly. If OpenSSL was written in Java, the code would be far easier to understand, because the language supports object-oriented programming.
Why create classes,instantiate them and call their concernedinterfaces/methods?
- You are not required to do it. It's a matter of design. If you design your system in a monolithic way you can simply write a program with lots of static classes with static methods and use the good old "structured programming".
"Thinking in Java" Bruce Eckel p. 207
"Some people argue that static methods are not object-oriented since they do have the semantics of a global function; with a static method you don't send a message to an object, since there's no "this". This is probably a fair argument and if you find yourself using a lot of static methods you should probably rethink your strategy.
Here are my thoughts on the subject.
To my mind, the single most important aspect of object oriented development is encapsulation because it allows me to bracket behavior into manageable chunks. Static methods are great when there's a single pathway, or when a functionality sees little use in terms of frequency, but may be needed throughout an application, or when a functionality is fairly simple in terms of aspect.
If you were going to make all of your methods static, why not just make one method with a bunch of loops and such, and while you're at it, make all of your variables public so that they're all visible everywhere you might possibly need them? The reason why not is because it then forces all of the developers to "know" where every thing might be found, and the whole idea of scoping and encapsulation goes out the window.
Just my thoughts. 
If static methods have the advantage of not creating/instantiating
the object to which they belong ,why not then create
all an entire application using static methods only.?Well, you could (depending on the app, of course). But you lose the value of OOP and maintaining individual objects with their respective states.
Why create classes,instantiate them and call their
concerned interfaces/methods?See above.
Can anyone please answer my question or am I missing
out on some point?Check these out...
Object-Oriented Programming Concepts
Object-oriented language basics
Don't Fear the OOP
LOL. Always a bridesmaid, never a bride... :o) 
All right,so using static methods wont take the advantage of the OOPs concepts.
Then why create the concept of static methods ?
Why not stick to the rule that to call a method, you have to instantiate the class.....
All right,so using static methods wont take the
advantage of the OOPs concepts.
Then why create the concept of static methods ?Read the links.
Why not stick to the rule that to call a method, you
have to instantiate the class.....Read the links.
Or think for just a moment that it might be useful to have methods that are not specific to an actual object (SomeClass.getInstance(), Math.pow(), etc.). 
All right,so using static methods wont take the
advantage of the OOPs concepts.
Then why create the concept of static methods ?
Why not stick to the rule that to call a method, you
have to instantiate the class.....if you have a function which translates english into german, then what object should it be attached to? i think the idea of static methods is to have global methods which you need here and then and have the function of being "little helpers". at least thats the way i use them. 
Static methods are great for functions that depend only on the parameters they receive. For instance, utility methods usually are better written as static methods.
The methods of the class java.lang.Math, for instance, only depend on their parameters (Math.sqrt, the square root, only depends on "a":
static double sqrt(double a)
          Returns the correctly rounded positive square root of a double value. It will be very wasteful if you needed to instantiate an object of the class java.lang.Math only for calculating a square root. 
edsonw, thats it! your explanation is the best one! 
Something that is naturally an "object" usually has internal state (data) to maintain. Something that is naturally a static method usually applies to external data.
The Math class doesn't try to maintain any state - so it doesn't need an instance. You could implement it as a class instance, but that wouldn't actually provide you with any additional functionality. Compare:
Math math = new Math();
double s = math.sin(1.0);versus:
double s = Math.sin(1.0);The latter is slightly less effort and (as it happens) requires less memory. On the other hand, the StringBuffer object very definitely has state. Compare:
char[] text;
text = StringBuffer.append(text,"Hello");
text = StringBuffer.append(text," World");versus
StringBuffer text = new StringBuffer();
text.append("Hello");
text.append("World");The essential difference between these two examples is that the Math methods apply to external data and Math does not maintain internal state, whereas StringBuffer applies to its internal state and is not usually applied to external data.

Passing Class<T> to a generic MyClass<T>'s constructor

I have a class like this:
class MyClass<T> {
    Class<T> theClass;
    MyClass(Class<T> theClass) {
        this.theClass = theClass;
    }
}This would require the following code to instantiate:
MyClass<String> myClass = new MyClass<String>(String.class);Correct? This is the simplest syntax for creating the class? It seems redundant to have to pass the type "String" twice when constructing the class. I understand constructors can have type parameters like methods, but that type parameter doesn't translate the T parameter to the class, so that won't work.
I tried the following solution:
class MyClass<T> {
    Class<T> theClass;
    MyClass(Class<T> theClass) {
        this.theClass = theClass;
    }
    public static MyClass<T> create(Class<T> theClass) {
        return new MyClass<T>(theClass);
    }
}This allows for the syntax:
MyClass<String> myClass = MyClass.create(String.class);Which seems more elegant. Of course, the obvious problem with doing this is that it makes subclassing of MyClass much more difficult. Sometimes I can get away with this workaround, more often I cannot. Have I missed anything? 
A great idea.
But this doesn't quite work because the scope of a class's type parameters excludes static members of the class. So you can't use T inside the static method.
However this is easily fixed, by making the static method parameteric, and so the type argument is infered at the call site and your example creation syntax works as intended.
Here is a version that compiles correctlyclass MyClass<T> {
    Class<T> theClass;
    MyClass(Class<T> theClass) {
        this.theClass = theClass;
    }
    public static <U> MyClass<U> create(Class<U> theClass) {
        return new MyClass<U>(theClass);
    }
}This is a useful mechanism to get around the WET syntax involved with this sort of constructor call.
WET == ! DRY
DRY == Don't Repeat Yourself
Thank-you. 
Actually, it does work, (at least my code works. :) ) but I agree that re-using the variable name T is confusing. 
It seems redundant to have to pass the
type "String" twice when constructing the class.It is in this case but you can instantiate the class without specifying the class at compile time. So the language designers could have handled this one case but it would provide a whole lot of benefit.
Personally, I think letting the syntax drive your design is ass-backwards. I mean in the long term, what difference does it make that you have one more 'String' in your line of code?
On the other hand I don't really see why this makes your class harder to subclass either. 
It is in this case but you can instantiate the class
without specifying the class at compile time. So
the language designers could have handled this one
case but it would provide a whole lot of benefit.that should be 'would not' 
Actually, it does work, (at least my code works. :) )
but I agree that re-using the variable name T is
s confusing.Then you ommited the type parameter from the method.
public static MyClass<T> create(Class<T> theClass) {should have saidpublic static <T> MyClass<T> create(Class<T> theClass) { which does indeed work (for the compiler - but isconfusing most human readers) 
I'm not sure what you're saying with that first statement. Do you mean instantiate the raw type? I thought that was frowned upon. As brucechapman noted, DRY is always better than WET. Personally, I find it distasteful when I have to repeat myself -- for the obvious reason that if you need to make a change you need to make that change in one more place.
I'm not sure how this syntactical construct has any bearing on the designg / object model of my applications.
As for subclassing, I had some problems in the past with two classes, one the subclass of the other, both defining a public static method of the same name. I tried it just now and you're right, it works just fine. 
Whoops, you're right. I posted a simplified case and did forget to include that. 
Personally, I think letting the syntax drive your
design is ass-backwards.On the contrary, when designing an API, I want the code that uses it to be as readable as possible. I want to optimise the amount of that code which is relevant to the problem while minimizing the amount of syntactic baggage. I want the normal use cases to be clean and uncluttered.
If I have two design choices, and one yields a clean and uncluttered use, and a simpler one yields a less clean, more cluttered use, then I am prepared to make the design more complex in order to make the use of it less cluttered. (within reason).
In most cases you are right. there is not much difference, but Occassionally a design will mean that this small amount of clutter gets multiplied. For example because a method has a MyClass... parameter, and the values supplied will probably be constructed inside the method invocation expression.
In those cases, the idiom discussed is a useful one where complexity in the design can help achieve simplicity at the use site.
StringBuffer.append(...) returning this StringBuffer is an example application of this principle. The simpler design would have returned void, but this would clutter the use site. 
I'm not sure what you're saying with that first
statement. Do you mean instantiate the raw type? I
thought that was frowned upon. I need to play around with this and figure out if what I was thinking makes sense.
As brucechapman
noted, DRY is always better than WET.Except for when it isn't. You are adding a redundant method to your class. That is, it doesn't do anything more than the constructor already does.
Personally, I
find it distasteful when I have to repeat myself --
for the obvious reason that if you need to make a
change you need to make that change in one more
place. Let's be real here. We are talking about a single line of code. Not a huge class. You have to change the one if you change the other. There's no danger of one getting left behind.
I'm not sure how this syntactical construct has any
bearing on the designg / object model of my
applications.You are creating a factory method on you class because of distaste for a syntactical construct. You don't see how this factory method changes the design?
Are you going to create this factory method for every class that has this kind of situation? I imagine someone is going to come along later to maintain the code and think "what the..?" 
On the contrary, when designing an API, I want the
code that uses it to be as readable as possible. I
want to optimise the amount of that code which is
relevant to the problem while minimizing the amount
of syntactic baggage. I want the normal use cases to
be clean and uncluttered.I don't see how this makes the code more readable. I think it makes it less understandable.
If I have two design choices, and one yields a clean
and uncluttered use, and a simpler one yields a less
clean, more cluttered use, then I am prepared to make
the design more complex in order to make the use of
it less cluttered. (within reason).I just don't think the constructor idiom is bad enough to waste time writing a factory over.
StringBuffer.append(...) returning this StringBuffer
is an example application of this principle. The
simpler design would have returned void, but this
would clutter the use site.I don't see the correlation to the current subject. What you are talking about is something that is functional. This is purely lexical. 
Let's be real here. We are talking about a single line of code. Not a huge class.
You have to change the one if you change the other. There's no danger of one
getting left behind.I don't agree. The nature of creating a class is that for every class you create, there will be one or more (usually more, sometimes MANY more) users of that class. If it were a class like StringBuffer that is used in a million places, then you are making code less redundant for each one of those use cases, and all you had to do was add a factory method.
You are creating a factory method on you class because of distaste for a
syntactical construct. You don't see how this factory method changes the
design?In a strict sense, yes, it impacts the design inasmuch as adding a method changes the contract of the class. However, I don't see how it makes any practical difference in the design.
Are you going to create this factory method for every class that has this kind of
situation? I imagine someone is going to come along later to maintain the
code and think "what the..?" Yeah, and they'll click on "Go to definition" in their IDE and see the extremely complicated method:
public static <U> create(Class<U> theClass) {
    return new MyClass<U>(theClass);
}If they can't understand that, they don't understand generic code and probably shouldn't be mucking around there anyway. 
Dubwai,
In most cases I agree with what you are saying.
Certainly this idiom is no silver bullet and to apply it everywhere would be stupid.
However, It is another design option, and sometimes (probably rarely) it will be better than the other options.
In other cases, the requirements might suggest a factory for other reasons, in which case the idiom can be applied when the gain in simplicity wouldn't be enough to justify the inclusion of a factory for that reason only.
I am saying this idiom will occasionally be useful. You seem to be implying it will never be useful. 
I don't agree. The nature of creating a class is
that for every class you create, there will be one or
more (usually more, sometimes MANY more) users of
that class. If it were a class like StringBuffer
that is used in a million places, then you are making
code less redundant for each one of those use cases,
and all you had to do was add a factory method.You mistunderstood. The reducancies always are on the same line. The problem with redundancy is when it is spread out across disparate parts of code such that you can change one part and not the other. This doesn't fall into that category. All this 'solution' does is save keystrokes (maybe.)
In a strict sense, yes, it impacts the design
inasmuch as adding a method changes the contract of
the class. However, I don't see how it makes any
practical difference in the design.That's actually the worst part about it. It doesn't really do anything. It's extraneous.
Yeah, and they'll click on "Go to definition" in
their IDE and see the extremely complicated method:
public static <U> create(Class<U> theClass) {
return new MyClass<U>(theClass);
}
If they can't understand that, they don't
understand generic code and probably shouldn't be
mucking around there anyway.No, I mean when they go and look at the factory that does nothing useful, they will say 'what the ...?" 
I am saying this idiom will occasionally be useful.
You seem to be implying it will never be useful.The only thing I can see that this is useful for is saving keystrokes. I'm not big on saving keystrokes. I've never had a keyboard wear out on me.
If you can how this is otherwise useful, I'll be willing to consider it so.

Proposals for adding method support to Java?

Hi,
Near the end of this presentation Graham Hamilton discusses the possibility of adding method support to Java for Dolphin.
The Next Releases of the Java Platform by Graham Hamilton
See 35. Many other Dolphin candidates...
http://wiki.javapolis.com/confluence/display/JP05/The+next+releases+of+Java
Does anybody have any information about what options are being considered?  Would anybody like to share a proposal?
Thanks,
Curt
allright, Im intrigued.  What do you mean by adding method support to Java? :)
leouser
The presentation talks about some sort of langauge support for method references.  The stated motivation is to make it easier to write GUI event handlers, although it is easy to see how just about any language construct added for such a purpose could have other uses.
So, this might mean something like delegates.  No matter what it means, I would like to know what options Sun is looking at.  I have some ideas about what I would like to see, but I would rather see what Sun is considering than subject everyone to my half-baked proposals.
About Microsoft's "Delegates"
http://java.sun.com/docs/white/delegates.html
The Truth About Delegates
http://msdn.microsoft.com/vjsharp/productinfo/visualj/visualj6/technical/articles/general/truth/default.aspx
A Java Programmer Looks at C# Delegates
http://www.onjava.com/pub/a/onjava/2003/05/21/delegates.html
Strongly Typed Java Delegates
http://weblogs.java.net/blog/alexwinston/archive/2005/04/strongly_types_1.html
oh yes, add function pointers to Java!
Makes it SOOOOO much simpler to understand what you're working with, NOT!
As far as I'm concerned anyonymous classes make the delegate concept completly redundant. What's the difference between a class creating a delegate on one of it's fuctions and createing an anomymous class instance that defines a method which [i]calls[/i] that method?
My next questions before trying to evaluate this is:
1. What's a good syntax for expressing a Method Reference
2. How does a Method Reference affect the reference to the parent widget?  Does it up the reference count by 1 or does it function not in this manner?  Similiar to that I find myself wondering how much clarity will be sacrificed by having references to Methods... how would you tell who the parent object is?
I know in python that you can pass methods around and such.
Say in jython you can do this:
a = swing.JButton("Hi")
a.actionPerformed = self.methodThatPrintsHi
methodThatPrintsHi would be a method in this case.  I think you can use functions as well.  When I did Tk programming, the passing of a function was the way to do it.
leouser
Since Java already has method references, I'm guessing that a more typesafe way of constructing them is being considered.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Method.html
There are several methods on java.lang.Class like this one:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getDeclaredMethod(java.lang.String,%20java.lang.Class...)
So, code like this is already quite possible:
Method method = null;
try {
    method =
        Foo.class.getDeclaredMethod("setBar",Bar.class);
} catch (NoSuchMethodException nsme) {
   // do whatever
} catch (SecurityException se) {
   // do whatever
}
Whether or not the exceptions will be thrown can often be determined at compile time, which would enable something like this:
Method method = Foo.setBar(Bar bar);
I have no information if this bears any relation to what is being considered.  I just would like to know what is being considered.  Perhaps this already published somewhere.  If so, I'm asking for a pointer.  If not, I'm suggesting it should be published.
If you go read Neal Gafter's blog, you may come to the same conclusion that I did.  It can be really hard to get community support for the final product even if you're relatively open all the way.  The sooner Sun can involve the community the better. 
http://gafter.blogspot.com/
I second soupdragon, we already have anonymous inner classes. If you want you can use introspection too.
I seriously hope that Sun is not going to add method pointers, as Java started it out as a thing that threw away all the unneeded, cluttering and hard-to-control features of C++, but as time goes on it is re-adding them, one by one... :-(
It certainly is possible to write a more enhanced version of Method in Java already.  I put some classes together over in the Collab project that essentially makes it simple have a Runnable(or Callable) call a method without having to define a new Runnable each time you want to execute a method on say the EDT Thread for example.  I suppose another class could be created from the base class and just act as an EnhancedMethod, or a MethodReference class.  So I think it is possible already to build machinery out of what exists without adding stuff to the language.
I guess a disadvantage of the reflective class approach is that you probably will get a better compiler check if it was part of the language.
leouser
Not only does this make things safer (type-safe), it makes things more efficient (since most of the type checking is done at compile time). Also this makes Java functions, first-class entities (to some extent), which basically means we can do a whole lot of cool stuff that was not efficiently possible before.
Hint: functionalj.sf.net
And NO, this does not make things more complicated, in fact it makes coding simpler. Neither does it overlap in functionality with anonymous inner classes. Use an Anonymous Inner class when you want to transfer "state" along with "actions" and use these Functions when you only want to transfer "actions".
Now all that's missing are Tuples and multiple dispatching functions (methods). It would make OO development a whole lot easier, and not to mention a whole lot more fun.
one concern I have at this moment is that if you have a method reference how will you be able to tell what it is?  Obviously you will need a special type for it, but I hope it wont be something as generic as Object.
The gizmo Im envisioning is something like:
method List.iterator li = //somehow get the method reference
this is more verbose than regular declarations, but how else can you convey everything you'd want to know?
thoughts folks?
leouser
hmmm, one problem with this:
method List.iterator it =//get a method reference somehow
is that it doesn't make overloading clear.  If we have 2+ methods that are iterator in some sense, which of those does it call?  One potentially, screwy, way of dealing with this is having the overload determined at call time, so method references could function as some form of pointer to groups of functions. yeash... :D
leouser
Why should the method be tied to a specific class?
Why not..:
(void):Iterator it = List.iterator;
where (void):Iterator denotes a method that takes no arguements and returns an Iterator. =/
similarly..
(int, int):int min = Math.min;
"min" takes two int's as arguments and returns an int.
I dunno.. i guess it's just a possibility..
I guess its best to not leave it half baked.. So we need anonymous method/functions,, aka lamda expressions or closures..
(int, int):int add = (int a, int b):int {return a + b;};
now... get rid of the semi-colon if it's the only statemen t and add a little type inferrencing to make it cleaner:
(int, int):int add = (int a, int b) -> {return a + b};
probably even better written as:
(int, int):int add = (int a, b) -> {a + b};
(if only one statment, return is implied)
where (int a, b) is a tuple of two int's... the -> is an inject/binding operator. any tuple bound to a block is basically an anonymous method notation.. :P
ok so maybe i'm taking this too far.. but to whatever reasonable level this can be implemented and in which ever manner.. we'd appreciate it.. right? :)
Message was edited by: rizzix
one reason I would want the method to be tied to a specific class is that you operate with the method's contract, not just the method itself.
because methods share a name and a list of parameters doesn't tell us what its contract is.  You need that information to do sensible programming.
That doesn't preclude using higher level classes in my mind.  So instead of needing to do stuff like:
ArrayList.iterator you could have the reference be
List.iterator.
My guess is your (int, int, int) may be a way to deal with which method is being referenced.
method Thing.doSomthingImportant(int, int, int) a = AThing.doSomethingImportant;
I suppose that would be enough information for the compiler to determine which method is being referenced.   Since so much info is in the reference, maybe just having the object would do to get the method:
method Thing.doSomethingImportant(int, int, int) a = AThing;
then Id hope the calling the method would be a simple manner of:
a(1,2,3);
//probably need some way of controlling what was called in this situation if there was a conflicting method called 'a'.  You could force it to use 'this', in this case.
I suppose you could drop the method keyword, or would that confuse the reader into thinking he was reading a method declaration?
Thing.doSomethingImportant(int, int, int) a = AThing;
hmm, this is kinda fun isn't it? :D
leouser

Static method variables

I know Java doesn't support static variables that are local to a function. Is there any particular reason why this is?
I know that it's just syntatic sugar for an instance variable, but the scoping is a bit tighter, so it can occasionally come in handy. 
I suppose that they're not present because they're not needed--they don't add anything that useful. C/C++'s static local variables maintain state. In Java, we have member variables for that. There's no need to add another feature, more clutter, more complexity to the language for minimal gain.
Just my $0.02. 
I threw "why no local static in java" at the Google oracle and got this:
http://groups.google.co.uk/group/comp.lang.java.programmer/browse_thread/thread/729fd528c95f2218/5401caecfe1b0487%235401caecfe1b0487
It doesn't add anything much to what you (and jverd) have said - except the point
that this usage began in C where functions weren't methods of objects that
could give them state - but it might be worth a read if you are thinking about this
question. 
Well, they're not strictly necessary--but they can be useful. For example, suppose you are doing network IO, and you don't necessarily know if you're received a complete line yet. The (hypothetical) processInput() function might want to store some internal state (i.e. the line so far) that the rest of the class has no need to know about. It's not necessary, but it is nice.
Yes, it's your class, and so you should know you shouldn't be mucking with that variable outside processInput(), but being able to tightly define the scope when a member variable should be valid is a nice convenience. And I believe the clutter that would be added would be minimal. 
If I want method local fields, I do two things.
- place the definitions with the methods instead of at the top. With a comment as to why.
- use the method name in the variable.
e.g.
public class MyClass {
   private final String name;
// later.
    // Only used for method method1
    private long nextId$counter = 0;
    public synchronized String nextId() {
       return name + '-' + nextId$counter++;
   }
} 
Static is a really poor name
Of all the many poorly chosen names in Java, "static" is the worst. The keyword is carried over from the C language, where it was applied to storage which can be allocated statically (at compile time). Whenever you see "static" in Java, think "once-only" or "one-per-class."
I also agree with this. Java only do this in order to make somethings different from MS world.
So if this static keyword was valid for also method scopes, would not it increase the efficiency and performance ? Of course Yes.
So why ? 
Well, they're not strictly necessary--but they can be
useful. Yes, but their usefulness is not that great, and was apparently deemed not great enough to make it worth the additional language complexity.
I programmed in C for many years, and I have not once found myself wishing Java had static locals. 
Static is a really poor name
Of all the many poorly chosen names in Java,
"static" is the worst. The keyword is carried over
from the C language, where it was applied to storage
which can be allocated statically (at compile time).
Whenever you see "static" in Java, think "once-only"
or "one-per-class."Static also has an "at compile time" meaning in Java. For instance, static methods are bound at compile time, while instance methods are not.
So if this static keyword was valid for also method
scopes, would not it increase the efficiency and
performance ? Of course Yes.
So why ?You're making no sense (as usual). 
Static is a really poor name
Of all the many poorly chosen names in Java,
"static" is the worst. The keyword is carried over
from the C language, where it was applied to storage
which can be allocated statically (at compile time).
Whenever you see "static" in Java, think "once-only"
or "one-per-class."
I also agree with this. Java only do this in order to
make somethings different from MS world.
So if this static keyword was valid for also method
scopes, would not it increase the efficiency and
performance ? Of course Yes.
So why ?Um. Ok, I don't quite know what you're trying to say. No, it wouldn't increase efficiency or performance. The only reason it would be nice is that it provides a tighter scope for variables that can occasionally prevent you from shooting yourself in the foot.
Yes, it adds clutter. But it's still nice. And you're not forced to use it. There are times when a function you call in a loop doesn't complete all of its work and has to save some internal state. Sure, you can call it myMethod$stateVariable, but that's not particularly nice or abstract. The stateVariables should conceptually be encapsulated by myMethod.
Besides. Java's not exactly simple once you get into the nitty, gritty details (see the JMM, among other things). 
Um. Ok, I don't quite know what you're trying to say.
No, it wouldn't increase efficiency or performance.
The only reason it would be nice is that it provides
a tighter scope for variables that can occasionally
prevent you from shooting yourself in the foot.
Yes, it adds clutter. But it's still nice. And you're
not forced to use it. There are times when a function
you call in a loop doesn't complete all of its work
and has to save some internal state. Sure, you can
call it myMethod$stateVariable, but that's not
particularly nice or abstract. The stateVariables
should conceptually be encapsulated by myMethod.
Besides. Java's not exactly simple once you get into
the nitty, gritty details (see the JMM, among other
things).Using static keyword provide you to allocate less memory space if we use it for properties, is not it ?
So suppose that the same situation is valid for also method's properties. Whe we call the same method times and times, the properties of that method is only created one time while creating that method. So while using it , we use the shared memory spaces, not for each of them.
Is not it regarded as an efficiency or performance powerty ??
Regards,
Mert 
Using static keyword provide you to allocate less
memory space if we use it for properties, is not it
?
o suppose that the same situation is valid for also
method's properties. Whe we call the same method
times and times, the properties of that method is
only created one time while creating that method. So
while using it , we use the shared memory spaces, not
for each of them.
Is not it regarded as an efficiency or performance
powerty ??You are talking about Java, right? Well, I know that you are asking other person, sorry for participating, but, about your reply, I don�t know, I don�t have good knowledges of internal details of JVM. Do you have an authority source that tells that what you wrote is valid? Or would it just be your question, and then you want an answer? 
Using static keyword provide you to allocate less
memory space if we use it for properties, is not it
?
o suppose that the same situation is valid for also
method's properties. Whe we call the same method
times and times, the properties of that method is
only created one time while creating that method. So
while using it , we use the shared memory spaces, not
for each of them.
Is not it regarded as an efficiency or performance
powerty ??It's hard to undertand what you're trying to say, but it seems to be that "member variables consume less memory than local variables because they're shared." There's some truth to that, but it's not as simple as you're making it out to be. But the point of this thread is not about performance or memory usage. It's about scoping and having code that closely refelcts your design intent. 
Using static keyword provide you to allocate less
memory space if we use it for properties, is not it
?
o suppose that the same situation is valid for also
method's properties. Whe we call the same method
times and times, the properties of that method is
only created one time while creating that method. So
while using it , we use the shared memory spaces, not
for each of them.
Is not it regarded as an efficiency or performance
powerty ??
Regards,
MertNo, the static method variables I'm referring to are something from C. For example, in C you might have something like this:
int inc_tick_count()
{
static int tick_count = 0;
return tick_count++;
}
The static variable is initialized once and then on subsequent calls to inc_tick_count(), it remembers the value from the last execution of the function, so calling inc_tick_count() multiple times would get you 0, 1, 2...
It doesn't actually /save/ space, because that variable still has to be remembered somewhere. Same in Java, if it were to hypothetically be implemented. To reiterate, it doesn't save space, it just provides better scoping for variables... although apparently most people argue that this is not necessary. Eh... whatever. I'll live. =)
Edit:
I did think of encapsulating the offending method in its own class. But while adding another layer of indirection is often a catch-all solution, I feel that it only serves to obfuscate the code.
Obviously, Java went without local statics for a good reason. I was merely curious what reasons from a language design standpoint there would be. While I feel that the reasons that I've seen don't really merit the exclusion of this feature, it's really not that big a deal in the scheme of things. 
Obviously, Java went without local statics for a good
reason. I was merely curious what reasons from a
language design standpoint there would be. While I
feel that the reasons that I've seen don't really
merit the exclusion of this feature, it's really not
that big a deal in the scheme of things.I can't say for sure, but I'd bet it comes down to complexity. You say it won't add "that much more" complexity, but it's probably not as simple as you may be thinking. From a programmer's perspective--one who uses the Java language--the meat of it will probably be pretty simple. But I wold imagine that from a JLS and copmiler perspective, and possibly a VM perspective, it could get somewhat hairy.
If a local were declared static, would there be one copy shared by all method invocations, which basically makes it a class-level variable, but one with a smaller scope? Or would there be one per instance, making it an instance variable, but with narrower scope? Does it matter if the defining method is static or not?
When would the space be allocated?
Would there be a default value, or would it be undefined until first assignment? If there's a default, when is it assigned. (See [url http://java.sun.com/docs/books/jls/third_edition/html/execution.html#12.5]JLS 12.5 Creation of New Class Instances for the kind of stuff you'd have to deal with w.r.t. these variables.)
When, if ever, would an object it refers to be GCed? That is, what are the reachability rules for this variable?
What are the multithreading implications?
All this stuff has to be addressed in the JLS and/or the VM spec. In the end, all you're getting is a class variable or instance variable with limited scope. For that, I just say--it's your class, you should know when it's appropriate to access which variables, and if it's too messy or hard to keep track of, then you should probably refactor.
I think it would be a fundamental shift in the overall Java philosophy if state were kept in methods, instead of just in classes and objects. 
I can't say for sure, but I'd bet it comes down to
complexity. You say it won't add "that much more"
complexity, but it's probably not as simple as you
may be thinking. From a programmer's perspective--one
who uses the Java language--the meat of it will
probably be pretty simple. But I wold imagine that
from a JLS and copmiler perspective, and possibly a
VM perspective, it could get somewhat hairy.It is rather easy.
It would simply be resolved as another static intiatializer by the compiler.
So in effect it would do the following..
       // Code the programmer writes.
        void myFunction()
        {
               static int i = 3;
               i++;
        }
        // Pseudo representation of what the compiler
        // would produce.
        static private int i_$funnyUniqueThing = 3;
        void myFunction()
        {
               i_$funnyUniqueThing++;
        }

Categories

Resources