Class libraries for Java's immense verbosity - java

I recently got into Java. I have a background in dynamic languages and I'm finally figuring out why people complain about Java's verbosity. Are there any class libraries out there that address this issue? I'd much rather type something like String text = someClass.stdin() instead of the 8 or so lines it takes to get user input in Java.

In Java 5:
import java.util.Scanner;
...
System.out.print("Enter your name: ");
String userName = new Scanner(System.in).nextLine();
Or, in Java 6:
String userName = System.console().readLine("Enter your name: ");

Some of the Apache Commons libraries (particularly Lang, IO and Collections) are designed to hide the verbosity of certain core Java APIs. The verbosity of the Java language, however, we're all stuck with.

Sure there are several JPython, JRuby, Clojure, Scala...

Google has also released a number of libraries that complement sections of the standard library, like the collections library. Guice is also a nice lightweight DI framework that, IMHO, is easier to learn that spring.
The standard library is so large I don't think you'll find a single library that replaces everything. You're best bet is to look for libraries that solve individual problems (i.e. I don't like the Collections API, I need an object pool, etc.)

I'd be interested in seeing these 8 lines to get user input in Java.
I personally think that Java's verbosity becomes an asset as your program becomes larger. Unlike C and C++, everything is done in a more object oriented way. You get the object representing your output, then you issue an operation on it, and so on. Much easier to understand and maintain in the long run.
Is this as quick as a nice printf() here and there? No. Is it as convenient as scripting in Python? Of course not. But that's part of the cost of using a language like Java, just like the lack of Lambdas is annoying.
As an engineer your role is to pick the best tool for the job. I do most of my coding in Java, and some in Python, accepting the tradeoffs of each.
While you can't change the language, you could use libraries that simplify some operations (e.g., Google's or Apache's IO libraries). You could also write your own classes for the things that annoy you the most.
I also think you're confusing the verbosity of the language and of the standard library. The library contains a lot of stuff, most of it you'll never need. I find the existing division fairly straightforward and have never found myself in areas I didn't care about.
If you really can't stand Java, you might want to use hybrid languages like Scala.

I'm a big fan of leaning on my IDE's live templating features. (IntelliJ IDEA) I can't remember the last time I spelled out StringBuffer or System.out.println("...").

Related

PHP to Java (using PtoJ)

