341 points · by Mitt · 15y ago · 204 comments
http://download.oracle.com/javase/7/docs/technotes/guides/la...
In a prev job, I saw this block of code -
-------
public int getDaysInMonth( String month ) {
if( month.equalsIgnoreCase("january")) return 31;
else if( month.equalsIgnoreCase("february")) return 28;
else if( month.equalsIgnoreCase("march")) return 31;
else if( month.equalsIgnoreCase("april")) return 30;
...
}-------
My eyes bled. I said folks, just map the month to an int M in range [1..12] and simply write 1 line of code
return 30+((M+Math.floor(M/8))%2;
( except for 2, which is 28 or 29 depending on a leap year)
I was overruled. "We are programmers, not mathematicians" was the response!!!
Now they'll happily use this string-switch to do
---------
switch( month.toLowerCase() ) {
case "january" return 31;
case "february" return 28;
case "march" return 31;
case "april" return 30;
... default : return -1;
}-------
which is an even nastier abomination :(
Edit: also, if you're mapping the month string to an integer anyway, I don't see how you're going to do that without doing basically the same thing as the switches you posted anyway.
[31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][M-1]
than your formula. Even a dictionary wouldn't be bad. And if it were wrong, it would be easier to fix it.The aforementioned code can never be verified as correct because February requires a year to be present to know the number of days.
Doesn't java have a massive calendar library to address exactly these sorts of human questions?
I mean sure you'd still be looking at code like:
public int getDaysInMonth(DateTime date) throws
CalendarFactoryFactorException,
DateOutOfRangeException,
ArrayOutOfBoundsException
{
CalendarFactoryFactory factoryMaker = new CalendarFactoryFactory("Western");
GregorianCalendarFactory gregFactory = factoryMaker.getGregorianFactory();
Calendar c = gregFactory.createCalendar(new DateTime());
return c.getDaysInMonth();
} case "september":
case "april":
case "june":
case "november": return 30;
It's sad, but still need to go through the poem in my head to remember most of the time.1. You have 12 months. Ignore February. Then you have 11.
2. The remaining 11 map to either 30 days or 31 days . ie. 30+0, or 30+1.
3. So the object is to write a many-to-one function that maps some members of the set to 0, rest to 1. Add 30 and you get the right answer ie. number of days in that month.
4. So you want to map {1,3,5,7,8,10,12} to 1, and {4,6,9,11} to 0.
5. Write down a 13 bit number. If you rightshift x times and AND it with unity, you get 1.
6. So then, x belongs to {1,3,5,7,8,10,12}.
7. That means the bit in each of those locations must be on. The rest of the bits must be off. That gives you the number 1010110101010, which is simply 5546 in decimal.
8. So that's ((5546>>M)&1)+30, except for M==2.
I'm sure this is useful in some cases though :-)
http://groups.google.com/group/mustachejava/browse_thread/th...
"These Supplemental License Terms add to or modify the terms of the Binary Code License Agreement....
A. COMMERCIAL FEATURES. You may not use the Commercial Features for running Programs, Java applets or applications in your internal business operations or for any commercial or production purpose, or for any purpose other than as set forth in Sections B, C, D and E of these Supplemental Terms. If You want to use the Commercial Features for any purpose other than as permitted in this Agreement, You must obtain a separate license from Oracle."
Sections mentioned are: B. SOFTWARE INTERNAL USE FOR DEVELOPMENT LICENSE GRANT. ... Oracle grants you a non-exclusive, non-transferable, limited license without fees to reproduce internally and use internally the Software complete and unmodified for the purpose of designing, developing, and testing your Programs.
C. LICENSE TO DISTRIBUTE SOFTWARE. ... Oracle grants you a non-exclusive, non-transferable, limited license without fees to reproduce and distribute the Software, provided that (i) you distribute the Software complete and unmodified and only bundled as part of, and for the sole purpose of running, your Programs, (ii) the Programs add significant and primary functionality to the Software, (iii) you do not distribute additional software intended to replace any component(s) of the Software, (iv) you do not remove or alter any proprietary legends or notices contained in the Software, (v) you only distribute the Software subject to a license agreement that: (a) is a complete, unmodified reproduction of this Agreement; or (b) protects Oracle's interests consistent with the terms contained in this Agreement and that includes the notice ...
D. LICENSE TO DISTRIBUTE REDISTRIBUTABLES. ... Oracle grants you a non-exclusive, non-transferable, limited license without fees to reproduce and distribute those files specifically identified as redistributable in the README File ("Redistributables") ...
E. DISTRIBUTION BY PUBLISHERS. This section pertains to your distribution of the JavaTM SE Development Kit Software with your printed book or magazine ....
Maybe I'm reading too much into it, because of the Android lawsuit?
Specific to (A), that is regarding the JDK (as opposed to the JRE). As mentioned elsewhere, you can't redistribute tools.jar, and I think the compiler itself is a problem too.
The comparison isn't Java to C++. It's Java to C#, Scala, even Python or Ruby. And against C# and Scala in particular, Java does very poorly.
Maybe I'm biased due to other new(er) languages becoming mainstream. But it feels like Java (as a language) has fallen behind as other Languages adopt new features that cater to different/modern techniques.
Java won't ever be cutting edge (and given the types of applications that are built with it, some stability/maturity makes a lot of sense), but look at the advances that C# has made since 1.5/1.6 has been out.
It wasn't like C++ pre C+11 -it didn't take a decade or soto catch up with the rest of the programming world, but you can see the its size slowing its advancement down.
I want to like programming in Java again (I'm not saying it's bad, or it's a mistake) - for a long time it was my go-to language for when I play with ideas. But for now it's just a way to pay the bills while I try to figure out what I want to do/make/build.
This is the mindset I've never understood.
Do you stop using a hammer to bang in nails because the hammer "community" has splintered, or the development of hammers has stagnated? No, you still use it to fulfill a job it solves.
New language features are all fun, but unless they actually result in faster execution, or allow you to do things you could not do before, they're only use is to make some developers happy, which I don't think is particularly important.
It looks like there's some real solid good APIs here though which is great to see.
At first thought I imagined it'd just be useless pandering to developers like "You can now do closures or first class functions" or something equally useless.
They require more resources to run, but they tend to get the job done a lot faster.
Perhaps a better analogy is a screwdriver. Apple came out with their "pentalobe" security screws a while back - is it reasonable to buy one of the screwdrivers that is made for it that are available now if you needed to (un)screw one? The other options are to use a philips and damage the screw and suffer a lot of frustration, or to wait until Craftsman makes one (probably never).
That said..
1. OF COURSE you can make languages that are faster or slower to write code in.
2. Trivializing anyone who jumps ship on a language as being enchanted with the 'novelty of a new language' is obnoxious and arrogant.
Anybody who wants Oracle commercial support:
http://www.oracle.com/technetwork/java/javase/community/open...
Oracle's Commercial Distribution of the JDK
People who want the benefits of commercial support and predictability can choose to use Oracle's commercial distribution of the Java SE JDK or JRE. Oracle's commercial JDK releases will be built from the open-source code, for the most part. Since there's some encumbered code in the JDK, Oracle will continue to use that code in commercial releases until it is replaced by fully-functional open-source alternatives. To learn more about development and deployment support options, visit the Java Support site.
- Try-with-resources-Catch-Block [0]
- Fork/Join libraries from Doug Lea (author of Executor framework) [1]
- Inferred/Simpler generics in declarations (should have been in Java 5)
- NIO2, brand new/robust filesystem APIs [2]
- NIO2, treat ZIP/JAR files like directories of files for R/W [3]
- SDP support [4]
- String-in-switch (NOTE: check on performance implications of this for tight loops)
NOTE: Read through "COMPILATION" section here for details [6]
- Elliptic curve cryptography (when normal curves just don't cut it)
- Underscores in numbers (e.g. int million = 1_000_000;)
- XRender pipeline on Linux (Swing/Java2D rendering get a big boost)
- New sound synthesizer (replaces a proprietary lib that wasn't OS)
- XML stack finally got updated across the board.
- InvokeDynamic (already talked about numerous times below)
- Other Swing stuff I'm not all that pumped about.
I think the most exciting items are: 1. Try-with-resources
2. NIO2 filesystem API
3. InvokeDynamic
Features that got pushed to 8 (next year) that will be really exciting: - Modular programming (super packages? think OSGi-lite)
- Syntactic Sugar: Collection literals
List<String> people = {"Frank", "Mary", "Satan"};
- Closures
- Modularization of the JDK (JDK gets broken into core modules)
And one that I can't get confirmation on if it's in 7 or got pushed, index-access for List and Maps [5]: - List<String> people = {"Frank", "Mary", "Satan"};
System.out.println("Hello " + people[0]);
I understand that a lot of people don't find Java sexy any more, that is understandable, it has become a platform for what seems like a lot of next-series of languages.That being said, I've been working with Java since 1998 and still love it. I know people get a big kick out of writing code with no exception handlers and no curly braces, and programming is a creative/artistic process so you have to do what feels good... but none of that stuff ever bothered me.
I like being a pedantic programmer.
[0] http://www.javacodegeeks.com/2011/07/java-7-try-with-resourc...
[1] http://artisans-serverintellect-com.si-eioswww6.com/default....
[2] http://openjdk.java.net/projects/jdk7/features/#f250
[3] http://openjdk.java.net/projects/jdk7/features/#fa537814
[4] http://openjdk.java.net/projects/jdk7/features/#f639
[5] http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/0...
[6] http://mail.openjdk.java.net/pipermail/coin-dev/2009-Februar...
I just tried it out, it didn't get added to 7.
> String-in-switch (NOTE: check on performance implications of this for tight loops)
I haven't checked the performance, but I tried decompiling a String switch statement:
String test = "asdf";
switch (test) {
case "sss":
System.out.println("sss");
break;
case "asdf":
System.out.println("asdf");
break;
}
That decompiles to: switch(test.hashCode()) {
case 114195:
if(test.equals("sss"))
byte0 = 0;
break;
case 3003444:
if(test.equals("asdf"))
byte0 = 1;
break;
}
switch(byte0) {
case 0: // '\0'
System.out.println("sss");
break;
case 1: // '\001'
System.out.println("asdf");
break;
}
So it's one switch on the String's hashcode, with calls to equals to verify that the string is a match (and an if/else if/else block if you have multiple strings in the switch that have the same hashcode), assigning the result to a temp variable, and then a switch on a temp variable to execute your code.It looks like it would be fairly quick.
This looks the same as the original proposal -- using the hashCode and final verification via equals.
So in a typical case scenario you have the 1-time calculation of the String's hashCode (which is then cached by java.lang.String) and the two method calls.
.equals() is the only thing that could get away from you performance wise, because unless string1 == string2 or are different lengths, you fall into a char-by-char comparison loop.
That could be a shitty surprise if you have a bunch of constants like "SAVE, RMVE, DELT, INST, UPDT" and don't realize what you are causing to happen under the covers.
I'd be curious (now) what actually happens with using Enums in switch statements to see what kind of hidden code is actually getting executed.
## ASIDE: An interesting alternative to switch statements with Enums: http://francisoud.blogspot.com/2008/02/better-way-to-use-jav...
Seems really a-typical though.
## UPDATE: It looks like using Enums ends up getting translated to:
switch(enum.ordinal())
calls followed up goto statements to the case labels. So enums should be practically just as performant as constant numeric values except for the method call.If the JVM is smart enough to replace the calls to 'ordinal' with the constant return value, then it should be right on par with using numerical constants which would be sweet and make using the strategy outlined in that link possibly a nice performant alternative to normal Enum use.
I checked what happens when you use an enum, and it generates some funky code. It creates an anonymous inner class with a static initializer for an array of ints. It uses the ordinal value to assign a sequential number starting with one. Then the switch statement is on intArray[theEnum.ordinal()], and the case statements start with 1. Here's the code:
class Test2{
public static void main(String[] args) {
MyEnum en = MyEnum.ONE;
switch (en) {
case ONE:
System.out.println("one"); break;
case TWO:
System.out.println("two"); break;
default:
System.out.println("default");
}
}
}
enum MyEnum {
ONE, TWO, THREE;
}
Decompiled (after being compiled with jdk1.7.0): public static void main(String args[])
{
MyEnum myenum = MyEnum.ONE;
static class _cls1
{
static final int $SwitchMap$MyEnum[];
static
{
$SwitchMap$MyEnum = new int[MyEnum.values().length];
try
{
$SwitchMap$MyEnum[MyEnum.ONE.ordinal()] = 1;
}
catch(NoSuchFieldError nosuchfielderror) { }
try
{
$SwitchMap$MyEnum[MyEnum.TWO.ordinal()] = 2;
}
catch(NoSuchFieldError nosuchfielderror1) { }
}
}
switch(_cls1.$SwitchMap$MyEnum[myenum.ordinal()])
{
case 1: // '\001'
System.out.println("one");
break;
case 2: // '\002'
System.out.println("two");
break;
default:
System.out.println("default");
break;
}
}
I wonder why it doesn't just switch on the ordinal directly. It's also worth noting that it has to make an array for MyEnum.values().length. This means if you have an enum with a lot of values, you're wasting a lot of memory (especially since it creates this array every class you use a switch in).
I tried with an enum with 40 values, and it didn't switch to a map. Maybe there's some higher threshold where it would switch to a map instead (but again, I don't understand why it wouldn't switch on ordinal() directly).Here's the doc on Collection Literals, BTW.
https://docs.google.com/Doc?id=ddv8ts74_4cbnn5mhj
Collection Literals are actually better than string literals, because they only enforce an interface, not an implemenation.
The closures that are proposed are more like a bolted on psuedo solution, basically syntactic sugar that makes the language more complex. You can only use them in SAM (Single Abstract Method) situations. If only they just added a simple lisp like lambda expression...
[0] http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-3...
List<Person> persons = Humans.list(); List<Person> adults = new ArrayList<Person>(); for(Person p: persons) { if(p.age>=18){ adults.add(p); } }
Notice how the logic (filtering a list) gets drowned in irrelevant details such as creating the result list, iterating over the list, and accumulating the matching elements.
The alternative (the poor man's functional Java) with libs like Google collections would look like:
List<Person> adults = persons.filter(new Filter<Person>() {
@Override public boolean accept(Person t) { return t.age>=18; } });
Notice the noise added by the anonymous inner class.
Now, with lambdas, we end up with (once the collections are augmented methods like filter, map, reduce, etc.):
List<Person> adults = persons.filter(#{p -> p.age >= 18});
A one-liner, where the core logic (comparing the age to 18) clearly stands out.
The auto conversions of lambdas to SAM types is a spark of genius if you ask me. But I'm not happy with the decision of not implementing structural types in Java. IMO, this will lead to a Cambrian explosion in the number of SAM types, types like Mapper<S, T>, Reducer, Folder, Filter or Predicate, plus the custom types added by various frameworks.
Sort of in the same vein as static imports (as far as usability) but has a really nice added side effect of exporting a default impl from an interface that can be overridden.
Thanks!
[1] http://www.baptiste-wicht.com/2010/05/java-7-add-public-defe...
I find it breathtaking this isn't core yet. I was writing test fixture support code for 1.4 to easily and DRYly generate lists of up to 10 items, which required 10 copy-paste functions each with a different number of arguments. 1.5 came along and made it possible to easily do it with one function thanks to varargs, but it's 6 years later and still no collection literals!
List<String> people = ImmutableList.of("Frank", "Mary", "Bob");
There's also ImmutableSet and many other goodies, to say the least. For instantiation of these generic types, you can do: List<String> people = Lists.newArrayList();
Map<String,Integer> scores = Maps.newHashMap();
and so on. List<String> people = Arrays.asList("Frank", "Mary", "Bob");
[1] http://download.oracle.com/javase/1.5.0/docs/api/java/util/A...It is like the Java world hit the 'pause' button on really ambitious stuff for a few years and the only things that got into releases were the laser-sharp-focused features that the teams needed no variation on. They knew exactly what the feature was, where to take it and when to ship it.
I think it was for the better, because now there is all this pent up energy getting reinjected into the platform and we'll see 8 next year with the rest of all these goodies and hopefully 9/10 2 years after that.
Pretty good recovery IMO. At least it didn't languish and die a horrible death or something.
I think adding special syntax rules is a pretty bad idea.
Try Scala! (So do I ;)
Try Scala! (So do I ;))
then?
(So do I ;\))BTW, this issue with emoticons and parenthesis was also subject of an XKCD comic: http://www.xkcd.com/541/
UPDATE: Couldn't add it to the original post (edit has expired), here is more info about Joda Time for Java 8[1] for folks that are interested.
[1] http://www.jroller.com/scolebourne/entry/what_about_jsr_310
JSR 310 is not Joda for Java 8 (or 7). It's by Joda's author and uses a very similar API, but it's a cleanroom implementation and not compatible with Joda: over time, Stephen Colebourne (Joda lead dev) found core issues in Joda, and JSR-310 is the occasion to use the lessons learned from Joda.
"... enable[s] implementers of compilers for dynamically typed languages, that is, the people who develop compilers for languages such as JRuby and Jython, to generate bytecode that runs extremely fast in the JVM."
[1] http://blogs.oracle.com/jrose/entry/jsr_292_launched_in_java
[2] http://java.sun.com/developer/technicalArticles/DynTypeLang/...
"There’s a very real chance that invokedynamic could improve JRuby performance many times, putting us on par with our statically-typed brothers like Java and Scala. And that means you can write Ruby code without fear. Awesome."
http://www.engineyard.com/blog/2011/jruby-1-6-released-now-w...
For example see here, pvec: http://clojure.org/other_libraries
Of course, improvements like the GC1, improvements in HotSpot etc, they all will make Clojure apps run even faster.
1. http://blog.headius.com/2008/09/first-taste-of-invokedynamic...
Welcome to the sixties, Java!
Sorry, I couldn't help it >:D
I'm thinking Oracle tried to put a lot more locks on this version of Java, to make it theirs, and not so open source anymore.
Having said that, GPL in theory ensures users and even people making derivatives of Java are protected from patent action by Oracle.
Commercial Features appears to be jRockit technology.
With java "deprecated" in lion, who knows how long it will take this time.
Apple and Oracle will be working together to create an OpenJDK for Macs.
http://www.macstories.net/news/apple-and-oracle-announce-ope...
In the future, they plan on placing Oracle in that role, I guess, but it hasn't happened yet. All Lion does is change it from shipped with the OS to not.
I'm especially happy to see some of the language syntax that makes your standard try/catch/finally blocks a little cleaner and less error prone.
otherwise companies will continue to migrate to faster
evolving languages
That still use the patent-encumbered JVM.Could you provide citations of any studies done please. i.e. How development times differ for small projects and large projects. For small projects I could see other languages being faster, what about large project or really large projects?
Edid: You change the link didnt you? Im talking about the image from here: http://blogs.oracle.com/theplanetarium/entry/summarizing_jav...
that worried me little bit. what do you think ?