天天看點

[J2SE 1.5]Joshua Bloch詠Tiger詩八首Joshua Bloch詠Tiger詩八首

Joshua Bloch詠Tiger詩八首

“Ease of Development”是J2SE 1.5的主要賣點。為此,這一版本加入了七種新的語言特性——Enhanced for Loop、Autoboxing/Auto-Unboxing、Varargs、Static Import、Enumeration、Metadata和Generics。使用這些特性,可以讓編寫出來的程式更簡練、更清晰、更不容易出錯,進而簡化開發的過程。

Joshua Bloch(《Effective Java》的作者,J2SE 1.5的主要開發人員之一)效仿William Blake(1757-1827,英國詩人)的《Tiger》一詩,為這些特性撰寫了這樣一組詩篇:

詠Tiger

Tiger, Tiger burning bright

Like a geek who works all night

What new-fangled bit or byte

Could ease the hacker's weary plight?

這一首是總說Tiger中的能使開發變得簡單的各種新語言特性。

詠Enhanced for Loop

While Iterators have their uses

They sometimes strangle us like nooses

With enhanced-for's deadly ray

Iterator's kept at bay

這一首單表Enhanced for Loop機制提供了一種更簡單的周遊數組、Collection和其它實作了java.lang.Iterable接口的對象的方法。

詠Autoboxing/Auto-Unboxing

When from the collections ints are drawn

Wrapper classes make us mourn

When Tiger comes, we'll shed no tears

We'll autobox them in the ears

這一首單表Autoboxing機制/Auto-Unboxing提供了一種更簡單的整合兩套不同的類型系統(基本類型和引用類型)的機制。

詠Varargs

O joyless nights, o joyless days

Our programs cluttered with arrays

With varargs here, we needn't whine;

We'll simply put the args inline

這一首單表Varargs機制提供了一種更簡單的傳遞個數可變的實參的方法。

詠Static Import

And from the constant interface

We shall inherit no disgrace

With static import at our side

Our joy will be unqualified

這一首單表Static Import機制提供了一種更簡單的通路靜态成員的機制。

詠Enumeration

The int-enum will soon be gone

Like a foe we've known too long.

With type safe-enum's mighty power

Our foe will bother us no more

這一首單表Enumeration機制提供了一種更簡單的定義“類型安全的枚舉類”的方法。

詠Metadata

As for noble metadata

I'll have to sing its praises later

Its uses are so numerous

To give their due, I'd miss the bus

這一首單表Metadata機制提供了一種更簡單的定義“機器可讀的說明資訊”的機制。

詠Generics

To the most despised collections' cast

We'll bid a fond farewell at last

With generics' burning spear

The need for cast will disappear

這一首是說用Generics機制,可以免去很多強制類型轉化的步驟的事情。Generics機制還有些其它用法,在這裡沒有提到。

各種特性的複雜程度

J2SE 1.5裡新增的七個語言特性的複雜程度很不一緻。大體說來,Enhanced for Loop、Autoboxing/Auto-Unboxing、Varargs和Static Import比較簡單,而Enumeration、Metadata和Generics就比較複雜。

沒有包含的一個特性

J2SE 1.5裡并沒有加入所有已經被發明的能簡化開發的語言特性——例如給參數指派預設值的功能,就沒有被包含。當然,如果隻是想要做到這個效果的話,可以考慮用重載來代替。

相關内容

  • 逐漸挖掘Enhanced for Loop
  • 逐漸挖掘Autoboxing/Auto-Unboxing
  • 逐漸挖掘Varargs
  • 逐漸挖掘Static Import

參考資料

  • Joshua Bloch的詩作,取自Qusay H. Mahmoud的《The All-New Java 2 Platform, Standard Edition (J2SE) 1.5 Platform: Programming with the New Language Features in J2SE 1.5》一文。
  • 關于“類型安全的枚舉類”的更多資訊,可以參考Joshua Bloch的《Effective Java》一書中的《Substitutes for C Constructs》一章。