SlideShare una empresa de Scribd logo
1 de 118
Descargar para leer sin conexión
Why
Java Sucks & C# Rocks
      ZhaoJie @ SNDA
         April, 2010
About me

• Name:                   Jeffrey Zhao

• Blog: http://blog.zhaojie.me/
• Twitter: @jeffz_cn
• Email: jeffz@live.com
Experiences

• Pascal,VB 5 & 6, Delphi before 2002
• Java programmer from 2002 to 2004
• C# programmer since 2004
I’m going to talk
    about ...
• Languages features
• Programming paradigms
• Usage patterns
• Why we should throw Java language away
I’m NOT going to make
       you ...
• 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
Timeline

• 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
So Java programmers,
 hold your breath ...
Let’s start from the
 very beginning ...
Is Java a pure object-
  oriented language?
No.
Primitive types are not
        objects.
In Java you can NOT ...

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

int	
  hash	
  =	
  3.hashCode();	
  //	
  cannot	
  compile
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();
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.
So you can always ...

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

int	
  hash	
  =	
  3.GetHashCode();
Thank God!
Here comes Java 5.0!
Finally you can ...
ArrayList	
  list	
  =	
  new	
  ArrayList();
list.add(5);	
  //	
  auto	
  boxing

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

//	
  you	
  still	
  can’t	
  do	
  this!
int	
  hash	
  =	
  3.hashCode();
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
But most of these
features were already
provided by C# 1.0 ...
... so who is the
     copy cat?
OK, let’s forget it and
 look deep inside ...
Annotations in Java are
     interfaces.

 Attributes in C# are
       classes.
Differences?
Let’s start coding!
Annotation’s shortages

• Strange convention
• Anemic object
• Hard to unit test
Well, Java 5.0 also
brings Generics, but ...
Type erasure: type
information will be lost
    after compiling!
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);
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
	
  	
  	
  	
  }
}
And “use-site variance”
 is strange and stupid.
Well, maybe I’m biased.
   I can give you a
separate talk about it.
Let keep moving.
The same time Java
  released 5.0 ...
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
Why closure matters?
And “yield” is only
 about iterator?
Let’s see some samples.
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
Two years after C# 2.0,
 Java 6 released with ...
Nothing!
Nothing!!
Nothing!!!
Give me a break and
 leave me alone ...
OK, I admit it ...
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
But we’re talking about
    language, so ...
Let’s move on to
     C# 3.0,
which brings us ...
LINQ
(Language Integrated
      Query)
Only LINQ?
Yes! The great LINQ!
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
Now tell me, which one
   do you prefer?
BBCode to HTML

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

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

//	
  Java
Arrays.sort(
	
  	
  	
  	
  users,
	
  	
  	
  	
  new	
  Comparator<User>()	
  {
	
  	
  	
  	
  	
  	
  	
  	
  public	
  int	
  compare(User	
  u1,	
  User	
  u2)	
  {
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  u1.Age	
  -­‐	
  u2.Age;
	
  	
  	
  	
  	
  	
  	
  	
  }
	
  	
  	
  	
  });
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
	
  	
  	
  	
  }),
};
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);
Is C# just full of
Syntactic Sugar?
I don’t think so.
It really changed my mind

 • Real-world Functional Programming
 • Write declarative code (anti-for)
 • Make code / API more and more elegant
Please write a program
   to index a list of
keywords (like books).
Explanation

• Input: List<String>
• Output: Map<Character, List<String>>
• The key of map is ‘a’ to ‘z’
• Each list in the map are sorted
Let’s see the Java code
         first ...
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);
}
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
Quite easy, ah?
Guess how does C#
  code look like?
List<string>	
  keywords	
  =	
  ...;
var	
  result	
  =	
  keywords
	
  	
  	
  	
  .GroupBy(k	
  =>	
  k[0])
	
  	
  	
  	
  .ToDictionary(
	
  	
  	
  	
  	
  	
  	
  	
  g	
  =>	
  g.Key,
	
  	
  	
  	
  	
  	
  	
  	
  g	
  =>	
  g.OrderBy(k	
  =>	
  k).ToList());
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
Amazing, isn’t it?
What about the Java
  community?
