118
Why Java Sucks & C# Rocks ZhaoJie @ SNDA April, 2010

Why Java Sucks and C# Rocks (Final)

  • Upload
    jeffz

  • View
    134.366

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Why Java Sucks and C# Rocks (Final)

WhyJava Sucks & C# Rocks

ZhaoJie @ SNDAApril, 2010

Page 2: Why Java Sucks and C# Rocks (Final)

About me

• Name: 赵劼(老赵,Jeffrey Zhao)

• Blog: http://blog.zhaojie.me/

• Twitter: @jeffz_cn

• Email: [email protected]

Page 3: Why Java Sucks and C# Rocks (Final)

Experiences

• Pascal, VB 5 & 6, Delphi before 2002

• Java programmer from 2002 to 2004

• C# programmer since 2004

Page 4: Why Java Sucks and C# Rocks (Final)

I’m going to talk about ...

Page 5: Why Java Sucks and C# Rocks (Final)

• Languages features

• Programming paradigms

• Usage patterns

• Why we should throw Java language away

Page 6: Why Java Sucks and C# Rocks (Final)

I’m NOT going to make you ...

Page 7: Why Java Sucks and C# Rocks (Final)

• Believe CLR is better than JVM

• Believe .NET is better than Java platform

• Get rid of Java language right away

• Use C# instead of Java language

• Use .NET instead of Java platform

Page 8: Why Java Sucks and C# Rocks (Final)

• 2002 - Java 1.4 & C# 1.0

• 2004 - Java 5.0 & C# 2.0

• 2006 - Java 6

• 2008 - C# 3.0

• 2010 - Java 7 & C# 4

Timeline

Page 9: Why Java Sucks and C# Rocks (Final)

So Java programmers, hold your breath ...

Page 10: Why Java Sucks and C# Rocks (Final)

Let’s start from the very beginning ...

Page 11: Why Java Sucks and C# Rocks (Final)

Is Java a pure object-oriented language?

Page 12: Why Java Sucks and C# Rocks (Final)

No.Primitive types are not

objects.

Page 13: Why Java Sucks and C# Rocks (Final)

ArrayList  list  =  new  ArrayList();list.add(5);  //  cannot  compileint  i  =  (int)list.get(0);  //  cannot  compile

int  hash  =  3.hashCode();  //  cannot  compile

In Java you can NOT ...

Page 14: Why Java Sucks and C# Rocks (Final)

You have to ...

ArrayList  list  =  new  ArrayList();Integer  five  =  Integer.valueOf(5);list.add(five);int  i  =  ((Integer)list.get(0)).intValue();

Integer  three  =  Integer.valueOf(3);int  hash  =  three.hashCode();

Page 15: Why Java Sucks and C# Rocks (Final)

In C# ...

• No primitive types

• All types are subtypes of Object.

• Just value types and reference types

• Programmers can build custom value types

• Value types can be assigned to Object variables without explicit casting.

Page 16: Why Java Sucks and C# Rocks (Final)

So you can always ...

ArrayList  list  =  new  ArrayList();list.Add(5);int  i  =  (int)list[0];

int  hash  =  3.GetHashCode();

Page 17: Why Java Sucks and C# Rocks (Final)

Thank God!Here comes Java 5.0!

Page 18: Why Java Sucks and C# Rocks (Final)

Finally you can ...

ArrayList  list  =  new  ArrayList();list.add(5);  //  auto  boxing

//  auto  unboxingint  i  =  (Integer)list.get(0);

//  you  still  can’t  do  this!int  hash  =  3.hashCode();

Page 19: Why Java Sucks and C# Rocks (Final)

Java 5.0 also brings ...

• Annotation - allows language constructs to be tagged with additional data

• Enumerations - the “enum” keyword creates a typesafe, ordered list of values

• Varargs - make passing an array as parameter easier then before

• Enhanced “for” loop - simplified iteration

Page 20: Why Java Sucks and C# Rocks (Final)

But most of these features were already provided by C# 1.0 ...

Page 21: Why Java Sucks and C# Rocks (Final)

... so who is thecopy cat?

Page 22: Why Java Sucks and C# Rocks (Final)

OK, let’s forget it and look deep inside ...

