您好,欢迎光临 | 我的主页 | 个人资料 | 短消息 | 好友 | 书签 | 黑名单 |
http://www.javayou.com (添加到收藏夹,设为首页)
当你不能再拥有时,你唯一能做的,就是让自己不要忘记 (手机请访问 http://3g.dlog.cn/javayou)

Java 7 - Null-safe types 

2007年1月14日(Sunday) 10点22分 作者: Stephen Colebourne 天气: 心情: 一般

如果感觉看英文忒没劲,不妨看看文章的几处代码(特别是#):

Yesterday I published part of a proposal for enhancing null handling in Java 7. Reading the comments, this got a few people upset. Unfortunately, what I didn't make clear was that I was also documenting the other part - null-safe types for Java.

The null-safe types part of the proposal is the tougher one to write-up, and probably the tougher one to implement. I was going to try and finish the details before publishing, but lets get the discussion going anyway...

Null-safe types are similar to Option Types in Nice. The difficulty is taking the idea and blending it with Java in a way that works and doesn't break the style of Java.

So, what is the null-safe types proposal? Well, lets examine this method:

  public Person lookupPerson(String personId) { ... }

This is a fairly typical method that loks up a person from a person identifier. But what happens if we pass a null identifier into the method? And can we get a null response? The current solution to this is adding explicit documentation:

  /**
   * Find person by identifier.
   * @param personId  the person id, not null
   * @return the person, never null
   * @throws IllegalArgumentException if the person is not found
   */
  public Person lookupPerson(String personId) { ... }

Now we know how the method is to be used. But this is just documentation. There is no compile-time checking. If we don't read the documentation then we may get a NPE at runtime.

The null-safe types proposal adds a new modifier to types - hash # - that prevents that variable/parameter/return from being null.

  public #Person lookupPerson(#String personId) { ... }

Now that we are using these declarations, the compiler can check that the calling code does not pass a null String to the method.

  String badId = null;
  #Person person = lookupPerson(badId);   // compile error

  #String id = "1234";
  #Person person = lookupPerson(id);      // ok

The draft of the formal null-safe types proposal is available with more details. And there are a lot more details, and probably a lot I've missed. If you've got any suggested enhancements or fixes to the proposal, or want to help out, let me know. All feedback welcomed.

And remember that this proposal is intended to complement the null-ignore part of the proposal.

标签: Java 
姓名: 
邮箱:  {可选}
网址:  {可选} 此评论只有我和写日记的人查阅
校验码: ... <我看不清楚>
网记为您提供手机和互联网同步的个人主页,带给你不一样的体验