Well, the Functional
Java project is out!
       But ...
... do you really want to
   write code like this?
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();
	
  	
  	
  	
  	
  	
  }
	
  	
  	
  	
  });
It’s really a pain without
   lambda expressions.
Fortunately, Java 7 will
  provide a sort of
   lambda syntax.
keywords
	
  	
  	
  	
  .groupBy({	
  String	
  k	
  =>	
  k.charAt(0)	
  })
	
  	
  	
  	
  .toMap(
	
  	
  	
  	
  	
  	
  	
  	
  {	
  Grouping<Character,	
  String>	
  g	
  =>	
  g.getKey()	
  },
	
  	
  	
  	
  	
  	
  	
  	
  {	
  Grouping<Character,	
  String>	
  g	
  =>	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  g.orderBy({	
  String	
  c	
  =>	
  c	
  }).toList()	
  });
Much better,
but still noisy because
     of lacking ...
Type Inference
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)
Fixed-point combinator
static	
  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));
Is it really useful in real
  world programming?
Yes, of course.
 I can’t live without the
functional features now.
Let me prove it to you.
Expression Trees
Code as Expressions

• Serializable code
• Consistent coding style
• Strong typing
• Compile-time verification
• Generate dynamic method easily
Many projects use
    Expressions.
Let me show you sth.
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
Most of them are
provided by C# now
What’s new in C# 4

• Default parameters
• Naming parameters
• Language build-in dynamic support
• Convariance / Contravariance
Taste a bit
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));
Ruby-like Markup Builder
dynamic	
  b	
  =	
  new	
  XmlMarkupBuilder();
var	
  persons	
  =	
  new	
  []	
  {
	
  	
  	
  	
  new	
  Person("Tom",	
  10),
	
  	
  	
  	
  new	
  Person("Jerry",	
  8)
};                                                            <persons>
XElement	
  xml	
  =	
                                     	
  	
  <person	
  age=”10”>Tom</person>
                                                           	
  	
  <person	
  age=”8”>Jerry</person>
	
  	
  	
  	
  b.persons(                                   </persons>
	
  	
  	
  	
  	
  	
  	
  	
  from	
  p	
  in	
  persons
	
  	
  	
  	
  	
  	
  	
  	
  select	
  b.person(p.Name,	
  age:	
  p.Age));
Convariance &
       Contravariance

• Improving the generics type system
• More powerful and safer than Java’s use-site
  variance
• Really a brain fucker
Summary


• (maybe I should put a table here...)
C# always make me
happy when coding ...
... and it brings us lots
of useful code patterns
But Java keeps me away
  from the great JVM
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
But what’s wrong with
        Java?
Java is too noisy

• The only way to work is not simple
• Write more and do less
• Little room for smart people.
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
... and becoming even more
//	
  C#
dynamic	
  o	
  =	
  ...;
int	
  i	
  =	
  o.SomeMethod(true,	
  “hello”);

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


• Java byte code is the machine code
• Java language is the ASM.
Would you like to
program with ASM?
What should we do?
Let’s use C# instead!
Just kidding
We can’t use C# since ...

 • JVM is powerful
 • Java libraries are great
 • Platform migration is a nightmare
So choose another
     language!
Languages on JVM

• JRuby
• Jython
• Groovy
• Clojure
• Scala
All these languages are

• More powerful
• Run on JVM
• Interop with Java seamlessly
• Mature enough
• Successful in real world
Scala makes me write
 Java program again.
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
What do you think?
Contact me via

• Email: jeffz@live.com
• Twitter: @jeffz_cn
• Blog: http://blog.zhaojie.me/
Show me your idea ...
... and prove it to me
Future Talks

• Why F# matters
• Why Scala matters (TBD.)
• Generics in Java, Scala, C# & F#
• The beauty of Parallel Library
• Real-world reactive programming
Thanks

Más contenido relacionado

La actualidad más candente

