JINQ – A minimalistic library for Java inspired from .NET LINQ
github.com
github.com
A pet peeve of mine is how these libraries put the 'old' alternative in the worst possible light, creating the fake impression (at a casual glance) that the library makes your code much nicer. It doesn't.
Passing in an array is weird, so lets assume we're not working with really outdated codebases and a List<Product> is passed in instead.
You can do the snippet with bog standard Java8+ stream API like so:
List<ProductDisplayInfo> getDisplayList(List<Product> products) {
return products.stream()
.filter(p -> p.getCategory() == 2 || p.getCategory() == 5 && isProductUnderDiscount(p))
.map(ProductDisplayInfo::new)
.collect(Collectors.toList());
}
Even in old style java6 syntax it's short, sweet, and to the point (as short as this library can let you write it): List<ProductDisplayInfo> getDisplayList(List<Product> products) {
var pdiList = new ArrayList<ProductDisplayInfo>();
for (var p : products)
if (p.getCategory() == 2 || p.getCategory() == 5 && isProductUnderDiscount(p))
pdiList.add(new ProductDisplayInfo(p));
return pdiList;
}
Separate from that, as scarface74 mentioned, part of the point of LINQ is that the structure of the expression tree can be applied elsewhere, for example, to an SQL statement.But most of what I've seen LINQ to Objects used for is simply mapping over data that already lives in memory. Oftentimes you want to just pass along a lazy projection of that data, on the grounds that re-running the operation is less expensive than allocating a bunch more memory in order to cache the result to a list.
In the cases where a source can't be restarted, it's always seemed easy enough to me to just build up your LINQ query and then pass its enumerator back rather than the original enumerable. Returning an IEnumerator<T> should be sufficient to communicate that you only get to enumerate the thing once, and tacking a ".GetEnumerator()" on the end of things requires barely more typing than tacking ".ToList()" on the end.
By contrast, with streams, I feel like the Java maintainers gave me an API that's less powerful than the standard I'm used to on other platforms, on the grounds that they think I'm not a smart enough developer to handle a more powerful API. I don't really appreciate that. All it's really meant is that I now need to work with two different libraries depending on whether I'm working with data that lives in memory or not, which does worse things to the cognitive load it takes to understand the codebase than simply having to keep track of the difference between an Iterable<T> and an Iterator<T> would have.
Iterable<ProductDisplayInfo> getDisplayList(List<Product> products) {
return () -> products.stream()
.filter(p -> p.getCategory() == 2 || p.getCategory() == 5 && isProductUnderDiscount(p))
.map(ProductDisplayInfo::new)
.iterator();
}
(E&OE - i haven't actually compiled this, but do this all the time!)I think that one thing a lot of people are missing when they talk about the Expressions bit of LINQ is that LINQ is really two different things that have two different killer features. There's the set of extensions on top of IEnumerable<T>, which are mostly used for writing declarative replacements for for-loops, and also supporting things like PLINQ. As far as I'm aware, IEnumerable<T>'s MSDN documentation doesn't even mention expression trees. And there's the (much more complicated) IQueryable<T> interface, which is the bit that supports things like the LINQ interface to Entity Framework, and is all about expression trees.
The IEnumerable<T> bits aren't as fancy, but they are still quite useful.
The same LINQ expression once translated to expression trees by the runtime can then be translated to SQL, MongoQuery,C# IL, etc at runtime depending on the linq provider.
https://blogs.msdn.microsoft.com/charlie/2008/01/31/expressi...
https://stackoverflow.com/questions/623413/expression-trees-...
var seniors = customers.Where(c => c.age > 65)
Could either represent C# IL, a MongoQuery, a SQL query, an ElasticSearch query, etc. depending on what type of variable “customer” is.
Also, you don't need a better term than "provider" as that's what they're called. :-) The IQueryable interface includes a property called Provider that returns an IQueryProvider which can operate on an expression tree.
To be further pedantic: it creates an expression when the method accepts an Expression<T>, which IQueryable happens to do.
That's the difference between IQueryable and IEnumerable. If you use IEnumerable, it'll filter on the client side rather than the server side. Potentially a performance and resource and even security/privacy problem. With IQueryable, the filtering is done on the server side.
Personally, the best thing to do is to use stored procedures. ORMs and query generation on the client side is such a bad idea. But it's easy, so people go for the easy solution.
Also, it’s a lot easier and less error prone to compose dynamic queries with Linq - ie keep chaining Where clauses and OrderBy’s based on a condition.
You can also do things like create methods that take predicates.
CustomerRepo.Find( c=>c.age > 65)
And define the Find method.
List<Customer> Find(Expression<Func<Customer,T>> predicate).
I’ve even had one project where the backing store could either be SQL Server or Mongo. We were able to use the same interface with methods like the Find method above and the repos translated the predicates appropriately.
List<Customer> Find(Expression<Func<Customer,T>> predicate)
Should be
List<Customer> Find(Expression<Func<Customer,bool>> predicate)
That's the general assumption of people not familiar with SQL, RDBMs and full stack architecture. One of my issues is that ORMs and LINQ have become crutches. Also, you are ignoring the major problem of security and auditing. If you are working on a local toy project, then sure, you can just do whatever you want. But if it is an enterprise project with real security concerns, the idea of giving read/write access to web server accounts is amateur hour. Trust me, I've seen it with my own eyes. People who spend 2 days reading "Learn web dev in 21 days" and "Learn SQL in 21 days" and putting today something akin to "Hello world" projects because their managers didn't know any better.
> - ie keep chaining Where clauses and OrderBy’s based on a condition.
You can use LINQ, chaining, lazy evaluation and all that on data/Enumerables/sequences retrieved from a stored procedure.
But hey, what do I know.
var movies = get("https://movies.org/movie") foreach( var movie in movies) { if (movie.year > 2016) addToTable(movie) }
Let's do this with LINQ: foreach( var movie in movies.Where(movie => movie > 2016)) { addToTable(movie) }
The naive observer will assume the two pieced of code are about the same. But in actuality, if you had a fictitious "LINQ to Movies", it could, internally, construct the correct REST API for you.
What I'm saying is that, this code: var list = movies.Where(movie => movie > 2016))
would translate into:
var movies = get("https://movies.org/movie?year>2016")
Not so hypothetical. This is how OData works from C#.
Look at the C# example under "Step 2: Requesting an individual resource" at http://www.odata.org/getting-started/understand-odata-in-6-s...
See how elegant it is compared to the other examples using Java, Node, etc.
Doing this requires meta-programming, which many other languages have. I don't know much about Clojure, Scala or Ruby, but I'm pretty sure stuff like this can be (and possibly already are) built using the existing meta-programming constructs.
(1) https://github.com/Const-me/EsentSerialize/tree/master/Core/... (2) https://github.com/Const-me/EsentSerialize/blob/master/Demos...
List<ProductDisplayInfo> list = Arrays
.asList(products)
.stream()
.filter(p -> p.getCategory() == 2 || p.getCategory() == 5 && isProductUnderDiscount(p))
.map(p -> new ProductDisplayInfo(p))
.collect(Collectors.toList());
https://docs.oracle.com/javase/8/docs/api/java/util/stream/p...For fun, you can further reduce the size of the code above (and IMO, make it clearer), but using `Arrays.stream(product)` and a method reference for the `map`:
List<ProductDisplayInfo> list = Arrays
.stream(products)
.filter(p -> p.getCategory() == 2 || p.getCategory() == 5 && isProductUnderDiscount(p))
.map(ProductDisplayInfo::new)
.collect(Collectors.toList());Java streams read data from spinning rust and then does the selection in RAM. LINQ can send the "where" to the RDBMS and the RDBMS can use an index/btree lookup to read just the data needed where java streams would read umpty megabytes.
I don't know whether the JINQ people plan to write a good query generator. But if I were the maintainer, my plan would definitely be to focus on the API first and only then work on optimal backend implementation(s).
But it all feels a bit too "magical" for me. Seems like you're trading one class of bugs - hand-written SQL mismatching your types - for another - this magic doing something unexpected when you try to do something weird. But maybe it's really really good and that second class of bug never happens. I'm just hesitant (and happy with doobie for now).
So, jOOQ will never become quill or end up looking like it.
That started out as a LINQ port but turned much more interesting.
Life would be much easier for everyone with expression trees in the language, though.
.where(p -> p.getCategory == 2 || p.getCategory == 5 && isProductUnderDiscount(p))
and if (product.getCategory() == 2 || product.getCategory() == 5) {
boolean yes = isProductUnderDiscount(product);
not functionally equivalent due to && precedence? .where(p -> p.getCategory == 2 || p.getCategory == 5 && isProductUnderDiscount(p))
is equivalent to: if (product.getCategory() == 2 || ( product.getCategory() == 5 && isProductUnderDiscount(product) );
The extra set of parentheses are not needed due to precedence, but have been included for clarification. (product.getCategory() == 2 || product.getCategory() == 5) && isProductUnderDiscount(product)[0] - https://vivekragunathan.wordpress.com/2016/04/02/jinq/
2. JINQ (as a name) already exists: http://www.jinq.org