In JPA, why does CriteriaBuilder let me build unsound predicates between unrelated types? - jpa-2.0

I am curious as to why it is possible, with the CriteriaBuilder class of JPA 2, to create such queries. Suppose I have a User class with a persisted String called name as attribute. Why can I write this?
CriteriaBuilder builder = mgr.getCriteriaBuilder();
CriteriaQuery<User> crit = builder.createQuery(User.class);
Root<User> user = crit.from(User.class); // 1
crit.select(user)
.where(builder.equal(user.get(User_.name), 2.5)); // 2
First, at Marker 1: Why must I indicate User.class again? Isn't my CriteriaQuery supposed to know I'm interested in users anyway? Doesn't it break type safety to possibly inject another class here?
Second, at Marker 2: The name property is a String. Why can I compile nonsense like this, comparing a String with a double? In other words, why is the signature of the called equal method this:
public Predicate equal(Expression<?> x, Object y)
instead of a presumably more type safe version as follows?
public <T> Predicate equal(Expression<T> x, T y)
Would other query frameworks like Querydsl provide a better solution to this issue?

I believe the typesafe aspects of the JPA 2 Criteria API were added at a quite late point of the specification process. That's why it doesn't feel consistent.
Querydsl is more concise than the JPA 2 Criteria API and also more typesafe. Querydsl uses fluent builders instead of a factory class for predicate creation, so the equivalent method can be found here http://www.querydsl.com/static/querydsl/2.8.0/apidocs/com/mysema/query/types/expr/SimpleExpression.html#eq%28T%29
I am the maintainer of Querydsl, so this answer is biased.

specific on JPA you can use also Object Query or Torpedo Query(but this is specialized on HQL) that not needs compile time model generation. anyway QueryDsl is one of the first to implement typesafe query

Related

How to create custom matchers in Mockito?

