by bane · 12y ago · 0 comments
I'm frequently surprised at the really rough and inconvenient bits in Java. Weird inconsistencies in the libraries, or not having a really convenient set of file read/write methods without having to cobble together bits and pieces of an I/O system to get a directory listing or read in a file or whatever, or how variable performance is between two similar looking pieces of code (if you haven't done lots of benchmarking on Java standard library containers, I urge you to do it, and make careful selection of containers based on that, it's frequently surprising how different otherwise identical looking code runs).
Considering there are what, 3 complete GUI toolkits built in, why isn't there a built in CSV parsing library, or a "read file to string" static method somewhere? Why do I have to put so much effort into basic tasks? It's such a weird and uneven and sloppy feeling thing.
There's all these weird aggregated different ways to do the same thing, but each built to fix some problem with some older solution, but the older broken ways were never really deprecated out for compatibility. Unless you run across some guide that says explicitly "use this instead of this because of <reasons>" you might never know the newer version exists. Yet the new releases includes so much compatibility breaking new syntax changes that it doesn't practically matter.
There's bits and pieces of related but complete solutions piled all over the library as well. e.g. Regex bits are in String, java.util.regex.* (Pattern and Matcher) and probably elsewhere...and don't get me started if you're moving back and forth between arrays and the various containers that make arrays more usable, and then all the utilities to help with that which are scattered all over the place. I spend half my time writing code to abstract all that nonsense away so I can write the main code logic in peace.
And then over the years the concepts about how to design an API have changed or something, because you can feel different stylistic concepts in different places. Here you instantiate an object, then set it up, then build another object of this type to catch the results and do some other magic. Here you instantiate the object with all the important bits and manipulate the object with local methods. It's like each class requires it's own style guide. I can understand that with 3rd party work, but it doesn't make sense with the batteries that come with the language to be so uneven.
It was probably 10 years ago that I last tried Java, and it sucked back then, with all the verbosity etc. But with modern IDE support I actually kind of like the flow and style of it to some extent. It's a beautifully simple syntax to use at its core. But then again I don't care about all the FactoryFactory nonsense. And I'm avoiding lots of the new stuff that doesn't really fit into the language.
I've actually started to become convinced that it's getting to the point that Java 10 or whatever should be a single minded house cleaning. Jettison all the broken old shit, clean up the style and usage, build decent syntax into the language for doing common tasks so the coder doesn't have to boilerplate themselves to death. Take 5 years to do it, the enterprise will survive that long.
edit I wonder if the idea of an "API editor" to vet the interfaces for consistency and style in these large standard libraries makes sense?
Then there are bits which should be avoided at all costs. Date and time is one. All the GUI libraries are another. HTTP via URLConnection isn't terrible, but people mostly use Apache HttpClient instead. NIO is a mixed bag, with some really good bits, and some complexity whose necessity escapes me (particularly since it can be hidden by XNIO without losing anything).
It is a real shame that there is this patchiness. I would love to claim that all the rough code is from the pre-1.2 era, but i would be lying. Particularly if you look beyond the JDK and into the enterprise libraries, there have been some real shitshows given official imprimatur (i remember Java Advanced Imaging being particularly horrifying).
And while the quality of the standard SDK varies, most of it is very good, and there are stuff that's solid gold in there, like Nio and Concurrency libs.
Also, you really shouldn't just drop "x sucks" into a conversation without backing it up with something reasonable. Or was this a well-crafted troll comment?
As for the Apache Commons, well where to start? It's been several years since I last dealed with them, on my Java days, but there were lots of issues.
From the general overboard AbstractFactoryProxyFactorytis and overall OO fails (real example: DoubleListIteratorListIterator), to useless utility classes that replicate already existing SDK capabilities, to the lack of generics support for the collections (for a looooong time, don't know if they fixed this now) -- oh, and them not being compatible with Java collection interfaces either --, to lack of thread safety, to string output libraries blisfully unaware of the existance of encodings, and a whole lot more besides.
It's really not that difficult to assemble the combination of classes to get a formatter. There are problems with the API, but that's not one of them.
Plus, your hand rolled case probably misses hundrends of edge cases (I'm not exagerrating, date and time is one of the most difficult things to get right).
Date thing = new Date(someStringWithaDate,"MMM dd, yyyy");
String newDateThing = thing.convertDateFormat("yyyy-mm-dd");
and be done with it. Or at worst Date thing = new Date(someStringWithaDate,"MMM dd, yyyy");
Date newDateThing = thing.convertDateFormat("yyyy-mm-dd");
String someStringWithaDateButFormattedLikeIWant = newDateThing.toString();
But the overwrought standard library just completely got in the way and I don't even remember how many lines of code and objects I ended up with just to do this before I said "fuck it" and did the equivalent of (with a some utilities to convert abreviated dates to numbers. String.replaceAll("([A-Z]{3}) (\d{2}), (\d{4})","$3-$2-$1");
Of course now I'm not getting whatever date validation the Date class might offer (if it does), and I ended up using a 50 cent solution when I really needed a $1.50 solution, but the standard library only offered an overpriced $20 way that I didn't need.The end result is that we're all poorer for it.
DateFormat format1 = new SimpleDateFormat("MMM dd, yyyy");
DateFormat format2 = new SimpleDateFormat("yyy-mm-dd");
String originalDateString = ...;
String newDateString = format2.format(format1.parse(originalDateString));
Even in something like Python, the basic pattern is the same: a call to strptime to convert from string => date object in the original format, and a call to strftime to convert from date object => string in desired format.Still it seems conceptually weird that the idea of a DateFormat object can be a thing, when it's just a String with the magic Format language.
Parsing or formatting (the verbs) seem more like actions to be taken on a Date itself. It seems much tidyier to me to just keep all that contextually in the Date class.
Why isn't all this garbage just bundled into the Date class? It seems to me that among the many things somebody might want to do on a date, converting the String representation might be one of them.
okay here's what I'm talking about. From the API docs on Date
toGMTString() - *Deprecated.* As of JDK version 1.1, replaced by DateFormat.format(Date date), using a GMT TimeZone.
toLocaleString() - *Deprecated.* As of JDK version 1.1, replaced by DateFormat.format(Date date).
toString() - Converts this Date object to a String of the form: dow mon dd hh:mm:ss zzz yyyy
All either deprecated or useless (dow mon dd hh:mm:ss zzz yyyy? really?). And the documentation doesn't point to the better classes to do what I want.Okay, so what's a DateFormat?
DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner.
Okay that sounds promising, of course they're admitting they don't have the concept of a "Date Format" object type since it's all just static stuff, so shouldn't all this just be in the Date class? That feels weird.Wait there's a DateFormatter, that sounds promising, it's all verby sounding.
DateFormatter is an InternationalFormatter that does its formatting by way of an instance of java.text.DateFormat.
Well what the hell is an InternationalFormatter? And down the rabbit hole I went.I did eventually figure it out. But it was so inelegant and stupid I felt ashamed to have it in my code. If I had read one more line in the DateFormatter doc I suppose I could have found SimpleDateFormat, but the bizarre complexity about converting formats was already so mind bendingly dumb.
This is stupid and obtuse design, overly parsing the problem and unnecessarily separating what should be connected pieces of the puzzle.
Solution (needs revision, but this would be a useful point to start a discussion):
Classes
Date - a representation of a specific date and time down to millionths of a second resolution
methods:
add, sub Dates - returns Duration
add,sub Duration, returns Dates
one of the constructors takes a String that ostensibly contains a Date of some sort, and a format String to parse it, throws exception if the date isn't valid
setOutPutFormat - takes a Format string and the next call toString() emits on that format.
all the get, set hour minute day year methods so you can pick it apart change pieces as you want
setOutPutCalendar - changes the Date to whatever recognized calendar system (Chinese, Arabic, Hebrew, etc.), setOutPutFormat is context aware of this
all the timezone stuff
after and before
get/set 2 digit year
Date comparison methods like isBefore(Date) to see if another Date object is before or after this one
Done. All of Date, DateFormat and SimpleDateFormat is there, problems solvedDuration - an representation of a time Duration (6 days, 7 minutes, 14 second), and since all time intervals are durations, that's it.
Methods:
Constructor can be an ISO 8601 String for Duration or two Date objects representing the beginning and end of a duration. Since Date objects should have their own timezone and locals, the magic black box of this class should figure out the duration for me. It's not my problem to sort this out. If the begin and end dates produce a negative duration that's cool because now I have a countdown.
Duration comparison methods, like isWithin(Duration) to check if another duration object is within this one or isWithin(Date) to see if a Date is within the duration or isLongerthan(Duration)
Duration math like add/subtract other durations from the begin and end of the Duration
Done.If you want inconsistent, .Net framework's collections and HTTP stuff was the worst for years. They added to the former and wrapped the latter but you still fall over crimes. Java collections and Servlet API are pretty good really in comparison.
It's not terrible really. Anything on that scale is inconsistent: python, ruby, .Net, C++.
The hard bit is learning where stuff is hidden. I'm currently doing that with Objective-C.
Well, I wonder if this is necessarily inevitable. The Oxford English Dictionary is probably as large and complex as any of the above, but is remarkably consistent in style and tone. I'm a firm believer that good design extends to code (and coders are sadly not very good designers in general).
It would be nice if a programming language came along that designed all features right from the start, so no features ever needed to be deprecated or redesigned. Unfortunately I have yet to find a language that is all things to all people, even after several versions; designing a language perfectly from scratch might not even be possible.
Keeping the even releases well scoped would ease the pain of transitioning. Maybe ensure some guaranteed level of support for 12-24 months a la Ubuntu and we might have a good model for language development.
I left Go off that list precisely for that reason.
The JDBC API is still beyond horrible (is there a decent 3rd party SQL API?). Checked Exceptions still survive. String still lacks many basic features.... and sadly as others have pointed out to get usable APIs you need Apache Commons.
I agree, Oracle needs to do some house cleaning. Some times it's ok to break things. Don't do it too often, but once every 10 years seems ok to me!
There is a method for reading a file into a list of lines (it is strange that they didn't include a method to read the lines into a single string).
It's best to use a library for this like SuperCSV: http://supercsv.sourceforge.net
22 people failed the test entirely, complaining about quotes and line ending inconsistency.
2 people wrote a proper state machine driven parser that didn't work.
1 person wrote a proper state machine driven parser that worked.
1 person imported commons-csv and wrapped stuff.
The last person got the job.
You probably missed three really good candidates here.
Geez, I think I've already reimplemented that half a dozen times. Of course it would be buried in the Files class and not one of the 30 dozen buffer reader whatever classes I have to piece together.
> String.split()
Yeah yeah, that's what all the Java books say ;)
Sort of have python.csv.reader, python.csv.DictReader, etc, which all conform as java-ish as possible to http://docs.python.org/release/2.7.3/library/csv.html
And there's still all the old poorly thought out junk still crufting up the standard library.