closures mean fully type-safe criteria? - java

combining closures (FCM) and generics, would it be possible to have fully type-safe criteria.
// The following works without a cast as Foo.id is a 'long' field.
List<Long> ids = session.createCriteria(Foo.class)
.setProjection(Foo#id)
.list();
// The following is a compilation error, as Foo.bar is defined as an int, and not a string
session.createCriteria(Foo.class)
.addRestriction(Restrictions.eq(Foo#bar,"blah"))
.list();
I've read the JPA 2.0 spec for type-safe criteria. But its still somewhat lacking.
Besides, I'm just using criteria here as an example of improving the type-safety of code in general. I used the static typing of java heavily to let me code faster. But as a result I get bitten now and then by the parts of my code that ignore typing. For example HQL queries.

The code you're describing does not use closures but field literals (method literals). Like the good old class literal. These could help in a criteria API. The JPA 2 source code generation work-around for a type-safe query interface could be replaced with it. If it will be part of JDK7.

As Thomas points out, this doesn't strictly require closures. It's all up in the air at the moment, given no-one knows quite what proposal is being looked at. It's not clear if FCM is actually the basis of the proposal, particularly given that Stephen Colebourne seemed to be as susprised as anyone about the announcement.
A lot of people are pointing at Neal Gafter's mysteriously-revised-more-or-less-right-as-the-Devoxx-presentation-announcing-closures-was-being-given spec as a hint as to what form closures might take. Mind you, the revised proposal looks (aesthetically) rather like FCM!
That spec does include the kind of references you refer to (under 'Method References' in the above line), and of course FCM has the same. Yes, this would definitely make you suggest possible. My very first thought when reading about this was how it would affect JPA/Hibernate, and/or our own abstraction layers around same, in this regard. Typesafe, refactorable method references in your criteria? Hell yeah.

Related

Showerthought: Datatype for dataype?

I'm not that experienced with programming, so sorry if this doesn't make any sense. Anyways: Is there a Datatype for datatypes?
This sounds really weird, so here's an example how one could use it:
DataType dt = new DataType("int");
dt i = 3;
double d = 5;
int castedD = (dt) d;
etc.
Eventhough I'm pretty sure the compiler(or interpreter?) makes this kind of syntax impossible, it is quite an interesting idea in my opinion.
Does a similar thing already exist? Sorry again if this doesn't make any sense, I was just wondering if this is stupid or a good idea. :)
Nothing like that is possible in Java. You cannot use a value as a type in Java source code:
The Java language specification states that type names and variable names are taken from different namespaces. So your example code actually tells the compiler look for a class whose name is dt.
If this sort of thing was allowed, Java would no longer be a statically typed programming language.
Now you can do this kind of thing in Java using reflection, but the code is nowhere like as elegant as your (phantasy) code. It is an order of magnitude (or more) slower than conventional Java code, and much more fragile because the compiler can offer you little in the way of error checking.
I can't think of any mainstream programming language (static or dynamically types) that allows variables to be used as types like that. Please comment if you know of one ....

What was Hibernate's CriteriaQueryCompiler replaced with?

Basically I want to use the code this answer gives https://stackoverflow.com/a/19516794 for my project, but compiler is giving me errors. Documentation mentions that CriteriaQueryCompiler is a temporary implementation.
NOTE : This is a temporary implementation which simply translates the criteria query into a JPAQL query string.
A better, long-term solution is being implemented as part of refactoring the JPAQL/HQL translator.
I'm using Hibernate 4.3.9. Is there an analogous implementation of CriteriaQueryCompiler?
use this import,
import org.hibernate.jpa.criteria.compile.RenderingContext;
and then change CriteriaQueryCompiler.RenderingContext to -> RenderingContext in the function parameters.

Interning of non String (non int/long) objects in Java 8

I was going through this documentation from Oracle :https://docs.oracle.com/javase/tutorial/java/annotations/basics.html
And came across this piece of code regarding type annotation
Class instance creation expression:
new #Interned MyObject();
Does it mean Java8 or future versions is-allowing/will-allow interning of non String/long/int objects ?
As far as I know there are no such plans. It's just an example how annotations can be used. I guess it can be implemented by third-party annotation processors like project Lombok, but unlikely we will see such feature in JDK (at least in the near future). Other examples like #Readonly are also just examples, they are not supposed to be added to JDK.
Please note that using String.intern() in the user code is extremely bad. Now it's not so big disaster like it was in JDK6, but it's still bad. You can easily implement your own Object pool using ConcurrentHashMap.putIfAbsent(obj, obj).
This particular annotation seem to originate from Checker Framework—an implementation of pluggable type checking system for Java (which is an amazingly interesting concept by itself). From Checker Framework documentation:
If the Interning Checker issues no errors for a given program, then all reference equality tests (i.e., all uses of “==”) are proper; that is, == is not misused where equals() should have been used instead.
Interning is a design pattern in which the same object is used whenever two different objects would be considered equal. Interning is also known as canonicalization or hash-consing, and it is related to the flyweight design pattern. Interning has two benefits: it can save memory, and it can speed up testing for equality by permitting use of ==.
and a bit below:
#Interned
indicates a type that includes only interned values (no non-interned values).
The Checker Framework is not officially part of Java, but it is developed and promoted by Oracle employees, so it is unsurprising to see this kind of fleeting mentions in Java documentation.
You can read more about the pattern in question in Wikipedia.
Note, that there are proposals for introducing additional semantics for value-only objects in Java, known under name Project Valhalla. If those ever get implemented, internability of objects will become a lot more important.

what are the OOP features which are not in java but c++ has those features?

Respected Sir!
As i have not learnt java yet but most people say that C++ has more OOP features than Java, I would like to know that what are the features that c++ has and java doesn't. Please explain.
From java.sun.com
Java omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. These omitted features primarily consist of operator overloading (although the Java language does have method overloading), multiple inheritance, and extensive automatic coercions.
For a more detailed comparison check out this Wikipedia page.
This might be controversial, but some authors say that using free functions might be more object oriented than writting methods for everything. So by those author's point of view, free functions in C++ make it more OO than Java (not having them).
The explanation is that there are some operations that are not really performed on an instance of an object, but rather externally, and that having externally defined operations for those cases improves the OO design. Some of the cases are operations on two objects that are not naturally an operation of either one. Incrementing a value is clearly an operation on the value, but creating a new value with the sum of two others (or concatenating) are not really operations on the instance. When you write:
String a = "Hello";
String b = " World";
String c = a.append( b );
The append operation is not performed on a: after the operation a is still "Hello". The operation is not performed on b either, it is an external operation that is performed on both a and b. In this particular example, the most OO way of implementing the operation would be providing a new constructor that takes two arguments (after all, the operation is performed on the new string), but another solution would be providing an external function append that takes two strings and returns a third one.
In this case, where both instances are of the same type, the operation can naturally be performed as a static method of the type, but when you mix different types the operation is not really part of either one, and in some cases it might end up being of a completely different type. In some cases free functions are faked in Java as in the Collections java class, it does not represent any OO element, but is rather simple glue to tie free functions are static methods because the language does not have support for the former. Note that all those algorithms are not performed on the collection nor an instance of the contained type.
Multiple inheritance
Template Metaprogramming
C++ is a huge language and it is common for C++ developers to only use a small subset during development. These language features are often cited as being the most dangerous/difficult part of C++ to master and are often avoided.
In C++ you can bypass the OO model and make up your own stuff, whereas in Java, the VM decides that you cannot. Very simplified, but you know... who has the time.
I suppose some would consider operator overloading an object oriented feature(if you view binary operators not much different then class methods).
Some links, that give some good answers:
Java is not pure a OOP language (... but I don't care ;) )
Comparing C++ and Java (Java Coffee Break article)
Comparing Java and C++ (Wikipedia comprehensive comparision)
Be careful. There are multiple definitions of OOP out there. For example, the definitions in Wegner 87 and Booch et al 91 are different to what people say in Java is not pure a OOP language.
All this "my language is more OO than your language" stuff is a bit pointless, IMO.

Is Java fully object-oriented? [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
Java has primitive data types which doesn't derive from object like in Ruby. So can we consider Java as a 100% object oriented language? Another question: Why doesn't Java design primitive data types the object way?
When Java first appeared (versions 1.x) the JVM was really, really slow.
Not implementing primitives as first-class objects was a compromise they had taken for speed purposes, although I think in the long run it was a really bad decision.
"Object oriented" also means lots of things for lots of people.
You can have class-based OO (C++, Java, C#), or you can have prototype-based OO (Javascript, Lua).
100% object oriented doesn't mean much, really. Ruby also has problems that you'll encounter from time to time.
What bothers me about Java is that it doesn't provide the means to abstract ideas efficiently, to extend the language where it has problems. And whenever this issue was raised (see Guy Steele's "Growing a Language") the "oh noes, but what about Joe Sixpack?" argument is given. Even if you design a language that prevents shooting yourself in the foot, there's a difference between accidental complexity and real complexity (see No Silver Bullet) and mediocre developers will always find creative ways to shoot themselves.
For example Perl 5 is not object-oriented, but it is extensible enough that it allows Moose, an object system that allows very advanced techniques for dealing with the complexity of OO. And syntactic sugar is no problem.
No, because it has data types that are not objects (such as int and byte). I believe Smalltalk is truly object-oriented but I have only a little experience with that language (about two months worth some five years ago).
I've also heard claims from the Ruby crowd but I have zero experience with that language.
This is, of course, using the definition of "truly OO" meaning it only has objects and no other types. Others may not agree with this definition.
It appears, after a little research into Python (I had no idea about the name/object distinction despite having coded in it for a year or so - more fool me, I guess), that it may indeed be truly OO.
The following code works fine:
#!/usr/bin/python
i = 7
print id(i)
print type(i)
print i.__str__()
outputting:
6701648
<type 'int'>
7
so even the base integers are objects here.
To get to true 100% OO think Smalltalk for instance, where everything is an object, including the compiler itself, and even if statements: ifTrue: is a message sent to a Boolean with a block of code parameter.
The problem is that object-oriented is not really well defined and can mean a lot of things. This article explains the problem in more detail:
http://www.paulgraham.com/reesoo.html
Also, Alan Kay (the inventor of Smalltalk and author(?) of the term "object-oriented") famously said that he hadn't C++ in mind when thought about OOP. So I think this could apply to Java as well.
The language being fully OO (whatever that means) is desirable, because it means better orthogonality, which is a good thing. But given that Java is not very orthogonal anyway in other respects, the small bit of its OO incompleteness probably doesn't matter in practice.
Java is not 100% OO.
Java may going towards 99% OO (think of auto-boxing, Scala).
I would say Java is now 87% OO.
Why java doesn't design primitive data
types as object way ?
Back in the 90's there were Performance reasons and at the same time Java stays backward compatible. So they cannot take them out.
No, Java is not, since it has primitive data types, which are different from objects (they don't have methods, instance variables, etc.). Ruby, on the other hand, is completely OOP. Everything is an object. I can do this:
1.class
And it will return the class of 1 (Fixnum, which is basically a number). You can't do this in Java.
Java, for the reason you mentioned, having primitives, doesn't make it a purely object-oriented programming language. However, the enforcement of having every program be a class makes it very oriented toward object-oriented programming.
Ruby, as you mentioned, and happened to be the first language that came to my mind as well, is a language that does not have primitives, and all values are objects. This certainly does make it more object-oriented than Java. On the other hand, to my knowledge, there is no requirement that a piece of code must be associated with a class, as is the case with Java.
That said, Java does have objects that wrap around the primitives such as Integer, Boolean, Character and such. The reason for having primitives is probably the reason given in Peter's answer -- back when Java was introduced in the mid-90's, memory on systems were mostly in the double-digit megabytes, so having each and every value be an object was large overhead.
(Large, of course is relative. I can't remember the exact numbers, but an object overhead was around 50-100 bytes of memory. Definitely more than the minimum of several bytes required for primitive values)
Today, with many desktops with multiple gigabytes of memory, the overhead of objects are less of an issue.
"Why java doesn't design primitive data types as object way ?"
At Sun developer days, quite a few years ago I remember James Gosling answering this. He said that they'd liked to have totally abstracted away from primitives - to leave only standard objects, but then ran out of time and decided to ship with what they had. Very sad.
So can we consider java as 100% object
oriented language?
No.
Another question : Why java doesn't
design primitive data types as object
way?
Mainly for performance reasons, possibly also to be more familiar to people coming from C++.
One reason Java can't obviously do away with non-object primitives (int, etc.) is that it does not support native data members. Imagine:
class int extends object
{
// need some data member here. but what type?
public native int();
public native int plus(int x);
// several more non-mutating methods
};
On second thoughts, we know Java maintains internal data per object (locks, etc.). Maybe we could define class int with no data members, but with native methods that manipulate this internal data.
Remaining issues: Constants -- but these can be dealt with similarly to strings. Operators are just syntactical sugar and + and would be mapped do the plus method at compile time, although we need to be careful that int.plus(float) returns float as does float.plus(int), and so on.
Ultimately I think the justification for primitives is efficiency: the static analysis needed to determine that an int object can be treated purely as JVM integer value may have been considered too big a problem when the language was designed.
I'd say that full-OO languages are those which have their elements (classes, methods) accessible as objects to work with.
From this POV, Java is not fully OOP language, and JavaScript is (no matter it has primitives).
According to Concepts in Programming Languages book, there is something called Ingalls test, proposed by Dan Ingalls a leader of the Smalltalk group. That is:
Can you define a new kind of integer,
put your new integers into rectangles
(which are already part of the window
system), ask the system to blacken a
rectangle, and have everything work?
And again according to the book Smalltalk passes this test but C++ and Java do not. Unfortunately book is not available online but here are some supporting slides (slide 33 answers your question).
No. Javascript, for example, is.
What would those Integer and Long and Boolean classes be written in?
How would you write an ArrayList or HashMap without primitive arrays?
This is one of those questions that really only matters in an academic sense. Ruby is optimized to treat ints, longs, etc. as primitives whenever possible. Java just made this explicit. If Java had primitives be objects, there would be IntPrimitive, LongPrimitive, etc (by whatever name) classes. which would most likely be final without special methods (e.g. no IntPrimitive.factorial). Which would mean for most purposes they would be primitives.
Java clearly is not 100% OO. You can easily program it in a procedural style. Most people do. It's true that the libraries and containers tend not to be as forgiving of this paradigm.
Java is not fully object oriented. I would consider Smalltalk and Eiffel the most popular fully object oriented languages.

Categories

Resources