History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
Yoshifumi Kawai
 

La actualidad más candente (20)

스타트업에서 기술책임자로 살아가기
스타트업에서 기술책임자로 살아가기스타트업에서 기술책임자로 살아가기
스타트업에서 기술책임자로 살아가기
 
JWTを使った簡易SSOで徐々にシステムをリニューアルしている話
JWTを使った簡易SSOで徐々にシステムをリニューアルしている話JWTを使った簡易SSOで徐々にシステムをリニューアルしている話
JWTを使った簡易SSOで徐々にシステムをリニューアルしている話
 
Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.Django, 저는 이렇게 씁니다.
Django, 저는 이렇게 씁니다.
 
적당한 스터디 발표자료 만들기
적당한 스터디 발표자료 만들기적당한 스터디 발표자료 만들기
적당한 스터디 발표자료 만들기
 
ASP.NETの進化とASP.NET Core Blazorの凄さ
ASP.NETの進化とASP.NET Core Blazorの凄さASP.NETの進化とASP.NET Core Blazorの凄さ
ASP.NETの進化とASP.NET Core Blazorの凄さ
 
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
[NDC18] 만들고 붓고 부수고 - 〈야생의 땅: 듀랑고〉 서버 관리 배포 이야기
 
PHPの戻り値型宣言でselfを使ってみよう
PHPの戻り値型宣言でselfを使ってみようPHPの戻り値型宣言でselfを使ってみよう
PHPの戻り値型宣言でselfを使ってみよう
 
SQLアンチパターン - 開発者を待ち受ける25の落とし穴 (拡大版)
SQLアンチパターン - 開発者を待ち受ける25の落とし穴 (拡大版)SQLアンチパターン - 開発者を待ち受ける25の落とし穴 (拡大版)
SQLアンチパターン - 開発者を待ち受ける25の落とし穴 (拡大版)
 
ドメイン駆動設計サンプルコードの徹底解説
ドメイン駆動設計サンプルコードの徹底解説ドメイン駆動設計サンプルコードの徹底解説
ドメイン駆動設計サンプルコードの徹底解説
 
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
History & Practices for UniRx UniRxの歴史、或いは開発(中)タイトルの用例と落とし穴の回避法
 
Unicode文字列処理
Unicode文字列処理Unicode文字列処理
Unicode文字列処理
 
PHP AST 徹底解説
PHP AST 徹底解説PHP AST 徹底解説
PHP AST 徹底解説
 
リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜
リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜 リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜
リアルタイムサーバー 〜Erlang/OTPで作るPubSubサーバー〜
 
ADRという考えを取り入れてみて
ADRという考えを取り入れてみてADRという考えを取り入れてみて
ADRという考えを取り入れてみて
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
C# Game Server
C# Game ServerC# Game Server
C# Game Server
 
PostgreSQLアンチパターン
PostgreSQLアンチパターンPostgreSQLアンチパターン
PostgreSQLアンチパターン
 
やはりお前らのMVCは間違っている
やはりお前らのMVCは間違っているやはりお前らのMVCは間違っている
やはりお前らのMVCは間違っている
 
正規表現リテラルは本当に必要なのか?
正規表現リテラルは本当に必要なのか?正規表現リテラルは本当に必要なのか?
正規表現リテラルは本当に必要なのか?
 
Where狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキーWhere狙いのキー、order by狙いのキー
Where狙いのキー、order by狙いのキー
 

Similar a Why Java Sucks and C# Rocks (Final)

A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
Garth Gilmour
 

Similar a Why Java Sucks and C# Rocks (Final) (20)

sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
JavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java codeJavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java code
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Clean up your code with C#6
Clean up your code with C#6Clean up your code with C#6
Clean up your code with C#6
 
Oop java
Oop javaOop java
Oop java
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Amusing C#
Amusing C#Amusing C#
Amusing C#
 

Más de jeffz

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错
jeffz
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践
jeffz
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望
jeffz
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)
jeffz
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
jeffz
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developers
jeffz
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
jeffz
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
jeffz
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
jeffz
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现
jeffz
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程
jeffz
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得
jeffz
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理
jeffz
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架
jeffz
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构
jeffz
 
