TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Handling Associations on Null Objects in Rails

21 pointsby rabidferretover 11 years ago

2 comments

thangalinover 11 years ago
<a href="http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare" rel="nofollow">http:&#x2F;&#x2F;www.infoq.com&#x2F;presentations&#x2F;Null-References-The-Billi...</a><p>I often see code such as:<p><pre><code> public Object getObject() { return this.object; } </code></pre> I favour lazy initialization combined with self-encapsulation:<p><pre><code> private Object getObject() { Object o = this.object; if( o == null ) { o = createObject(); this.object = o; } return o; } </code></pre> This is thread-safe and allows injecting new behaviour via polymorphism (overriding the &quot;create&quot; methods in a subclass), which adheres to the Open-Closed Principle. It also eliminates the possibility of accidentally dereferencing nulls.<p>It could even be implemented as a language feature:<p><pre><code> public class C { nullsafe String name; public void greeting() { System.out.printf( &quot;Hello, %s\n&quot;, getName() ); } } </code></pre> Where the &quot;nullsafe&quot; keyword automatically generates a private accessor and corresponding protected creation method.
评论 #7040964 未加载
sitkackover 11 years ago
The null object is a beautiful device. <a href="http://en.wikipedia.org/wiki/Initial_object" rel="nofollow">http:&#x2F;&#x2F;en.wikipedia.org&#x2F;wiki&#x2F;Initial_object</a>