I am using Mockito for unit testing. And there are many matchers like anyString(), anyBoolean() in Mockito. But suppose if I have a custom enum like
Enum LoginType.java
//LoginType.java
public enum LoginType {
FACEBOOK,
EMAIL,
GOOGLE
}
In one of the method arguments I need to pass an instance of LoginType. How do I pass the argument without explicitly passing LoginType.FACEBOOK or LoginType.GOOGLE. Something like anyString(). Any hint in that direction will be useful.
For any behavior, just calling Matchers.any() may be good enough on Java 8. That's when parameter type inference came out.
You might also choose Matchers.any(LoginType.class), which has pure any() behavior in Mockito 1.x but will provide type checking in Mockito 2.0 and beyond. In either case, passing in the class literal will help Java get the type information you need for inference.
For related problems:
If you have a generic type, the class literal isn`t enough either; you need to specify it as an explicit method parameter:
Matchers.<YourContainer<YourType>>any();
...or extract to a static helper method, which you need to do instead of a constant or local variable because Mockito matchers work via side effects:
public static LoginType anyLoginType() {
return Matchers.any();
}
Finally, for future readers who might be here to implement custom matching logic, look for Matchers.argThat or MockitoHamcrest.argThat to adapt a Hamcrest-style Matcher object into a Mockito method call.

Identifying methods with a specified Id in D

I want to have specific methods with a specific pattern recognized at compile time and registered along with a specified id trough mixins in a parent class.
ex.:
take a method 'X' from a class with a predetermined id:5, what I want is that, in a mixin in a parent class, method X will be registered as a delegate with its id to be called later on by its id.
What would be the best way to specify the Id considering I want the id to be of type int and only the specified methods to be registered?
should I (if it is even possible) do it with a custom annotation pretty much like the #property but with an argument, like:
#autoregister(id)
void method(...)
if it is possible to do it this way, an example or a link to the documentation on how to do it would be nice since I didn't find it in the documentation.
if it is not possible I'll use the function's signature as a string instead but I really want to do it with a numeric identifier instead of a possibly quite long string as much as possible.
Making custom annotations is not possible at the moment (but it will be in the future).
However, you can make your own method-naming convention that will allow you to do something similar to what you have described. I do not have time to think deeply how to accomplish this, but I would start with having a method like:
public void id30_doSomething(/* params */) {
// body
}
alias id30_doSomething doSomething;
// finally, lets do something with all these methods
// and generate mixin...
After this you could probably list all methods and find if their names match id([0-9]*)_.*, if so, then you generate mixin to register them in the parent...

Checking function equality in a F# unit test

I have a bunch of F# functions that implement different algorithms for the same input, kind of like the Strategy pattern. To pick the right strategy, I want to pattern match on the input argument and return the function as a value :
let equalStrategy points : seq<double> =
...
let multiplyStrategy factor (points: seq<double>) =
...
let getStrategy relationship =
match relationship with
| "=" -> equalStrategy
| "*5" -> multiplyStrategy 5.0
| _ -> raise (new System.NotImplementedException(" relationship not handled"))
Now I want to write some unit tests to make sure that I return the right strategy, so I tried something like this in nUnit :
[<TestCase("=")>]
[<Test>]
member self.getEqualstrategy( relationship:string ) =
let strategy = getStrategy relationship
Assert.AreEqual( strategy, equalStrategy )
Now I think the code is correct and will do what I want, but the assertion fails because functions don't seem to have an equality operation defined on them. so my questions are :
(a) is there a way to compare 2 functions to see if they are the same, i.e. let isFoo bar = foo == bar, that I can use in an nUnit assertion?
or
(b) is there another unit testing framework that will do this assertion for me in F#?
Testing whether an F# function returned by your getStrategy is the same function as one of the funcions you defined is also essentially impossible.
To give some details - the F# compiler generates a class that inherits from FSharpFunc when you return a function as a value. More importantly, it generates a new class each time you create a function value, so you cannot compare the types of the classes.
The structure of the generated classes is something like this:
class getStrategy#7 : FSharpFunc<IEnumerable<double>, IEnumerable<double>> {
public override IEnumerable<double> Invoke(IEnumerable<double> points) {
// Calls the function that you're returning from 'getStrategy'
return Test.equalStrategy(points);
}
}
// Later - in the body of 'getStrategy':
return new getStrategy#7(); // Returns a new instance of the single-purpose class
In principle, you could use Reflection to look inside the Invoke method and find which function is called from there, but that's not going to be a reliable solution.
In practice - I think you should probably use some other simpler test to check whether the getStrategy function returned the right algorithm. If you run the returned strategy on a couple of sample inputs, that should be enough to verify that the returned algorithm is the right one and you won't be relying on implementation details (such as whether the getStrategy function just returns a named function or whether it returns a new lambda function with the same behaviour.
Alternatively, you could wrap functions in Func<_, _> delegates and use the same approach that would work in C#. However, I think that checking whether getStrategy returns a particular reference is a too detailed test that just restricts your implementation.
Functions doesn't have equality comparer:
You will have error: The type '('a -> 'a)' does not support the 'equality' constraint because it is a function type
There is a good post here
It would be very difficult for the F# compiler to prove formally that two functions always have the same output (given the same input). If that was possible, you could use F# to prove mathematical theorems quite trivially.
As the next best thing, for pure functions, you can verify that two functions have the same output for a large enough sample of different inputs. Tools like fscheck can help you automate this type of test. I have not used it, but I've used scalacheck that is based on the same idea (both are ports from Haskell's QuickCheck)

Categorizing items the right way

I'm working on an application which among other things downloads items that belong to a certain category form a server. I want to make the downloader look like this:
class Downloader
{
Downloader(const ItemCategoryBase &category);
...
}
Each class derived from ItemCategoryBase will provide it's category ID trough a virtual function (in fact that's the only thing each derived class will do).
The issue I'm having is that I have a total of 120 item categories and writing a derived class for each one is going to be painful.
I've considered using a primitive to hold the ID but, I do not wish to implement range checking and throw exceptions in case the ID is out of range mainly because category IDs aren't all part of the same interval.
What I'm looking for is an efficient way of writing code that would fit the scheme above.
Any help is highly appreciated.
If you really have determined that this is the right way to do things, then I would suggest writing a code generator to handle it for you: create a CSV document containing all the Category ID's, and write an app that inserts each ID into template header/source files, and saves it out.. (For instance, put "$CATEGORY_ID" in wherever the Category ID goes in the files, and then just do a replace on "$CATEGORY_ID" with each ID in turn.)
However, I'm not sure I understand your statement: "I've considered using a primitive to hold the ID but, I do not wish to implement range checking and throw exceptions in case the ID is out of range mainly because category IDs aren't all part of the same interval." I can't imagine a case in which you wouldn't have to handle the complexity somewhere in your application anyway, and the range checking wouldn't be hard: just put all the valid Category IDs into a list structure of whatever your ID type is, and a simple index lookup call can answer whether the ID is part of that list.
If I have misunderstood you, what exactly is it about your setup that makes dealing with 120 ItemCategoryBase derived classes simpler than one ItemCategoryBase base class validated against a list of the IDs? You say "mainly because category IDs aren't all part of the same interval," so perhaps the checking against a list would give you what you need there. Otherwise, can you explain a bit more about how it works? Although I realize there are always exceptions, 120 classes doing nothing other than providing different IDs really strikes me as something that's unlikely to be a solution that will serve you well in the long run.
Since you're using C++, why not use templates and specify a non-type template parameter containing the ID?
For example, supposing that the category is an integer:
template<int category_id>
class Downloader : public ItemCategoryBase
{
public:
virtual int get_id()
{
return category_id;
}
};
You might as well let the compiler do the work for you.

Flexible application configuration in C++

I am developing a C++ application used to simulate a real world scenario. Based on this simulation our team is going to develop, test and evaluate different algorithms working within such a real world scenrio.
We need the possibility to define several scenarios (they might differ in a few parameters, but a future scenario might also require creating objects of new classes) and the possibility to maintain a set of algorithms (which is, again, a set of parameters but also the definition which classes are to be created). Parameters are passed to the classes in the constructor.
I am wondering which is the best way to manage all the scenario and algorithm configurations. It should be easily possible to have one developer work on one scenario with "his" algorithm and another developer working on another scenario with "his" different algorithm. Still, the parameter sets might be huge and should be "sharable" (if I defined a set of parameters for a certain algorithm in Scenario A, it should be possible to use the algorithm in Scenario B without copy&paste).
It seems like there are two main ways to accomplish my task:
Define a configuration file format that can handle my requirements. This format might be XML based or custom. As there is no C#-like reflection in C++, it seems like I have to update the config-file parser each time a new algorithm class is added to project (in order to convert a string like "MyClass" into a new instance of MyClass). I could create a name for every setup and pass this name as command line argument.
The pros are: no compilation required to change a parameter and re-run, I can easily store the whole config file with the simulation results
contra: seems like a lot of effort, especially hard because I am using a lot of template classes that have to be instantiated with given template arguments. No IDE support for writing the file (at least without creating a whole XSD which I would have to update everytime a parameter/class is added)
Wire everything up in C++ code. I am not completely sure how I would do this to separate all the different creation logic but still be able to reuse parameters across scenarios. I think I'd also try to give every setup a (string) name and use this name to select the setup via command line arg.
pro: type safety, IDE support, no parser needed
con: how can I easily store the setup with the results (maybe some serialization?)?, needs compilation after every parameter change
Now here are my questions:
- What is your opinion? Did I miss
important pros/cons?
- did I miss a third option?
- Is there a simple way to implement the config file approach that gives
me enough flexibility?
- How would you organize all the factory code in the seconde approach? Are there any good C++ examples for something like this out there?
Thanks a lot!
There is a way to do this without templates or reflection.
First, you make sure that all the classes you want to create from the configuration file have a common base class. Let's call this MyBaseClass and assume that MyClass1, MyClass2 and MyClass3 all inherit from it.
Second, you implement a factory function for each of MyClass1, MyClass2 and MyClass3. The signatures of all these factory functions must be identical. An example factory function is as follows.
MyBaseClass * create_MyClass1(Configuration & cfg)
{
// Retrieve config variables and pass as parameters
// to the constructor
int age = cfg->lookupInt("age");
std::string address = cfg->lookupString("address");
return new MyClass1(age, address);
}
Third, you register all the factory functions in a map.
typedef MyBaseClass* (*FactoryFunc)(Configuration *);
std::map<std::string, FactoryFunc> nameToFactoryFunc;
nameToFactoryFunc["MyClass1"] = &create_MyClass1;
nameToFactoryFunc["MyClass2"] = &create_MyClass2;
nameToFactoryFunc["MyClass3"] = &create_MyClass3;
Finally, you parse the configuration file and iterate over it to find all the entries that specify the name of a class. When you find such an entry, you look up its factory function in the nameToFactoryFunc table and invoke the function to create the corresponding object.
If you don't use XML, it's possible that boost::spirit could short-circuit at least some of the problems you are facing. Here's a simple example of how config data could be parsed directly into a class instance.
I found this website with a nice template supporting factory which I think will be used in my code.