Page 23: Why Java Sucks and C# Rocks (Final)

Annotations in Java are interfaces.

Attributes in C# are classes.

Page 24: Why Java Sucks and C# Rocks (Final)

Differences? Let’s start coding!

Page 25: Why Java Sucks and C# Rocks (Final)

Annotation’s shortages

• Strange convention

• Anemic object

• Hard to unit test

Page 26: Why Java Sucks and C# Rocks (Final)

Well, Java 5.0 also brings Generics, but ...

Page 27: Why Java Sucks and C# Rocks (Final)

Type erasure: type information will be lost

after compiling!

Page 28: Why Java Sucks and C# Rocks (Final)

What’s the output?

List<String>  a  =  new  ArrayList<String>();List<Integer>  b  =  new  ArrayList<Integer>();

bool  sameType  =  a.getClass()  ==  b.getClass();System.out.println(sameType);

Page 29: Why Java Sucks and C# Rocks (Final)

And you can’t do this

public  class  MyClass<E>  {        public  static  void  myMethod(Object  item)  {                if  (item  instanceof  E)  {  //  Compiler  error                        ...                }                E  item2  =  new  E();  //  Compiler  error                E[]  iArray  =  new  E[10];  //  Compiler  error        }}

Page 30: Why Java Sucks and C# Rocks (Final)

And “use-site variance” is strange and stupid.

Page 31: Why Java Sucks and C# Rocks (Final)

Well, maybe I’m biased. I can give you a

separate talk about it.

Page 32: Why Java Sucks and C# Rocks (Final)

Let keep moving.

Page 33: Why Java Sucks and C# Rocks (Final)

The same time Java released 5.0 ...

Page 34: Why Java Sucks and C# Rocks (Final)

C# 2.0 comes with

• Better generics (comparing to Java 5.0)

• Anonymous methods (hello, closure!)

• “yield” keyword - iterator creation can’t be more easier

Page 35: Why Java Sucks and C# Rocks (Final)

Why closure matters?

Page 36: Why Java Sucks and C# Rocks (Final)

And “yield” is only about iterator?

Page 37: Why Java Sucks and C# Rocks (Final)

Let’s see some samples.

Page 38: Why Java Sucks and C# Rocks (Final)

So closure and yield are ...

• Increasing productivity dramatically

• Coming with new programming patterns

• Important features for async / parallel / reactive programming

• The primitives for Fibers - lightweight computation units

Page 39: Why Java Sucks and C# Rocks (Final)

Two years after C# 2.0, Java 6 released with ...

Page 40: Why Java Sucks and C# Rocks (Final)

Nothing!

Page 41: Why Java Sucks and C# Rocks (Final)

Nothing!!

Page 42: Why Java Sucks and C# Rocks (Final)

Nothing!!!

Page 43: Why Java Sucks and C# Rocks (Final)

Give me a break and leave me alone ...

Page 44: Why Java Sucks and C# Rocks (Final)

OK, I admit it ...

Page 45: Why Java Sucks and C# Rocks (Final)

Java 6 is cool because of ...

• pluggable annotations (JSR 269): customized compile-time processing (Project Lombok)

• dramatic JVM improvements: compiler performnace, start-up time, GC, JIT...

• scripting language support (JSR 223): Rhino JavaScript for Java included

Page 46: Why Java Sucks and C# Rocks (Final)

But we’re talking about language, so ...

Page 47: Why Java Sucks and C# Rocks (Final)

Let’s move on toC# 3.0,

which brings us ...

Page 48: Why Java Sucks and C# Rocks (Final)

LINQ(Language Integrated

Query)

Page 49: Why Java Sucks and C# Rocks (Final)

Only LINQ?

Page 50: Why Java Sucks and C# Rocks (Final)

Yes! The great LINQ!

Page 51: Why Java Sucks and C# Rocks (Final)

LINQ is made up of ...• Extension method - safely add methods to

types without breaking anything

• Lambda expression - make C# a better functional language

• Anonymous type - compile time auto generated types

• Expression tree - language-level code in the form of data

Page 52: Why Java Sucks and C# Rocks (Final)

Now tell me, which one do you prefer?

Page 53: Why Java Sucks and C# Rocks (Final)

BBCode to HTML

//  JavaUtil.stripWhites(        Util.stripXss(                Util.bbToHtml(bbCode)))

//  C#bbCode.BBToHtml().StripXss().StripWhites()

Page 54: Why Java Sucks and C# Rocks (Final)

Sorting an array//  C#users.Sort((u1,  u2)  =>  u1.Age  -­‐  u2.Age);

//  JavaArrays.sort(        users,        new  Comparator<User>()  {                public  int  compare(User  u1,  User  u2)  {                        return  u1.Age  -­‐  u2.Age;                }        });

Page 55: Why Java Sucks and C# Rocks (Final)

JSON Output (C#)

List<User>  userList  =  ...;var  json  =  new  {        errorCode  =  0,        message  =  "OK",        users  =  userList.Select(u  =>  new  {                name  =  u.FirstName  +  "  "  +  u.LastName,                age  =  (DateTime.Now  -­‐  u.BirthData).Year        }),};

Page 56: Why Java Sucks and C# Rocks (Final)

JSON Output (Java)JSONObject  obj  =  new  JSONObject();obj.put("errorCode",  0);obj.put("message",  "OK");

JSONArray  userArray  =  new  JSONArray();for  (User  u:  userList)  {        JSONObject  objUser  =  new  JSONObject();        objUser.put("name",  /*  get  full  name  */);        objUser.put("age",  /*  calculate  age  */);        userArray.add(objUser);}

obj.put("users",  userArray);

Page 57: Why Java Sucks and C# Rocks (Final)

Is C# just full of Syntactic Sugar?

Page 58: Why Java Sucks and C# Rocks (Final)

I don’t think so.

Page 59: Why Java Sucks and C# Rocks (Final)

It really changed my mind

• Real-world Functional Programming

• Write declarative code (anti-for)

• Make code / API more and more elegant

Page 60: Why Java Sucks and C# Rocks (Final)

Please write a program to index a list of

keywords (like books).

Page 61: Why Java Sucks and C# Rocks (Final)

Explanation

• Input: List<String>

• Output: Map<Character, List<String>>

• The key of map is ‘a’ to ‘z’

• Each list in the map are sorted

Page 62: Why Java Sucks and C# Rocks (Final)

Let’s see the Java code first ...

Page 63: Why Java Sucks and C# Rocks (Final)

List<String>  keywords  =  ...;Map<Character,  List<String>>  result  =  new  HashMap<>();

for  (String  k:  keywords)  {   char  firstChar  =  k.charAt(0);     if  (!result.containsKey(firstChar))  {     result.put(firstChar,  new  ArrayList<String>());   }     result.get(firstChar).add(k);}

for  (List<String>  list:  result.values())  {   Collections.sort(list);}

Page 64: Why Java Sucks and C# Rocks (Final)

List<String>  keywords  =  ...;Map<Character,  List<String>>  result  =  new  HashMap<>();

for  (String  k:  keywords)  {   char  firstChar  =  k.charAt(0);     if  (!result.containsKey(firstChar))  {     result.put(firstChar,  new  ArrayList<String>());   }     result.get(firstChar).add(k);}

for  (List<String>  list:  result.values())  {   Collections.sort(list);} Imperative code

“How” to do

Page 65: Why Java Sucks and C# Rocks (Final)

Quite easy, ah?Guess how does C#

code look like?

Page 66: Why Java Sucks and C# Rocks (Final)

List<string>  keywords  =  ...;var  result  =  keywords        .GroupBy(k  =>  k[0])        .ToDictionary(                g  =>  g.Key,                g  =>  g.OrderBy(k  =>  k).ToList());

Page 67: Why Java Sucks and C# Rocks (Final)

List<string>  keywords  =  ...;var  result  =  keywords        .GroupBy(k  =>  k[0])        .ToDictionary(                g  =>  g.Key,                g  =>  g.OrderBy(k  =>  k).ToList());

Declarative code

“What” to do

Page 68: Why Java Sucks and C# Rocks (Final)

Amazing, isn’t it?

Page 69: Why Java Sucks and C# Rocks (Final)

What about the Java community?

Page 71: Why Java Sucks and C# Rocks (Final)

... do you really want to write code like this?

Page 72: Why Java Sucks and C# Rocks (Final)

keywords    .groupBy(        new  F<String,  Character>  {            public  Character  f(String  s)  {  return  s.charAt(0);  }        })    .toMap(        new  F<Grouping<Character,  String>,  Character>  {            public  Character  f(Grouping<Char,  String>  g)  {                  return  g.getKey();            }        },        new  F<Grouping<Character,  String>,  List<String>>  {            public  List<String>  f(Grouping<Character,  String>  g)  {                return  g                    .orderBy(                        new  F<String,  String>  {                            public  String  f(String  s)  {  return  s;  }                        })                    .toList();            }        });

Page 73: Why Java Sucks and C# Rocks (Final)

It’s really a pain without lambda expressions.

Page 74: Why Java Sucks and C# Rocks (Final)

Fortunately, Java 7 will provide a sort of lambda syntax.

Page 75: Why Java Sucks and C# Rocks (Final)

keywords        .groupBy({  String  k  =>  k.charAt(0)  })        .toMap(                {  Grouping<Character,  String>  g  =>  g.getKey()  },                {  Grouping<Character,  String>  g  =>                          g.orderBy({  String  c  =>  c  }).toList()  });

Page 76: Why Java Sucks and C# Rocks (Final)

Much better,but still noisy because

of lacking ...

Page 77: Why Java Sucks and C# Rocks (Final)

Type Inference

Page 78: Why Java Sucks and C# Rocks (Final)

C# is an FPL because of

• First class functions (as .NET delegates)

• Elegant lambda expression syntax

• Enough type inference for most cases

• Full set of functional primitives in BCL

• Great extensibility (by extension method)

Page 79: Why Java Sucks and C# Rocks (Final)

Fixed-point combinatorstatic  Func<T,  TResult>  Fix<T,  TResult>(        Func<Func<T,  TResult>,        Func<T,  TResult>>  f){        return  x  =>  f(Fix(f))(x);}

var  fib  =  Fix<int,  int>(f  =>  x  =>        x  <=  1  ?  1  :  f(x  -­‐  1)  +  f(x  -­‐  2));

Page 80: Why Java Sucks and C# Rocks (Final)

Is it really useful in real world programming?

Page 81: Why Java Sucks and C# Rocks (Final)

Yes, of course. I can’t live without the

functional features now.

Page 82: Why Java Sucks and C# Rocks (Final)

Let me prove it to you.

Page 83: Why Java Sucks and C# Rocks (Final)

Expression Trees

Page 84: Why Java Sucks and C# Rocks (Final)

Code as Expressions

• Serializable code

• Consistent coding style

• Strong typing

• Compile-time verification

• Generate dynamic method easily

Page 85: Why Java Sucks and C# Rocks (Final)

Many projects use Expressions.

Let me show you sth.

Page 86: Why Java Sucks and C# Rocks (Final)

Java 7 is coming• Automatic Resource Management

• Collection Literals

• Improved Type Inference for Generics Instance Creation

• Language support for JSR 292

• Simplified Varargs Method Invocation

• Support for Strings in Switch Statements

Page 87: Why Java Sucks and C# Rocks (Final)

Most of them are provided by C# now

Page 88: Why Java Sucks and C# Rocks (Final)

What’s new in C# 4

• Default parameters

• Naming parameters

• Language build-in dynamic support

• Convariance / Contravariance

Page 89: Why Java Sucks and C# Rocks (Final)

Taste a bit

Page 90: Why Java Sucks and C# Rocks (Final)

Ruby-like Markup Builder

dynamic  b  =  new  XmlMarkupBuilder();var  persons  =  new  []  {        new  Person("Tom",  10),        new  Person("Jerry",  8)};XElement  xml  =          b.persons(                from  p  in  persons                select  b.person(p.Name,  age:  p.Age));

Page 91: Why Java Sucks and C# Rocks (Final)

Ruby-like Markup Builder

dynamic  b  =  new  XmlMarkupBuilder();var  persons  =  new  []  {        new  Person("Tom",  10),        new  Person("Jerry",  8)};XElement  xml  =          b.persons(                from  p  in  persons                select  b.person(p.Name,  age:  p.Age));

<persons>    <person  age=”10”>Tom</person>    <person  age=”8”>Jerry</person></persons>

Page 92: Why Java Sucks and C# Rocks (Final)

Convariance & Contravariance

• Improving the generics type system

• More powerful and safer than Java’s use-site variance

• Really a brain fucker

Page 93: Why Java Sucks and C# Rocks (Final)

Summary

• (maybe I should put a table here...)

Page 94: Why Java Sucks and C# Rocks (Final)

C# always make me happy when coding ...

Page 95: Why Java Sucks and C# Rocks (Final)

... and it brings us lots of useful code patterns

Page 96: Why Java Sucks and C# Rocks (Final)

But Java keeps me away from the great JVM

Page 97: Why Java Sucks and C# Rocks (Final)

Java is popular since it’s ...

• Fast - designed for the JVM, as C is designed for the machine

• Stable - it’s always one and only one way to do things

• Easy - most of the features are quite easy to learn

Page 98: Why Java Sucks and C# Rocks (Final)

But what’s wrong with Java?

Page 99: Why Java Sucks and C# Rocks (Final)

Java is too noisy

• The only way to work is not simple

• Write more and do less

• Little room for smart people.

Page 100: Why Java Sucks and C# Rocks (Final)

Java is weird ...

int  a  =  1000,  b  =  1000;System.out.println(a  ==  b);  //  true

Integer  c  =  1000,  d  =  1000;System.out.println(c  ==  d);  //  false

Integer  e  =  100,  f  =  100;System.out.println(e  ==  f);  //  true

Page 101: Why Java Sucks and C# Rocks (Final)

... and becoming even more

//  C#dynamic  o  =  ...;int  i  =  o.SomeMethod(true,  “hello”);

//  JavaObject  o  =  ...;Object[]  args  =  new  Object[]  {  true,  “hello”  };InvokeDynamic.<int>SomeMethod(o,  args);

Page 102: Why Java Sucks and C# Rocks (Final)

If JVM is machine ...

• Java byte code is the machine code

• Java language is the ASM.

Page 103: Why Java Sucks and C# Rocks (Final)

Would you like to program with ASM?

Page 104: Why Java Sucks and C# Rocks (Final)

What should we do?

Page 105: Why Java Sucks and C# Rocks (Final)

Let’s use C# instead!

Page 106: Why Java Sucks and C# Rocks (Final)

Just kidding

Page 107: Why Java Sucks and C# Rocks (Final)

We can’t use C# since ...

• JVM is powerful

• Java libraries are great

• Platform migration is a nightmare

Page 108: Why Java Sucks and C# Rocks (Final)

So choose another language!

Page 109: Why Java Sucks and C# Rocks (Final)

Languages on JVM

• JRuby

• Jython

• Groovy

• Clojure

• Scala

Page 110: Why Java Sucks and C# Rocks (Final)

All these languages are

• More powerful

• Run on JVM

• Interop with Java seamlessly

• Mature enough

• Successful in real world

Page 111: Why Java Sucks and C# Rocks (Final)

Scala makes me write Java program again.

Page 112: Why Java Sucks and C# Rocks (Final)

Why Scala?

• a statically-compiled language

• a pure object-oriented languages

• clean & powerful generic support (including convariance & contravariance)

• enough functional features

• actor-based programming model

• really scalable

Page 113: Why Java Sucks and C# Rocks (Final)

What do you think?

Page 114: Why Java Sucks and C# Rocks (Final)

Contact me via

• Email: [email protected]

• Twitter: @jeffz_cn

• Blog: http://blog.zhaojie.me/

Page 115: Why Java Sucks and C# Rocks (Final)

Show me your idea ...

Page 116: Why Java Sucks and C# Rocks (Final)

... and prove it to me

Page 117: Why Java Sucks and C# Rocks (Final)

Future Talks

• Why F# matters

• Why Scala matters (TBD.)

• Generics in Java, Scala, C# & F#

• The beauty of Parallel Library

• Real-world reactive programming

Page 118: Why Java Sucks and C# Rocks (Final)

Thanks