企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性
jeffz
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
jeffz
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 

Más de jeffz (20)

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)
 
深入浅出Jscex
深入浅出Jscex深入浅出Jscex
深入浅出Jscex
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developers
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构
 
企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 

Why Java Sucks and C# Rocks (Final)

  • 1. Why Java Sucks & C# Rocks ZhaoJie @ SNDA April, 2010
  • 2. About me • Name: Jeffrey Zhao • Blog: http://blog.zhaojie.me/ • Twitter: @jeffz_cn • Email: jeffz@live.com
  • 3. Experiences • Pascal,VB 5 & 6, Delphi before 2002 • Java programmer from 2002 to 2004 • C# programmer since 2004
  • 4. I’m going to talk about ...
  • 5. • Languages features • Programming paradigms • Usage patterns • Why we should throw Java language away
  • 6. I’m NOT going to make you ...
  • 7. • 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
  • 8. Timeline • 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
  • 9. So Java programmers, hold your breath ...
  • 10. Let’s start from the very beginning ...
  • 11. Is Java a pure object- oriented language?
  • 12. No. Primitive types are not objects.
  • 13. In Java you can NOT ... ArrayList  list  =  new  ArrayList(); list.add(5);  //  cannot  compile int  i  =  (int)list.get(0);  //  cannot  compile int  hash  =  3.hashCode();  //  cannot  compile
  • 14. 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();
  • 15. 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.
  • 16. So you can always ... ArrayList  list  =  new  ArrayList(); list.Add(5); int  i  =  (int)list[0]; int  hash  =  3.GetHashCode();
  • 18. Finally you can ... ArrayList  list  =  new  ArrayList(); list.add(5);  //  auto  boxing //  auto  unboxing int  i  =  (Integer)list.get(0); //  you  still  can’t  do  this! int  hash  =  3.hashCode();
  • 19. 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
  • 20. But most of these features were already provided by C# 1.0 ...
  • 21. ... so who is the copy cat?
  • 22. OK, let’s forget it and look deep inside ...
  • 23. Annotations in Java are interfaces. Attributes in C# are classes.
  • 25. Annotation’s shortages • Strange convention • Anemic object • Hard to unit test
  • 26. Well, Java 5.0 also brings Generics, but ...
  • 27. Type erasure: type information will be lost after compiling!
  • 28. 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);
  • 29. 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        } }
  • 30. And “use-site variance” is strange and stupid.
  • 31. Well, maybe I’m biased. I can give you a separate talk about it.
  • 33. The same time Java released 5.0 ...
  • 34. 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
  • 36. And “yield” is only about iterator?
  • 37. Let’s see some samples.
  • 38. 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
  • 39. Two years after C# 2.0, Java 6 released with ...
  • 43. Give me a break and leave me alone ...
  • 44. OK, I admit it ...
  • 45. 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
  • 46. But we’re talking about language, so ...
  • 47. Let’s move on to C# 3.0, which brings us ...
  • 50. Yes! The great LINQ!
  • 51. 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
  • 52. Now tell me, which one do you prefer?
  • 53. BBCode to HTML //  Java Util.stripWhites(        Util.stripXss(                Util.bbToHtml(bbCode))) //  C# bbCode.BBToHtml().StripXss().StripWhites()
  • 54. Sorting an array //  C# users.Sort((u1,  u2)  =>  u1.Age  -­‐  u2.Age); //  Java Arrays.sort(        users,        new  Comparator<User>()  {                public  int  compare(User  u1,  User  u2)  {                        return  u1.Age  -­‐  u2.Age;                }        });
  • 55. 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        }), };
  • 56. 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);
  • 57. Is C# just full of Syntactic Sugar?
  • 59. It really changed my mind • Real-world Functional Programming • Write declarative code (anti-for) • Make code / API more and more elegant
  • 60. Please write a program to index a list of keywords (like books).
  • 61. Explanation • Input: List<String> • Output: Map<Character, List<String>> • The key of map is ‘a’ to ‘z’ • Each list in the map are sorted
  • 62. Let’s see the Java code first ...
  • 63. 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); }
  • 64. 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
  • 65. Quite easy, ah? Guess how does C# code look like?
  • 66. List<string>  keywords  =  ...; var  result  =  keywords        .GroupBy(k  =>  k[0])        .ToDictionary(                g  =>  g.Key,                g  =>  g.OrderBy(k  =>  k).ToList());
  • 67. 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
  • 69. What about the Java community?
  • 70. Well, the Functional Java project is out! But ...
  • 71. ... do you really want to write code like this?
  • 72. 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();            }        });
  • 73. It’s really a pain without lambda expressions.
  • 74. Fortunately, Java 7 will provide a sort of lambda syntax.
  • 75. keywords        .groupBy({  String  k  =>  k.charAt(0)  })        .toMap(                {  Grouping<Character,  String>  g  =>  g.getKey()  },                {  Grouping<Character,  String>  g  =>                          g.orderBy({  String  c  =>  c  }).toList()  });
  • 76. Much better, but still noisy because of lacking ...
  • 78. 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)
  • 79. Fixed-point combinator static  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));
  • 80. Is it really useful in real world programming?
  • 81. Yes, of course. I can’t live without the functional features now.
  • 82. Let me prove it to you.
  • 84. Code as Expressions • Serializable code • Consistent coding style • Strong typing • Compile-time verification • Generate dynamic method easily
  • 85. Many projects use Expressions. Let me show you sth.
  • 86. 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
  • 87. Most of them are provided by C# now
  • 88. What’s new in C# 4 • Default parameters • Naming parameters • Language build-in dynamic support • Convariance / Contravariance
  • 90. 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));
  • 91. Ruby-like Markup Builder dynamic  b  =  new  XmlMarkupBuilder(); var  persons  =  new  []  {        new  Person("Tom",  10),        new  Person("Jerry",  8) }; <persons> XElement  xml  =      <person  age=”10”>Tom</person>    <person  age=”8”>Jerry</person>        b.persons( </persons>                from  p  in  persons                select  b.person(p.Name,  age:  p.Age));
  • 92. Convariance & Contravariance • Improving the generics type system • More powerful and safer than Java’s use-site variance • Really a brain fucker
  • 93. Summary • (maybe I should put a table here...)
  • 94. C# always make me happy when coding ...
  • 95. ... and it brings us lots of useful code patterns
  • 96. But Java keeps me away from the great JVM
  • 97. 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
  • 98. But what’s wrong with Java?
  • 99. Java is too noisy • The only way to work is not simple • Write more and do less • Little room for smart people.
  • 100. 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
  • 101. ... and becoming even more //  C# dynamic  o  =  ...; int  i  =  o.SomeMethod(true,  “hello”); //  Java Object  o  =  ...; Object[]  args  =  new  Object[]  {  true,  “hello”  }; InvokeDynamic.<int>SomeMethod(o,  args);
  • 102. If JVM is machine ... • Java byte code is the machine code • Java language is the ASM.
  • 103. Would you like to program with ASM?
  • 105. Let’s use C# instead!
  • 107. We can’t use C# since ... • JVM is powerful • Java libraries are great • Platform migration is a nightmare
  • 108. So choose another language!
  • 109. Languages on JVM • JRuby • Jython • Groovy • Clojure • Scala
  • 110. All these languages are • More powerful • Run on JVM • Interop with Java seamlessly • Mature enough • Successful in real world
  • 111. Scala makes me write Java program again.
  • 112. 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
  • 113. What do you think?
  • 114. Contact me via • Email: jeffz@live.com • Twitter: @jeffz_cn • Blog: http://blog.zhaojie.me/
  • 115. Show me your idea ...
  • 116. ... and prove it to me
  • 117. Future Talks • Why F# matters • Why Scala matters (TBD.) • Generics in Java, Scala, C# & F# • The beauty of Parallel Library • Real-world reactive programming
  • 118. Thanks