I would like to transition our codebase from poorly written PHP code to poorly written Java, since I believe Java code is easier to tidy up. What are the pros and cons, and for those who have done it yourselves, would you recommend PtoJ for a project of about 300k ugly lines of code? Tips and tricks are most welcome; thanks!
Poorly written PHP is likely to be very hard to convert because a lot of the bad stuff in PHP just doesn't exist in Java (the same is true vice versa though, so don't take that as me saying Java is better - I'm going to keep well clear of that flame-war).
If you're talking about a legacy PHP app, then its highly likely that your code contains a lot of procedural code and inline HTML, neither of which are going to convert well to Java.
If you're really unlucky, you'll have things like eval() statements, dynamic variable names (using $$ syntax), looped include() statements, reliance on the 'register_globals' flag, and worse. That kind of stuff will completely thwart any conversion attempt.
Your other major problem is that debugging the result after the conversion is going to be hell, even if you have beautiful code to start with. If you want to avoid regressions, you will basically need to go through the entire code base on both sides with a fine comb.
The only time you're going to get a satisfactory result from an automated conversion of this type is if you start with a reasonably tide code base, written at least mainly in up-to-date OOP code.
In my opinion, you'd be better off doing the refacting excersise before the conversion. But of course, given your question, that would rather defeat the point. Therefore my recommendation is to stick it in PHP. PHP code can be very good, and even bad PHP can be polished up with a bit of refactoring.
[EDIT]
In answer to #Jonas's question in the comments, 'what is the best way to refactor horrible PHP code?'
It really depends on the nature of the code. A large monolithic block of code (which describes a lot of the bad PHP I've seen) can be very hard (if not imposible) to implementunit tests for. You may find that functional tests are the only kind of tests you can write on the old code base. These would use Selenium or similar tools to run the code through the browser as if it were a user. If you can get a set of reliable functional tests written, it is good for helping you remain confident that you aren't introducing regressions.
The good news is that it can be very easy - and satisfying - to rip apart bad code and rebuild it.
The way I've approached it in the past is to take a two-stage approach.
Stage one rewrites the monolithic code into decent quality procedural code. This is relatively easy, and the new code can be dropped into place as you go. This is where the bulk of the work happens, but you'll still end up with procedural code. Just better procedural code.
Stage two: once you've got a critical mass of reasonable quality procedural code, you can then refactor it again into an OOP model. This has to wait until later, because it is typically quite hard to convert old bad quality PHP straight into a set of objects. It also has to be done in fairly large chunks because you'll be moving large amounts of code into objects all at once. But if you did a good job in stage one, then stage two should be fairly straightforward.
When you've got it into objects, then you can start seriously thinking about unit tests.
I would say that automatic conversion from PHP to Java have the following:
pros:
quick and dirty, possibly making happy some project manager concerned with short-time delivery (assuming that you're lucky and the automatically generated code works without too much debugging, which I doubt)
cons:
ugly code: I doubt that automatic conversion from ugly PHP will generate anything but ugly Java
unmaintainable code: the automatically generate code is likely to be unmaintainable, or, at least, very difficult to maintain
bad approach: I assume you have a PHP Web application; in this case, I think that the automatic translation is unlikely to use Java best practices for Web application, or available frameworks
In summary
I would avoid automatic translation from PHP to Java, and I woudl at least consider rewriting the application from the ground up using Java. Especially if you have a Web application, choose a good Java framework for webapps, do a careful design, and proceed with an incremental implementation (one feature of your original PHP webapp at a time). With this approach, you'll end up with cleaner code that is easier to maintain and evolve ... and you may find out that the required time is not that bigger that what you'd need to clean/debug automatically generated code :)
P2J appears to be offline now, but I've written a proof-of-concept that converts a subset of PHP into Java. It uses the transpiler library for SWI-Prolog:
:- use_module(library(transpiler)).
:- set_prolog_flag(double_quotes,chars).
:- initialization(main).
main :-
Input = "function add($a,$b){ print $a.$b; return $a.$b;} function squared($a){ return $a*$a; } function add_exclamation_point($parameter){return $parameter.\"!\";}",
translate(Input,'php','java',X),
atom_chars(Y,X),
writeln(Y).
This is the program's output:
public static String add(String a,String b){
System.out.println(a+b);
return a+b;
}
public static int squared(int a){
return a*a;
}
public static String add_exclamation_point(String parameter){
return parameter+"!";
}
In contrast to other answers here, I would agree with your strategy to convert "PHP code to poorly written Java, since I believe Java code is easier to tidy up", but you need to make sure the tool that you are using doesn't introduce more bugs than you can handle.
An optimum stategy would be:
1) Do automated conversion
2) Get an MVP running with some basic tests
3) Start using the amazing Eclipse/IntelliJ refractoring tool to make the code more readable.
A modern Java IDE can refactor code with zero bugs when done properly. It can also tell you which functions are never called and a lot of other inspections.
I don't know how "PtoJ" was, since their website has vanished, but you ideally want something that doesn't just translate the syntax, but the logic. I used php2java.com recently and it worked very well. I've also used various "syntax" converters (not just for PHP to Java, but also ObjC -> Swift, Java -> Swift), and even they work just fine if you put in the time to make things work after.
Also, found this interesting blog entry about what might have happened to numiton PtoJ (http://www.runtimeconverter.com/single-post/2017/11/14/What-happened-to-numition).
http://www.numiton.com/products/ntile-ptoj/translation-samples/web-and-db-access/mysql.html
Would you rather not use Hibernate ?

General Purpose Decision Tree Algorithm Code Implementations

Are there any well-designed, general purpose decision tree implementations for iPhone or Java? I know with LINQ it would be quite trivial, but with Objective C and Java, it would be much more complex.
Basically, I want to drill down a set of objects based off any number of qualifications or attributes in my apps.
You could try Weka. The API is somewhat obtuse and makes simple things complicated, but it's a very good machine learning library and it even comes with a GUI front end if you want to play around with the classes interactively before writing code that uses them programmatically.

First Steps with DSL on Java?

Guys... Girls, I'm working on a project which I think could be enhanced by implementing a Domain Specific Language for defining a set of rules and/or conditions for some type of work-flow.
I want to get a firm grasp on the subject, fundamentals, best practices, etc. specially how to implement them somehow with Java.
What do you suggest?
First I would recommend reading chapter 9 (Notation) of The Practice of Programming by Kernighan and Pike.
When you have done that, come back here with specific questions on how to map the concepts in that chapter to specific designs for the problems you want to solve.
The basic pattern is to write an interpreter that is passed a 'command' argument, and possibly an 'environment' argument and executes the command (in the environment). You then have the option of writing a parser, that takes a 'script' string and converts it into a valid 'command' object (ie. an external-DSL); or you provide a library to help users build the 'command' object explicitly in the same language you are using (internal-DSL).
Kernighan and Pike do a good job of showing both how trivial and how complex an interpreter can be. If you want more depth, then I would suggest reading The Essentials of Programming Languages by Daniel Friedman et al. Which builds at least one different interpreter per chapter, and demonstrates how to implement features such as variables, functions, scopes, objects, classes, static-typing, and continuations.
However I would suggest trying your hand at a trivial DSL first, otherwise it's all just theory—a book is much more interesting when it is made relevant and practical by your previous experience.
As others have commented, Java really isn't a great choice for creating a DSL. Scala, Clojure, Groovy, Ruby/JRuby would all be great choices. However, considering you were thinking about using Java, I think Groovy or Scala seem like the most natural choices. The learning curve for java developers is quite gradual for both languages. Here are some links that will get you started:
Groovy for Domain-Specific Languages (Book)
DSLs - A powerful Scala feature
DSL Composition Techniques in Scala
Once I used openArchitectureware to define and use a DSL. oAW is a plugin to eclipse and now part of the eclipse modeling framework, but of course it can be used outside EMF too.
I liked it because it was fairly easy to define a DSL and oAW will automatically generate an editor with syntacx highlighting and error checking for the DSL.
And it provides a template engine that is pretty comfortable if you plan to use documents written in your DSL to autogenerate Java, XML or other files.
(I've linked the old oAW URL because the page still provides some details and all links to the eclipse project pages)
Just an addition to #Recurse. I'm actually doing the regex example in chapter 9 he was referring to and it didn't work until I changed a line in the main function:
if (grep(argv[1], f, argc>3 ? argv[i] : NULL) > 0)
should really be:
if (grep(argv[1], f, argc>2 ? argv[i] : NULL) > 0)
notice the argc>2. It worked for me after that. Wasn't on the books errata (which is not surprising given it's age).
Yeah, this is a dense but treasure trove of a book so I have to say I agree with #Recurse. Honestly, it's a time sensitive book for the student (I probably would have been confused a couple of years ago).

xml.etree.ElementTree equivalent in Java

I've been doing quite a bit of simple XML-processing in python and grown to like the ElementTree way of doing things.
Is there something similar and as easy to use in Java? I find the DOM model a bit cumbersome and find myself writing much more code than I would like to do simple things.
Or am I asking the wrong thing?
Maybe my question is: Is there a better option than the "XMLUtils" classes I see people implementing in some places to simplify their code when dealing with DOM?
Adding a litte bit here about why I like ElementTree since the question was asked.
Simplicity (I guess anything seems simple after working with DOM though)
Feels like a natural fit in python
Requires very little code on my part.
I'm trying to come up with a simple code example to illustrate, but it's sort of hard to give a good example.
Here's an attempt though. This just adds a tag with a value and an attribute to an existing xml string.
from xml.etree.ElementTree import *
xml_string = '<top><sub a="x"></sub></top>'
parsed = fromstring(xmlstring)
se = SubElement(parsed, "tag")
se.text = "value"
se.attrib["a"] = "x"
new_xml_string = tostring(parsed)
After that, the new_xml_string is
<top><sub a="x" /><tag a="x">value</tag></top>
Not an example that really covers everything, but still. There's also the fairly simple looping over tags when you want to do stuff, easy testing for presence of tags and attributes and other things.
To be honest, all XML APIs in Java suck, you just can vary the level of suckage you push yourself into which may turn horrible/slow to manageable/decent to even suprisingly OK at times.
This all mostly stems from the fact that Java APIs try to be as W3C DOM compliant as possible, in fact Xerces (Java's current native XML solution) prides itself on being compliant to a whole bunch of XML related W3C specifications as you can see from their front page.
The actual Xerces API is very unpleasant to work with, though, and because of that multiple other Java XML libraries have popped out over the years. Currently most popular ones are
JDOM, simplifies DOM operations a lot and do I dare to say even pleasant at times, works like a charm when mixed with Jaxen - well, unless you hit this problem with namespaces.
XOM which has a wonderful presentation about what's wrong with Java's XML right now and how they propose their way of doing things as a solution. In part it is actually better than JDOM, but it's not widespread enough yet so can't really say how it behaves in the real world out there. Definitely worth a check though.
dom4j, well-rounded library, supports all kinds of important features and plays out as a down-to-earth solution for XML. dom4j is basically the "old, proven and reliable" option of the popular ones.
Last but definitely not least I just have to mention StAX just because it's different, it's actually event-driven streaming API for XML. Definitely worth a look just out of curiosity.
PS. I'm currently actually writing my own XML parser/navigator as an exercise but haven't decided on what kind of API it will have. I'm really aiming for ease of use which seems to be quite rare in Java XML APIs so far, but I'm not entirely sure what kind of API I am going to provide. Python's ElementTree seems interesting, but since I'm not entirely familiar with it, would you like to maybe give a short summary on what exactly in it you find enjoyable?
You might look into the following alternatives:
dom4j
xom
jdom
Since I never used ElementTree I don't know wich one is the closest.
If you can use Groovy inside your project, it offers a set of classes that helps a lot when processing XML.
We find XOM (http://www.xom.nu) to provide simple subclassable Element functionality.
It is true the Java XML APIs are not the greatest in terms of usability. My prefered options would be XOM, JDOM then the built in JAXP in that order. There were some rumbling about native XML in the language (Begin Product Tab Sub Links
Integrating XML into the Java Programming Language) as a new data-type but that seems to have stalled.

replacement project for existing school assignment

I have a school assignment which consists of programming a scanner/lexical analyzer for a specified simple language. The scanner has to be programmed in C++.
This type of assignment has been used since the 90's and, although still a valid excersise, I consider it to be a little antiquated and a little boring.
I have gotten permission to come up with a new programming assignment.
It has to be of equal difficulty and it can be in C++, Objective C or Java.
What direction should I go that has the same level of difficulty but is a little bit more modern and applicable to modern CS/life.
Thanks
This type of assignment... is considered to be a little antiquated and a little boring.
I'm curious: who considers this antiquated? Your professor? Somebody notable in the parsing community? Or you?
Scanners and parsers are still relevant to professional software development and, more importantly, relevant to the science of computation. If you wish to understand computers, then you should understand scanners and parsers.
Still, if you are convinced that you should do some other assignment, why not write a tool to generate a scanner in C++? You could supply, as input, a set of regular expressions that define the tokens of the grammar, and it would produce a C++ program that would recognize the input tokens. Then, you will never need to write a scanner ever again!
Why do you think that Lexers / Parsers are not relevant anymore? I find that I write something along those lines at least once a year.
As a software engineer, I would say whatever code you write during the CS courses would be the best ones that you may probably write in your life. Once you come into the industry, you will probably write only modules and not the entire thing.
Believe me. Once you come into the industry and has spend some time here, you will just want to write those compilers, assemblers, lexical analyzers. So please don't miss the chance.
I believe the challenges in writing this "boring" stuffs are just worth it and you will find them truly interesting once you start designing the stuff.
Writing a scanner/lexical analyzer was one of my favorite assignments. I would argue that it was also one of the most relevant. It is a real world problem.
My guess is that it does not feel modern because of the simple programming language you are scanning. I personally would change out the simple programming language for something like Markdown or Textile. Both of these are used in modern programming, and will teach you similar concepts.

Categories