tag:blogger.com,1999:blog-88665926696655851952024-03-14T05:30:45.201+02:00Red and Sensual JavaThoughts about software engineering (mostly)Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.comBlogger54125tag:blogger.com,1999:blog-8866592669665585195.post-29597305800679033402010-03-03T12:20:00.007+02:002010-03-03T13:22:21.620+02:00Sayeret Lambda<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjDnrPeaqVPoUXL2k3un-k1rdObyacVs0c35BShMTuq2Jgn51Y_7BSS1qVR4e6b0ZXoAa-F-WWV2iQTznA405YJarHJN8Z6sG3iZaPrVy6fFAwLXzph75F7_Fc7R3rlp076H-1SPsHHPaE/s1600-h/lambda3small.gif"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 151px; height: 150px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjDnrPeaqVPoUXL2k3un-k1rdObyacVs0c35BShMTuq2Jgn51Y_7BSS1qVR4e6b0ZXoAa-F-WWV2iQTznA405YJarHJN8Z6sG3iZaPrVy6fFAwLXzph75F7_Fc7R3rlp076H-1SPsHHPaE/s200/lambda3small.gif" border="0" alt="" id="BLOGGER_PHOTO_ID_5444364520198869746" /></a><div style="text-align: left;">After delivering the keynote at <a href="http://www.alphacsp.com/web/guest/javaedge-2009/about">JavaEdge2009</a>, <a href="http://www.tedneward.com/">Ted Neward</a> asserted that <a href="http://blogs.tedneward.com/2009/11/29/Thoughts+From+The+JavaEdge+2009.aspx">Israel is ready</a> for the "polyglot" era. Ronen, Ophir and I decided to verify this assertion, so we are happy to announce the creation of "<a href="https://sites.google.com/site/sayeretlambda/">Sayeret Lambda</a>", the Israeli "<a href="http://lambdalounge.org/">Lambda Lounge</a>"! The group contains researchers, consultants, students, and industry professionals, interested in Scala, Clojure, Erlang, Lisp, Prolog, Smalltalk, Ruby, Fan, Groovy and so on...</div><div><br /></div><div>Our first meeting is going to take place on March 10th, and is dedicated to Lisp and Clojure. In April we are going to host Gilad Bracha's talk about Newspeak. Both talks will be in Hebrew. <div><br /></div><div>Programming language geeks in Israel are <a href="http://groups.google.com/group/sayeret-lambda">welcome to join</a> us! </div></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com7tag:blogger.com,1999:blog-8866592669665585195.post-41447041297902972952009-05-19T19:59:00.027+03:002009-05-22T01:06:53.826+03:00Lessons we learn, lessons we teach<div>Lately I've been a little involved in both (learning and teaching that is), and wanted to share some thoughts on the subject.<div><br /></div><div>Do you like science fiction? I used to like it (when I was younger, so much younger than today). Asimov, Bradbury and such. It's especially fun when the story mixes past, future and present; reality and imagination. What fascinates me most in these stories, is how the author is making deep and painful observations about reality through moving the characters into a completely unrealistic setting - future comes handy, because it is hardest to imagine . It's just amazing how, by disguising things beyond recognition, the author breaks the thought conventions and emotional associations built in our brain, and doing that lets us understand the reality beyond what we were able to before. John Lennon <a href="http://www.youtube.com/watch?v=NzJ2NKp23WU">said</a> "nothing you can see that isn't shown", right, but you can<a href="http://www.youtube.com/watch?v=-b7qaSxuZUg"> imagine</a> what you don't see, and that's how you "know the unknown" a little bit better. </div><div><br /></div><div>There's this recurring theme in sci-fi stories "smart man builds machine, machine becomes smarter than man, machine rules man". Is it a real threat? If so, how can we prevent it? Should we stop building smart machines? Is high-tech going to destroy mankind? I don't think so. For one, if I did think so, I would quit and become an organic farmer, and I haven't done so... so far. But the question does bother me. And the answer is, I think, that if we want to continue building smarter machines, we absolutely need to keep building smarter people, or we'll end up like in those sci-fi stories. </div><div><br /></div><div>The main purpose of education is often perceived as passing on what we already know to the next generation, so they don't waste time on rediscovering it. But it's only secondary. The real goal should be passing on the ability to explore the unknown and solve what previous generation haven't solved. Because if students can think at least as well as their teachers, rediscovering something will be just a small detour for them on the road to Knowledge. But without a developed mind they have no legs to walk that road. And it's a steep road up, so when they stop, they (inadvertently perhaps, but) inevitably slip to the bottom. So how do we nourish the ability to think?</div><div><br /></div><div><b>It's not what we know, it is how we learned it.</b></div><div>When asking ourselves how to teach, we should first turn to introspection - how did we learn? If the way we've been taught made us discover all those great things that we are so anxious to pass on, why don't we teach what we've been taught? Sure, we will throw in a bit or two of what we've discovered, but basically why don't we build from the same grounds? They say it about parenting - if you like the way you were raised, you'll likely be a good parent, because you'll repeat what you saw. However, if you look around in what's going on in education system, in almost every level, you see the curriculum constantly changing, "updating", "modernizing" etc. "It was true then, it's wrong now. We don't need it." Why? Because we have the technology? Big mistake. Ancient Greeks, Hebrews, Egyptians, not having the technology, weren't even tiny bit stupider than us. Without the wheel, there would be no Internet, speaking of which, who invented <a href="http://sensualjava.blogspot.com/2008/05/net-goddess-of-wisdom.html">the Net</a>? But no, we don't need old men, old books and such, religion, history... we have TV commercials to teach us how to live, we have the technology. And once technology costs money, suppliers of technology don't want us thinking independently, because, Google forbid, we may decide we don't need it! In computer science, this is the nightmare sci-fi writers were warning us against, and we should at least try to prevent it from happening. </div><div><br /></div><div>We can't go forward without understanding the past. Students can't possibly understand Java and Object Orientation before they understand procedural programming, functions, math, logic. Then, when (and if) we show them objects, let's show how they <a href="http://gagne.homedns.org/~tgagne/contrib/EarlyHistoryST.html">came about</a>, and not a <a href="http://java.sun.com/">popular imitation</a>. If we have a <a href="http://mitpress.mit.edu/sicp/">great book and curriculum</a> that generations of computer scientists and engineers grew on, why are we<a href="http://danweinreb.org/blog/why-did-mit-switch-from-scheme-to-python"> throwing it away</a>? Let Java, Python and their patrons wait. They will lay their heavy paws on the students in just very few years anyway and will turn them in Dilberts, Wallies, and Alices, converting large XML files to long stack traces. Let's give freedom of thought and curiousity a chance to grow just a little bit in students' minds, so at least some of it can survive through corporate development.</div><div><br /></div><div><b>It's not what a technology does, it is how and why it works</b></div><div>We're all the time obsessively looking for solutions to our problems. We barely stop and analyze them, until the solution itself becomes our biggest problem. I watched <a href="http://www.infoq.com/presentations/Making-Roles-Explicit-Udi-Dahan">this QCon presentation</a> a while back, and it was a deja vu in many senses. I encountered problems like that, and I even solved them in somewhat similar way. I may be wrong, but what I get from the presentation on the technical level, is that sometimes Object Orientation as we know it (C#, Java), with all the patterns and practices and such, does not solve our problem. The problem in the presentation reminds me of the <a href="http://www.daimi.au.dk/~madst/tool/papers/expression.txt">expression problem</a> - data and operation-set need to evolve, how do we express the relationships? The proposed solution (although I may be getting it wrong) is to have interface per operation; then the implementation of the interface, using reified generic type parameter, stores the type of object it applies to; then at start-up something wires together data types and implementations; then it all becomes a big happy family of <a href="http://en.wikipedia.org/wiki/Multiple_dispatch">multi-methods</a>, operation implementation chosen via dynamic dispatch on the data type. And an old saying goes "when the problem is hard enough, you will find yourself re-inventing Lisp to solve it". It's interesting how Udi describes arriving at this design - a team of people were struggling with the problem for years, until an "old programmer" came to the project retrospective meeting and said "make your roles explicit". Udi took the guy aside and made him explain. Then Udi (and his team, I suppose) implemented it, and now reported the success at QCon. Who was that "old geezer"? What was he? Udi didn't say, in the presentation he is portrayed as a little green troll. Anyway, why do I care who that mysterious character was? Because I didn't come to computer science for some wise Merlin to tell me where the Holy Grail is, I want to <i>be</i> that Merlin! Unfortunately, I am probably not smart enough, but someone else is. That's why I think we need more wanna-be Merlins; wanna-be Kings we already have plenty. </div><div><br /></div><div>Since I became interested in functional programming, for example, my Java coding style changed significantly. I thought I knew how to use Generics, only after a taste of OCaml and Benjamin Pierce's writings I realized how little I knew about types. I thought I knew how to write object-oriented programs, only after playing with Smalltalk I realized what object oriented really meant. I may not be able to use Haskell for the day job, but the concepts of immutability, closures, function composition, laziness, are helpful no matter what language I use. Let's look at one example - the (in)famous problem of object-oriented design: does square extend rectangle, or in other words does circle extend ellipse? In both cases the former has 2 distinct properties (edge sizes or focal points) and the latter has only 1. Bob Martin discusses the problem in his article "Design Principles and Design Patterns". Does he offer a solution? No - "design by contract" and Eiffel and some hand-waving. On the other hand, understanding types helps, because then I can "design for subsumption": I ask myself - if Ellipse is a type that describes all ellipses in the world, do they all have 2 distinct focal points? No. Then maybe I shouldn't have methods to get and set them. Maybe my API should try to follow the definition of ellipse more precisely. That surely helps to design good APIs. Furthermore, magically, once we turn the shapes to immutable, the problem almost goes away. If Rectangle has a method Rectangle transform(x,y) that produces a <b>new</b> Rectangle with given sizes, then Square can inherit it with no problem, it would simply produce a Rectangle, not a Square when x != y. Same trick would work for Ellipse. After all, shapes are math definitions, why should they be mutable?! See, a bit of "functional" thinking solved the problem. And the moral - understanding the classic foundation of computer science is necessary for programmers. </div><div><br /></div><div><b>Reality distracts clarity of thought.</b></div><div>If there is one more thing that we can learn from these sci-fi stories, it's that detaching things from reality may actually increase our ability to grasp them. However education in recent years is insisting on "examples", or worse - "realistic examples", or even worse "examples of being used in the industry". I am not saying the above is worthless, or unnecessary, but it should not be overrated. At some point education ministry decided to teach elementary school math with actual objects - sticks and such, rather than teaching kids the abstract idea of numbers, and it was a disaster. Math, in general, cannot be taught by following "real world" intuition. Nor logic. Physics has evolved way beyond relatively "intuitive" mechanics. So why are so many educational institutions chasing "real life" technologies, at the expense of classics, and ignoring the "too innovative to be popular"? I know why, of course, - money, pressure from the industry, pressure from students who want real jobs after they graduate. But resisting that pressure is absolutely necessary, for the sake of future generations, to save our civilization! Luckily we still have some universities in Northern Europe :-) </div><div><br /></div><div>I noticed an interesting phenomena with students - when they are "fresh" and don't carry a baggage of "field experience" (C, Java, curly braces etc.), it is easier for them to take a "different" point of view, to understand more abstract ideas. Generics is one example. Teaching them to experienced Java programmers is extremely hard. But with undergraduates it is, surprisingly, much easier. So why don't we teach Haskell for types, Smalltalk for objects, and maybe C for low-level stuff? Then when they meet Java, or any language they will likely encounter in the industry, it will be a piece of cake to learn. Furthermore, some of them will be able to design the next Java!</div></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com6tag:blogger.com,1999:blog-8866592669665585195.post-15842828847266850862009-05-19T16:51:00.014+03:002009-05-19T19:56:53.771+03:00Java nested classes - tips and tricks<div>I had to prepare this anyway, so I thought I might as well post. </div><div><br /></div><div>First of all to get the <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html">terminology</a> straight: normal classes and interfaces are top-level. But class or interface can also be <span class="Apple-style-span" style="font-weight: bold;">nested</span>, if it is defined inside another class or interface. Nested classes originate in <a href="http://www.daimi.au.dk/~beta/">Beta</a> programming language, and are available in Java since version 1.1. Non-static nested classes are called <span class="Apple-style-span" style="font-weight: bold;">inner</span>. Inner classes can be <span class="Apple-style-span" style="font-weight: bold;">members </span>(declared immediately inside outer class definitions), like this:</div><div></div><blockquote><div>class Outer { class Inner { ... } }</div><div></div></blockquote><div>Inner classes can also be declared within methods and other blocks, then they are called <span class="Apple-style-span" style="font-weight: bold;">local</span>, like:</div><div></div><blockquote><div>class Outer { void foo() { class Local { ... } ... }</div><div></div></blockquote><div>A more popular breed of local inner classes are <span class="Apple-style-span" style="font-weight: bold;">anonymous </span>classes: </div><div></div><blockquote><div>class Outer { void foo() { ... new Bar(...) { ... } ... }</div><div></div></blockquote><div>For visual impression - check out <a href="http://blogs.sun.com/darcy/entry/nested_inner_member_and_top">this diagram</a>.</div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Tip - construction:</span> Creating new instance of nested or inner class within the outer class is simple. From outside it's a bit trickier, suppose we have a class like this:</div><div></div><blockquote><div>class Outer {</div><div> static class Nested { ... } </div><div> class Inner { ... } </div><div>} </div><div></div></blockquote><div>We can reference and instantiate the classes like this:</div><div></div><blockquote><div>Outer.Nested nested = new Outer.Nested(...);</div><div>Outer out = ... </div><div>out.Inner in = out.new Inner(...); //translated by javac to new Inner(out, ...)</div><div></div></blockquote><div>The magic behind inner class constructor is that compiler implicitly adds <span class="Apple-style-span" style=" ;font-family:'courier new';">Outer </span>parameter to all <span class="Apple-style-span" style=" ;font-family:'courier new';">Inner </span>constructors, and passes the enclosing instance when constructor is invoked. From then on, inner class instance (for its entire lifetime) holds a <span class="Apple-style-span" style="font-weight: bold; ">strong reference </span>to the enclosing instance.<br /></div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Tip - instanceOf: </span>If we have two distinct instances <span class="Apple-style-span" style="font-family:'courier new';">Outer out1, out2</span> then <span class="Apple-style-span" style="font-family:'courier new';">out1.Inner</span> and <span class="Apple-style-span" style="font-family:'courier new';">out2.Inner</span> denote the same class, but <span class="Apple-style-span" style="font-family:'courier new';">Inner</span> instances will refer to a different enclosing instances. This is different from <a href="http://www.scala-lang.org/node/115">Scala</a> and <a href="http://blog.3plus4.org/category/newspeak/">Newspeak</a>, where inner class is distinct for every enclosing instance.</div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Tip - access enclosing instance: </span>To access the instance of outer class from within a contained inner class use <span class="Apple-style-span" style="font-family:'courier new';">Outer.this</span>. Nested/inner class methods/fields <span class="Apple-style-span" style="font-weight: bold; ">hide </span>outer class ones, to access outer class elements prefix them with <span class="Apple-style-span" style="font-family:'courier new';">Outer</span> class name, e.g. <span class="Apple-style-span" style="font-family:'courier new';">Outer.staticMethod(...) </span>or <span class="Apple-style-span" style="font-family:'courier new';">Outer.this.anyMethod(...)</span>. </div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Tip - nesting and inheritance: </span>Generally, method lookup rules in Java nested classes follow "<a href="http://blogs.sun.com/jrose/entry/scope_ambiguities_between_outer_and">comb semantics</a>" - first search inheritance hierarchy, then enclosing lexical scopes. This behavior can <a href="http://dyla2007.unibe.ch/?download=dyla07-Gilad.pdf">introduce some wierd puzzlers</a>, like <a href="http://www.javapuzzlers.com/java-puzzlers-sampler.pdf">#9 here</a>. In Newspeak the enclosing scope is considered before inheritance, which makes it easier to follow from programmer's perspective.</div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Tip - generics: </span>Generics type parameters of enclosing class (or method) can be used within inner classes.</div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Tip - interfaces: </span>Interfaces may have nested classes (necessarily and implicitly static), it may be particurlaly useful for declaring nested enums.</div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Tip - statics: </span>Inner class <a href="http://blog.zvikico.com/2008/07/static-members-in-inner-classes-the-answer.html">cannot have static declarations</a> in it, except compile-time constants. To overcome this, static declarations canbe moved to the top-level class.</div><div> </div><div><span class="Apple-style-span" style="font-weight: bold;">Trick - loading: </span>Nested class is treated just as any other class by the JVM, e.g. it is not loaded/initialized until used. This fact is used to implement <a href="http://crazybob.org/2007/01/lazy-loading-singletons.html">thread-safe lazy singletons</a> using the Holder pattern.</div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Tip - final: </span>Anonymous inner classes and local classes can access variables in the surrounding scope only if the variables are <span class="Apple-style-span" style="font-weight: bold;">final:</span></div><div></div><blockquote><div>void invokeAnon(final int number) {</div><div> final String word = “hello”;</div><div> someObject.pass(new Runnable() { </div><div> public void run() { </div><div> System.out.println(word.substring(number));</div><div> }</div><div> });</div><div>} </div><div></div></blockquote><div><span class="Apple-style-span" style="font-weight: bold;">Trick - double braces: <span class="Apple-style-span" style="font-weight: normal; "><a href="http://www.c2.com/cgi/wiki?DoubleBraceInitialization">Double brace initialization</a> is a trick of putting initialization block inside anonymous inner class declaration, like:</span></span></div><div></div><blockquote><div> final Map<string,integer> numbers = new HashMap<string,integer>(){{</string,integer></string,integer></div><div> put("one", 1);</div><div> put("two", 2);</div><div> put("three", 3);</div><div> //...</div><div> }};</div><div></div></blockquote><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Trick - tokens: </span>A cool Generics trick that uses local class to capture type parameters is <a href="http://gafter.blogspot.com/2006/12/super-type-tokens.html">super-type-token</a>, a.k.a. Gafter Gadget. </div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Tip - reflection: </span>Starting from Java 5 a <a href="http://blogs.sun.com/darcy/entry/nested_inner_member_and_top">bunch of methods</a> have been added to reflection with regards to nested classes. For example, <a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getEnclosingClass()"><span class="Apple-style-span" style="font-family:'courier new';">Class#getEnclosingClass()</span></a> method will let you find out the enclosing class for an inner class, for example:</div><div></div><blockquote><div>class Enigma { </div><div> final static Class MY_CLASS = new Object(){}.getClass().getEnclosingClass(); </div><div>} </div></blockquote><div></div><div><span class="Apple-style-span" style="font-weight: bold; ">Prolog: </span>Last, but not least <a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html">JLS</a> is the ultimate resource for finding out more.<br /></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com3tag:blogger.com,1999:blog-8866592669665585195.post-90384079989749622142009-05-08T12:13:00.011+03:002009-05-10T14:37:32.258+03:00Community Choice Award<a href="http://sourceforge.net/community/cca09/nominate/?project_name=Newspeak%20Programming%20Language&project_url=http://sourceforge.net/projects/newspeakpl/"><img src="http://sourceforge.net/images/cca/cca_nominate.png" border="0" /></a><br />I nominated <a href="http://newspeaklanguage.org/">Newspeak Programming Language</a> for "Most Likely to Change the Way You Do Everything" <a href="http://sourceforge.net/community/cca09/">Community Choice Award</a>. I don't know how exactly they choose winners, apparently:<div><blockquote>The first phase will be to nominate finalists for each of the Categories. Nominations will be accepted at ... between May 6, 2009 at 10:00 a.m. PDT and May 29, 2009 at 4:00 PDT. Among the nominees for each of the Categories, the finalists for the Awards will be chosen. Voting for the final winners will commence at ... on June 22, 2009 at 10:00 a.m. PDT and end on July 20, 2009 at 4:00 pm PDT. ... The odds of winning in any category are dependent upon the total number of eligible nominations received.</blockquote></div><div>Anyway, clicking the orange bot on <a href="http://sourceforge.net/projects/newspeakpl/">Newspeak sourceforge page</a> might help the odds - I ask all my readers to contribute a click for a good cause!<br /></div><div><br /></div>Thank you.<div><br /><div><span class="Apple-style-span" style="font-weight: bold;">UPDATE: </span>Why does Newspeak deserve it? Newspeak is a class-based dynamically-typed object-orientated language that revives the ideals of Smalltalk and Self. It incorporates many great ideas, but one of the major innovations is its modularity support. </div><div><br /></div><div>No other language or framework today provides comprehensive solution for creating modular software. Some languages support hierarchical code organization, there are tools that build components, tools that manage dependencies between components, yet another set of tools and formats deal with module deployment, there are platforms and tools that facilitate versioning and patching, hot and cold updates. <span class="Apple-style-span" style="font-weight: bold;">Newspeak has it all</span> - the language, development environment, and platform together provide easy and intuitive end-to-end modularity support. </div><div><br /></div><div>Newspeak supports both mixin-based inheritance and class nesting - modules are top level classes, while all other classes are nested in them. Dependencies between modules are specified using constructors, the absence of global (static) scope enforces complete isolation of modules and prevents creation of incidental or implicit dependencies. Since all objects communicate via virtual method invocations, there is no hard wired dependency on a particular module implementation. Everything is virtual, including the parent-child relationship between classes, which allows for great flexibility and extensibility. The platform supports construction, serialization and loading of module instances, and therefore effectively supports building and deploying applications without the need for any external tools (even though some of this is still under development). Dynamic platform underneath Newspeak has rich meta-programming support and allows querying module definitions, extending modules and supports hot (incremental) updates. Multiple versions of the same module can coexist without interference. Security is maintained by capability-based model where access to resources is guarded by capability objects (also under development). Modules may access their execution environment (the virtual machine, or platform) and through it interact with external resources. Newspeak is also network-aware, and is designed to support distributed component management using service objects. </div><div><br /></div><div>Newspeak is open-source, it was not widely, but successfully, used in an industrial environment, until financial situation deteriorated and corporations turned their back on funding innovation. There are several publications, and more on the way, conference presentations are received with great excitement. Newspeak is modern, it combines "best-of-breed" ideas of computer science and decades of Smalltalk and Java practical experience. It is easy to learn and very pleasant to code in (and not just for Smalltalkers and programming languages afficonados, but also for averagely skilled Java programmers like yours truly). Newspeak philosophy is inspiring. The people who work on it are extremely smart, but also nice and cool guys... Need I say more?</div><div><br /></div></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com0tag:blogger.com,1999:blog-8866592669665585195.post-84739919683119478922009-03-31T15:06:00.013+03:002009-04-01T00:28:12.073+03:00Oh Null, Null<blockquote></blockquote><span class="Apple-style-span" style="font-weight: bold;"><blockquote></blockquote>Introduction</span><div>Some say it’s one of <a href="http://qconlondon.com/london-2009/presentation/Null+References%3A+The+Billion+Dollar+Mistake">the worst inventions in history of programming languages</a>, some say it is number one cause of errors in Java programs. Anyway you look at it - <a href="http://en.wikipedia.org/wiki/Pointer#The_null_pointer">null pointer</a> (in all its incarnations) is a sensitive subject. I wonder why there is no song about it, there are several funny <a href="http://www.daniweb.com/forums/thread43073.html">re-works of Beatles songs</a> with geeky lyrics, like Unix Man (Nowhere Man, “he’s a real Unix man sitting in his Unix LAN, making all his UNIX .plans for nobody…”), Write In C (Let It Be), Yesterday (“yesterday, all those backups seemed a waste of pay…”), Something ("Something in the way it fails, defies the algorithm logic...") and a not so funny Eleanor Rigby. I’d like to write a new song, “Null” using the “Girl” tune. Only my inspiration ended after a single verse:<br /></div><div><div></div><blockquote><div>If there’s anybody going to listen to my story, </div><div>All about the Null who brought the fall.</div><div>It’s a value that you want so much, it makes you sorry,</div><div>Still you don’t regret a single call. </div><div>Oh Null, Null…</div><div></div></blockquote><div><p>I also have a middle verse inspired by Smalltalk, where the equivalent of <b>null</b> is <b>nil</b>, a keyword that returns an object of class UndefinedObject. It has no methods, except <i>isNil </i>and <i>notNil</i> that return true and false respectively, so <b>nil</b> responds to any other method invocation with “<b>DoesNotUnderstand:</b> <method name><i><method></method></i>”, and in my experience, at least, pretty much equivalent to NPE in Java. Interestingly enough, though, <a href="http://wiki.squeak.org/squeak/5962">Objective-C turned </a><b><a href="http://wiki.squeak.org/squeak/5962">nil</a></b><a href="http://wiki.squeak.org/squeak/5962"> into a “black hole”</a> that returns self upon any invocation.</p></div><div><div></div><div></div><blockquote><div>Nil’s a kind of null, she is not answering your calls,</div><div>you feel a fool (fool fool).</div><div>When you think the code looks good, she answers “it’s not understood”, </div><div>she’s cruel (cruel cruel).</div><div>Ah null, null…</div></blockquote><div></div><div><blockquote></blockquote><blockquote></blockquote><span class="Apple-style-span" style="font-weight: bold;">From Beatles to Elvis</span></div><div>One situation where nulls are very annoying, is when we have a “chain” of method invocations, such as account.getOwner().getAddress().getStreet(). If any of the methods return null, we get NullPointerException from the next method invocation. I previously <a href="http://sensualjava.blogspot.com/2007/11/null-safe-access-to-properties.html">suggested a solution</a> to the problem, but now (due to popular demand) there is a <a href="http://jroller.com/scolebourne/entry/java_7_null_ignore_invocation">proposal</a> for Java 7 language enhancement, called <a href="http://docs.google.com/Doc?docid=ddb3zt39_78frdf87dc&hl=en">The Elvis Operators</a>. One of the stronger arguments for this solution is that it is available in other languages like C# and Groovy, even if <a href="http://adventuresinsoftware.com/blog/?p=293">not everybody is entirely happy with it</a>. Perhaps this is subjective, but after all, programming language design is about human perception and feelings, as much as about computer capabilities. So, I admit: <span class="Apple-style-span" style="font-style: italic;">I feel uneasy with this new way of method invocation.</span><br /></div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">The Demeter </span><strike><span class="Apple-style-span" style="font-weight: bold;">Law</span></strike><span class="Apple-style-span" style="font-weight: bold;"> Suggestion</span></div><div>One of the more controversial guidelines of object-oriented programming, Demeter Law is related to “Tell Don’t Ask” and usually summarized as “only talk to your close friends”. It prohibits series of method invocations like the one described above; in fact, more than one dot in series of method invocations is disallowed (unless the chain originates in a this object’s member (?)). There’s a good description of the “The Law” in <a href="http://www.pragprog.com/articles/tell-dont-ask">Pragmatic Programmers article</a>; it was originally discovered and named by <a href="http://www.ccs.neu.edu/groups/faculty/lieber.html">Karl Lieberherr</a>, who created the <a href="http://www.ccs.neu.edu/research/demeter/">Demeter Project</a> and wrote the <a href="http://www.ccs.neu.edu/research/demeter/biblio/dem-book.html">book</a> named “Adaptive Object-Oriented Software - The Demeter Method”. Martin Fowler <a href="http://pages.citebite.com/n1f0t3t8b0kvt">demoted the Law to Suggestion</a>, and in general, Demeter managed to generate a lot of controversy and debates inside both Java and Ruby communities, the debates ranging from <a href="http://www.javalobby.org/java/forums/t104659.html">intellectual (almost academic) polemics</a>, to flamed <a href="http://pivotallabs.com/users/alex/blog/articles/273-lovely-demeter-meter-maid">battles between consulting firms over preferences in programming styles, music and hairdo</a>. Yes, really. Anyway, if you believe in Demeter, our use-case for “null-safe” method invocations is flawed to begin with. But do we believe in Demeter? It took me a while to form an opinion.<br /></div><div><blockquote></blockquote>1) I do believe in “Tell, Don’t Ask” and the internal iterator (as presented in Pragmatic Programmers article) to be preferable over external iterator (<a href="http://gafter.blogspot.com/2007/07/internal-versus-external-iterators.html">when applicable</a>, of course). </div><div><blockquote><span class="Apple-style-span" style="font-style: italic;"><span class="Apple-style-span" style="font-size:small;">“Tell Don’t Ask” begs for closures in the language. For those who say “closures are not object-oriented”, Smalltalk not only supports closures, and with minimal syntactic overhead, but basic things like <span class="Apple-style-span" style="font-weight: bold;">if </span>and <span class="Apple-style-span" style="font-weight: bold;">while </span>are designed around closures and would not be possible otherwise. </span></span></blockquote></div><div>But "Tell Don't Ask" goes much deeper and wider. For example let's look through Demeter's eyes on service locator vs. injection: locator is wrong, because you go to a factory to get a factory to get a service. Injection is right, because you pass yourself to injector, which sets your the dependencies directly. How about ORM? How much grief is in loading strategies, because we do getContainer().getItem().getProperty(), vs. calling database.execute(query)? Food for thought.<br /><br /></div><div>2) Now the paper boy example – this one I do not buy. First of all, we don’t pay for things in cash these days – we give the seller our credit card. Not very secure? Maybe. But much more handy. <br /></div><div><blockquote><span class="Apple-style-span" style="font-size:small;"><span class="Apple-style-span" style="font-style: italic;">People should generally stop obsessing around security in software, I think. At one point a highly ranked architect in the firm I worked for said “we can’t deploy any software in the browser because it is not secure”. Yes, it is not secure, it’s a problem and people are working on it. And yet, even as it is, is it secure for the jeweler store to put some jewels in the front window? Why not keep them all in the backroom safe? Because they won’t have buyers, that’s why. What good is all the security, if you go out of business? </span></span></blockquote><p class="MsoListParagraph">Back to paper boy, the example also does not hold if you are a large organization – the receiver of the service is not the one who authorizes the payment, and not the one who handles the payment. The supplier may wish for “direct communication” as much as he wants, but the rules of corporate procurement are quite different. Then again, it may be silly to attack the example…? Well, the thing is that I hope to show later that you can’t follow Demeter and scale, just like the example doesn’t.</p><p class="MsoListParagraph">3) Now there’s “hard to mock” argument. Ok, at risk of starting a flame war here, I mean: I love unit-testing just like the next guy, and I know how useful it is, but let’s not get carried away here. </p><p class="MsoListParagraph"></p><blockquote><span class="Apple-style-span" style="font-style: italic;"><span class="Apple-style-span" style="font-size:small;">Unit-testing, just like static types/compilation, or static analysis, is a means to achieve code quality, not the goal in itself. If it helps you – great, if it gets in your way – ditch it. I think the “100% test coverage” is a fallacy. Dijkstra said “tests only prove presence of bugs, never their absence”, which is even truer for unit-tests. (I heard “we have unit-tests, we don’t need QA” argument once or twice. Yeah, right.) </span></span></blockquote><p></p><p class="MsoListParagraph">Anyway, “hard to test” may be a smell, but unless the suspicion can be substantiated – sorry, circumstantial evidence not accepted.</p></div><div>4) So even though I partially agree that “Demeter violation” is a symptom of a problem, the solution proposed by Demeter is, in my opinion, simply absurd. The grand huge fat mega-façade? Dots replaced with underscores? It cannot scale and it is sweeping design problems under the carpet. I mean, give me <a href="http://gbracha.blogspot.com/2009/03/subsuming-packages-and-other-stories.html">hierarchies of nested objects that support subsumption</a>, like <a href="http://blog.3plus4.org/2009/03/08/a-taste-of-nested-classes-part-4/">Newspeak modules</a> – now we are talking. But mega-façades? No thanks.</div><div><div>So there are good things that result from minding Demeter, but not following the law per se. </div><div>a) For example, “don’t return a java.util.List from your API when you don’t want clients adding elements to the list” – that’s basics of any sound API design – return the minimum interface that the client needs, Josh Bloch has been saying this repeatedly. </div><div>b) We should consider to proxy the returned object (perhaps with our own (inner) class), and then we’ll have control over what the returned object’s methods do.</div><div>c) Applied to DI – “do not depend on module A just to give you access to another module B, instead depend on B directly”, is also a reasonable rule of thumb. </div><div><br /></div><div>But let’s now go back to our beloved nulls.<br /></div><div><br /></div><div><span class="Apple-style-span" style="font-weight: bold;">Power to the method - let the declaration site decide</span><br /></div><div>Demeter or not, methods are meant to do things. I would argue that typical methods should not be assumed to be wrapping field access, or performing trivial computations. Yeah, I know we all do POJOs, which are really POCS, Plain Old C Structs in disguise. (And what makes them structs are frameworks that assume a dumb accessor and mutator, and freak out if they are not.) I believe that most methods should do something, so invoking them on a null target should yield an error, not some ambivalent null… So I am not too happy with changing the programming language to accommodate to behavior that should have been atypical.<br /></div><div><br /></div><div>Now if some methods are “dumb” and have reasonable defaults (like null for property accessor in null object, or 0 for size/length of a null collection/array, or null for a null string upper case transformation), then the method implementer should decide – not the caller. And again, it’s not problem-free, but worth exploring. Somewhat similar behavior has been proposed by Jacek <a href="http://codervirtue.blogspot.com/2009/03/null-safe-invocation-in-java-7.html">here</a>.<br /></div><div><br /></div><div>Suppose at the method declaration we add a default clause: either <span class="Apple-style-span" style="font-weight: bold;">default <value>,</span> or <span class="Apple-style-span" style="font-weight: bold;">default <expression></span>, or <span class="Apple-style-span" style="font-weight: bold;">default <code-block></span>, with the return type of value/expression/code-block similar to method return type, and parameters and exceptions (in 2 latter cases) similar to the method’s ones. BTW <span class="Apple-style-span" style="font-weight: bold;">default </span>is an existing Java keyword, used in <span class="Apple-style-span" style="font-weight: bold;">switch </span>statements. <br /></div><div><br /></div><div><div>Now examples:</div><div><span class="Apple-style-span" style=" ;font-family:'courier new';"></span></div><span><span><div><br /></div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">public int</span> size() { <span class="Apple-style-span" style="font-weight: bold;">return this</span>.size; } <span class="Apple-style-span" style="font-weight: bold;">default </span>0; </span></span></span></div><div><span><span><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">public boolean </span>isEmpty() { <span class="Apple-style-span" style="font-weight: bold;">return this.</span>size == 0; } <span class="Apple-style-span" style="font-weight: bold;">default true</span>; </span></span></span></div><div><span><span><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">public </span>Person getOwner() { <span class="Apple-style-span" style="font-weight: bold;">return this</span>.owner; } <span class="Apple-style-span" style="font-weight: bold;">default null</span>; </span></span></span></div><div><span><span><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">public </span>Iterator iterator() { <span class="Apple-style-span" style="font-weight: bold;">return </span>… } <span class="Apple-style-span" style="font-weight: bold;">default </span>Collections.emptyList().iterator(); </span></span></span></div><div><span><span><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">public </span>Something produce(Param1 p1, Param2 p2) <span class="Apple-style-span" style="font-weight: bold;">throws </span>E1 {</span></span></span></div><div><span><span><span class="Apple-style-span" style="font-family:'courier new';"> //normal method code here</span></span></span></div><div><span><span><span class="Apple-style-span" style="font-family:'courier new';">} <span class="Apple-style-span" style="font-weight: bold;">default </span>{</span></span></span></div><div><span><span><span class="Apple-style-span" style="font-family:'courier new';"> //default calculation, similar to static method, can use p1 and p2, throw sub-type of E1</span></span></span></div><div><span><span><span class="Apple-style-span" style="font-family:'courier new';"> //needs to return Something</span></span></span></div><div><span><span><span class="Apple-style-span" style="font-family:'courier new';">} </span></span></span><div><span class="Apple-style-span" style=" ;font-family:'courier new';"></span></div><div><br /></div><div><div>The location of the “default clause” can be after method body (and if we stick to coding convention of keeping default it on the same line as the closing curly brace, I think it is preferable), but it can sit also between end of method parameter list and the <span class="Apple-style-span" style="font-weight: bold;">throws </span>clause, or between the <span class="Apple-style-span" style="font-weight: bold;">throws </span>and the method body start. I think tail location is preferable, because it reminds of the <span class="Apple-style-span" style="font-weight: bold;">switch </span>statement. </div><div></div><blockquote><div><span class="Apple-style-span" style="font-style: italic;"><span class="Apple-style-span" style="font-size:small;">Another variation that increases similarity to switch may be adding a colon (<span class="Apple-style-span" style="font-weight: bold;">default :</span> ) and requiring return keyword, like <span class="Apple-style-span" style="font-weight: bold;">default : return null;</span> instead of <span class="Apple-style-span" style="font-weight: bold;">default null</span>. Also, the support for “defaults” can be added gradually, with only values in the first stage and more later if it proves to be successful. Also, alternative to default may be <span class="Apple-style-span" style="font-weight: bold;">case null : </span>… .</span></span></div><div></div></blockquote><div>The method would be compiled now additional synthetic static method, e.g. ___size(), with the same signature and throws clause, the synthetic method returning the “default” body provided by the user. <br /></div><div><br /></div><div>Unfortunately, though, call sites are affected by such method definition and compiled to something like:</div><div><br /></div><div><span class="Apple-style-span" style="font-family:'courier new';">SomeType object;</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">if </span>(object != <span class="Apple-style-span" style="font-weight: bold;">null</span>) {</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> object.m()</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">} <span class="Apple-style-span" style="font-weight: bold;">else </span>{</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> <span class="Apple-style-span" style="font-weight: bold;">try </span>{</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> SomeType.___m();</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> } <span class="Apple-style-span" style="font-weight: bold;">catch </span>(NoSuchMethodError e) {</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> <span class="Apple-style-span" style="font-weight: bold;">throw </span><span class="Apple-style-span" style="font-weight: bold;">new </span>NullPointerException();</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> }</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">} </span></div><div><br /></div><div>So the “default” would be calculated based on declaration type of the object, just like any static method invocation. Why catching NoSuchMethod? Well, what if SomeType class is recompiled alone, and the default clause, and with it the ___m() method, are gone? We want NPE to be thrown, not NSME. </div><div><br /></div><div>If, on the other hand, we add the default behavior without recompiling clients, they’ll be still throwing NPEs, I think we would not want all method invocations to become complex byte-code like the one described above… If I understand Jacek’s proposal correctly, unlike me, he suggests every method invocation to go through a static method. </div><div></div><blockquote><div><span class="Apple-style-span" style="font-style: italic;"><span class="Apple-style-span" style="font-size:small;">It would be interesting to see to what extent JIT could optimize code like that when it learns that object is not null… could it throw away everything but object.m()? This certainly requires more investigation.</span></span></div><div></div></blockquote><div><span class="Apple-style-span" style="font-weight: bold;">Maybe, babe, boom</span><br /></div><div><div>Another option would be to turn to Functional Programming for an answer. This is one of the things known in FP world for ages: <span class="Apple-style-span" style="font-weight: bold;">Maybe </span>in Haskell, or <span class="Apple-style-span" style="font-weight: bold;">Option </span>in Scala and F#. Here’s a <a href="http://debasishg.blogspot.com/2008/03/maybe-scala.html">nice description by Debasish Gosh</a>, and if you want to learn about Monads, <a href="http://james-iry.blogspot.com/search/label/monads">James Iry’s blog</a> or a Haskell book would be a good place to start. But we don’t have Monads in Java, Stephan Schmidt tried to <a href="http://feeds.feedburner.com/~r/stephansblog/~3/357235228/">simulate Maybe with Iterable</a>, and the result is cute, very cute even, but lacks the monadic awesomeness of flatMap, as others have pointed out. Hm, but wait, we do have a monad in Java. That’s exceptions. The naïve translation of Maybe in Java would be:</div><div><br /></div><div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">String </span>street;</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">try </span>{</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> street = account.getOwner().getAddress().getStreet();</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">} <span class="Apple-style-span" style="font-weight: bold;">catch </span>(NullPointerException e) {</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> street = <span class="Apple-style-span" style="font-weight: bold;">null</span>;</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">}</span></div><div><br /></div><div>Ok, it’s not so clean and pretty as pattern match, but… well, that’s Java. No, wait, smart and experienced programmers like us – we know that we shouldn’t use exceptions that way, because it is expensive! Hm, and why is it? Because <a href="http://blogs.sun.com/jrose/entry/longjumps_considered_inexpensive">filling in the stack trace</a>, actually, otherwise it’s <a href="http://www.javaspecialists.eu/archive/Issue129.html">rather cheap</a>. But we don’t need stack trace here, only… the exception is the standard NPE, we cannot subclass it and override fillInStackTrace(). Bummer.</div><div><br /></div><div>Using exceptions for control flow is <a href="http://www.drmaciver.com/2009/03/exceptions-for-control-flow-considered-perfectly-acceptable-thanks-very-much/">debatable</a>. I am not a proponent of this style, just for the record. I am simply exploring options… what if the JVM “magically” knew not to fill in stack trace when it’s not used? Exceptions would become cheaper and whole new programming style in Java would emerge...? </div><div><br /></div><div>Some of the Java 7 language enhancement proposals are to do with exceptions, <a href="http://tech.puredanger.com/java7/#catch">multi-catch</a> for example, I am all for it BTW. Now what if we add another flavor to catch and introduce “no-instance” catch, such as:</div><div><br /></div><div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">try </span>{</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> //…</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">} <span class="Apple-style-span" style="font-weight: bold;">catch </span>(NullPointerException) {</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> //…</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">}</span></div><div><br /></div><div>Note that there is no e, no exception instance, no way to re-throw or print – clearly no need for a stack trace. What if JVM kept a bit-map of exception types in “no-instance” try/catch blocks on the stack, and threw these exceptions without filling in the stack trace? After all, we are guaranteed that they are caught and no “phantom” exception like this escapes to the user… these exceptions could be pooled too. Then we could say</div><div><br /></div><div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">String </span>street;</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">try </span>{</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> street = account.getOwner().getAddress().getStreet();</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">} <span class="Apple-style-span" style="font-weight: bold;">catch </span>(NullPointerException) {</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> street = <span class="Apple-style-span" style="font-weight: bold;">null</span>;</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">}</span></div><div><br /></div><div>And <a href="http://www.javac.info/">if we had closures</a>, we could even make it prettier. We could create a utility method like</div><div><br /></div><div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">public static</span><span class="Apple-style-span" style=""> <T> </span><t>T nullsafe({ => T} expression) {</t></span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> <span class="Apple-style-span" style="font-weight: bold;">return </span>nullsafe(expression, <span class="Apple-style-span" style="font-weight: bold;">null</span>);</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">}</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">public static</span> <t><T> T nullsafe({ => T} expression, T default_value) {</t></span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> <span class="Apple-style-span" style="font-weight: bold;">try </span>{</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> <span class="Apple-style-span" style="font-weight: bold;">return </span>expression.invoke()</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> } <span class="Apple-style-span" style="font-weight: bold;">catch </span>(NullPointerException) {</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> <span class="Apple-style-span" style="font-weight: bold;">return </span>default_value;</span></div><div><span class="Apple-style-span" style="font-family:'courier new';"> }</span></div><div><span class="Apple-style-span" style="font-family:'courier new';">}</span></div><div><br /></div><div>It would be invoked like this:</div><div><br /></div><div><span class="Apple-style-span" style="font-family:'courier new';"><span class="Apple-style-span" style="font-weight: bold;">String </span>street = nullsafe({ => account.getOwner().getAddress().getStreet() });</span></div><div><br /></div><div>In all its glorious maybiness and with no, or little, performance overhead?! :-) But hey, I said I don’t like clients deciding on the value that the method returns… true, which is why I am not entirely happy with any of the proposals. But at least here we don’t change the language for the sake of null alone – the “exceptional” invocation is explicitly made with a catch clause or via a special library call. </div></div></div></div><div><p class="MsoListParagraph"><span class="Apple-style-span" style="font-weight: bold;">Epilog</span></p><p class="MsoListParagraph">All this just for the sake of intellectual exercise, so don't take too seriously. :-)</p><p class="MsoListParagraph"><span class="Apple-style-span" style="text-decoration: underline;">Update</span>: </p><p class="MsoListParagraph">So why I don't like any of the solutions, not even the ones I proposed? The "default clause" is essentially another static method. It may even work for interfaces, with a slight twist. The real problem is that static cannot be overridden, unlike the method it is "attached to", so the default clause and the actual method body will not correspond, so we basically gained nothing. </p><p class="MsoListParagraph">As for the instance-less exception, call me old-fashined, but I think that exceptions are for exceptional things, and this is stretching the hacks around them just one bit too far. </p><p class="MsoListParagraph">So I'll stay with plain old null for now, thank you.</p><p class="MsoListParagraph"><br /></p></div></div></div></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com8tag:blogger.com,1999:blog-8866592669665585195.post-90396693992886337332009-01-09T17:35:00.008+02:002009-01-09T23:11:43.344+02:00The return of forgotten design patternsSome design patterns are used all the time and their names are known to all - like facade, factories and proxies. Some design patterns are <a href="http://tech.puredanger.com/presentations/design-patterns-reconsidered">more popular than they should be</a>. But some, although rarely mentioned by their name, have been recently "rediscovered". I'm talking about <a href="http://www.javaworld.com/javaworld/jw-07-2003/jw-0725-designpatterns.html">Flyweight</a> and <a href="http://en.wikipedia.org/wiki/Memento_pattern">Memento</a>.<br /><br /><span style="font-weight: bold;">Flyweight</span><br />This one basically lets us share n instances between m concurrent clients when m > n. It separates "intrinistic state", the normal class members, and "extrinistic state", which is maintained via parameter passing and return values. Make your intrinistic state immutable, and you can share the same instance between multiple clients. Cool, ha? Priceless. Look at <a href="http://en.wikipedia.org/wiki/Concurrent_computing#Concurrent_interaction_and_communication">message passing concurrency instead of shared memory concurrency</a>, <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST</a>, <a href="http://martinfowler.com/bliki/Transactionless.html">transactionless architecture</a>... All these treasures actually follow the same spirit as Flyweight.<br /><br /><span style="font-weight: bold;">Memento</span><br />This pattern suggests that if you want to save your object state, you better export it in a new dedicated memento object and store the memento. Then restore your object from the memento.<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://upload.wikimedia.org/wikipedia/commons/1/18/Memento_design_pattern.png"><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 444px; height: 180px;" src="http://upload.wikimedia.org/wikipedia/commons/1/18/Memento_design_pattern.png" alt="" border="0" /></a>This is like serialization, only serialization didn't follow the pattern, unfortunately.<br /><br />Josh Bloch suggests we do it manually with so called "Serialization Proxies" - see item 78 in chapter 11 of 2nd edition of "<a href="http://java.sun.com/docs/books/effective/">Effective Java</a>". Here's a slide from <a href="http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1512.pdf">JavaOne 2006 preso</a>:<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvGJNEXMbGR7Tn92xtg-bFjAe7lCRjXZMMGjZNmBGGAlJ3ExqHH_47kfBPcsVuZjnZXv3It9MBDetg206tnxef8dcPIOm5bY_boG3vVzu-e34IxZCOPgER8tkKyrHOuFLkUiHDyHsNrfI/s1600-h/ser_proxy.JPG"><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 400px; height: 300px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvGJNEXMbGR7Tn92xtg-bFjAe7lCRjXZMMGjZNmBGGAlJ3ExqHH_47kfBPcsVuZjnZXv3It9MBDetg206tnxef8dcPIOm5bY_boG3vVzu-e34IxZCOPgER8tkKyrHOuFLkUiHDyHsNrfI/s400/ser_proxy.JPG" alt="" id="BLOGGER_PHOTO_ID_5289334478230712578" border="0" /></a>The book lists more advantages of the pattern, like improved security (see item 76 - danger of hackers acquiring references to private fields using de-serialization), ability to de-serialize a different class from the originally serialized instance (RegularEnumSet and JumboEnumSet example) etc.The name "memento" isn't mentioned though.<br /><br />Now imagine persistence architectures actually using intermediate memento objects... instead of modifying actual objects bytecode, breaking encapsulation with access to their private fields, imposing constraints like public empty constructors and so on... Maybe we would have been better off with mementos...?Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com0tag:blogger.com,1999:blog-8866592669665585195.post-32939011830509820552009-01-09T13:22:00.006+02:002009-01-09T14:02:53.518+02:00Static types are from Mars, Dynamic types are from Venus<div style="text-align: center;"><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://upload.wikimedia.org/wikipedia/en/8/8c/VenusandMarsalbumcover.jpg"><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 300px; height: 300px;" src="http://upload.wikimedia.org/wikipedia/en/8/8c/VenusandMarsalbumcover.jpg" alt="" border="0" /></a><a href="http://www.paulmccartneyshop.com/mall/productpage.cfm/PMEn/163473">Venus and Mars</a><br /></div><br /><span style="font-weight: bold;">static </span>- associated with logic and acting by the rules, strong, efficient, usually responsible for safety and order enforcement; but non-compromising (for better or worse), non-adaptive, weak in communication skills.<br /><br /><span style="font-weight: bold;">dynamic </span>- associated with beauty and elegance, light, good in communication skills, can usually be easily made to do what you want them to, change all the time and adapt to change well; but unpredictable, act on intuition rather than logic, often seen as less efficient and weaker.<br /><br /><hr />Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com0tag:blogger.com,1999:blog-8866592669665585195.post-25086038011454524182009-01-07T19:10:00.026+02:002009-02-15T13:52:10.972+02:00Types and componentsJust some thoughts following a recent conversation I had. Don't we always want static types? If we can detect errors in our program, why not do it as early as possible? Sure. So when is "as early as possible"? I think the answer depends on what our program is - is it one monolithic piece or a component? <div><br /></div><div>In the past monolithic software was prevalent, but today I would bet that most software is meant to be a component. Just look at open-source as it used to be before Java - you'd usually download the C source-code, change it if you need, build it all on your machine, and create one big executable. (And BTW - congratulations, you are a geek.) Cross platform Java changed the situation. Now open-source projects give you a jar to download, you put it on your classpath and you are ready to go. This lowered the bar for open-source adoption, and contributed (aside less restrictive licenses and other factors) to baby-boom of open-source frameworks and tools. Nowadays a Java developer cannot even imagine having no 3rd party jars in the classpath!<br /><br />Static type check validates our software component against other components in the <span style="font-weight: bold;">compilation</span> environment. Does it match the <span style="font-weight: bold;">runtime </span>environment? What about different configurations of the runtime environment - there are tests and real deployments, and various types of deployments, and any given installation environment can change over time - new components being added, other updated or removed? How do we guarantee that compile time checks still hold? The short answer is - we can't. We need dynamic type safety anyway. Now let's examine the added value and the price (yes, there is one!) of deeply static types.<br /><br />On code organization level, we try to reduce the dependencies to bare minimum - hide classes behind interfaces that we hope will remain more stable. The problem is that number of interfaces and factories in our application grows, while pursuing modularity we sacrifice simplicity... So maybe the problem is in the name? <a href="http://whiteoak.sourceforge.net/">Some</a> go as far as add support for <a href="http://en.wikipedia.org/wiki/Structural_type_system">structural types</a>, <a href="http://debasishg.blogspot.com/2008/06/scala-to-java-smaller-inheritance.html">minimizing dependency</a> to a single field/method signature (<a href="http://beust.com/weblog/archives/000476.html">not a problem-free</a> solution, but there are <a href="http://www.jot.fm/issues/issue_2008_01/article4/">interesting refinements</a>). All this may help, but doesn't really solve the problem.<br /><br />Another aspect we need to deal with is building and packaging the software. Here we enter the world of dependency management, the world of "make", Ant, Maven, repositories, jar versions; if it's a large enough and complex enough software we work on, simply speaking - we enter the world of pain. I still find it strange that we haven't found a better way.<br /><br />As for application deployment and its problems, we'll get back to it later. But the truth is that no matter how hard we try, we can't guarantee there will be no errors when we deploy our software, so ... JVM doesn't trust us and gives us <a href="http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#88597">verification</a>.<br /><br />Simply put, when class is compiled, some of its requirements from other classes are captured and encoded into the bytecode. Then JVM would check them when the class is loaded, and reject the class if they can't be met. (This is really an over-simplified description of a complex algorithm, which also takes time to execute, despite <a href="http://en.wikipedia.org/wiki/Java_performance#Split_bytecode_verification">optimization efforts</a> on JVM side.) So this isn't really a dynamic check, it's something in between - names in our class get linked when it is loaded. In the classic Java SE class-loading scheme, where components are basically a chain, this scheme should work. But if we want real components, ones we can add, override, replace or remove while program is running - sweet turns sour. Our interfaces and factories have names, and classes that represent them need to reside in some "common vocabulary" usually loaded by the parent classloader, because it's not only the class bytecode that matters, but also <a href="http://www.bracha.org/classloaders.ps">who loaded what</a>. Since we are talking actual classes, not their names, once we loaded two components, they cannot change their protocol of communication without reloading their parent, they also can't use a different version of a sub-component that the parent component has referenced.<br /><br />In JEE that sort of things is necessary, that's why classloading in JEE is a terrible mess, not only it does not follow any specification, but it is different in almost each and every app server (wasn't there supposed to be portability?!) If you ever used <a href="http://commons.apache.org/logging">commons-logging</a> in a JEE app, you probably <a href="http://www.qos.ch/logging/classloader.jsp">know what I mean</a>. Maybe it got fixed lately, I don't know, but the <a href="http://commons.apache.org/logging/tech.html">Tech Guide</a> for commons-logging is an ode to classloader frustration.<br /><br />Back to deployment: whenever there are some sort of dynamic components - JEE, Spring or OSGi, there is always reflection. And most of the time there's lots of XML too. It's an escape route from static types. I attended <a href="http://javaedge.net/sessions.html">Alef Arendsen's session</a> at JavaEdge that presented OSGi and SpringSource. I carefully watched Alef juggle between XML, source and console like a child who watches a circus magician trying to uncover his tricks. But I didn't quite figure out the magic. And that was a whole session just for HelloWorld. I know Spring folks are doing best they can, and they're smart and all... but comparing to Smalltalk, I wasn't quite impressed. As for other solutions, although I haven't tried this out, there's <a href="http://code.google.com/p/peaberry/wiki/DetailedDesign">Guice/OSGi integration</a> without XML and with dynamic proxies and on-the-fly bytecode generation with ASM, but there's some overhead for the user, because it requires intermediate objects for services. So this way or the other, looks like JVM platform is holding us back.<br /><br />Verification is addition, not replacement of dynamic checks. So what we get is basically a triple check of correctness (javac, verifier, dynamic) but loss of flexibility - we are interfering with components runtime life-cycles. If the invocation target is resolved just in time when the call is made, nothing precludes the target component from being reloaded between calls. But with preemptive validation, we get a static dependency tree at runtime, classes wired with each other "too early" and for good, which makes reloading a component very hard (although people <a href="http://www.zeroturnaround.com/presentation/">keep trying</a>). The reason for "early linking" is also performance, but late binding doesn't mean that the runtime platform can't do any optimization heuristics... but they'll have to be dynamic optimizations in the style of JIT. Will <a href="http://jcp.org/en/jsr/detail?id=292">invokedynamic</a> bring the salvation?<br /><br />It seems when we are talking about multiple components, "statically typed platform" does not quite do the job. Static type check may mean a lot inside a component, but as for inter-component communication they are not only useless, but harmful. People sometimes dismiss dynamic types, because they think "it's like static types, but without static types". What they may not realize is that you are not just loosing, you are gaining something with dynamic types. You get <span style="font-weight: bold;">late binding</span> and <span style="font-weight: bold;">meta-programming</span>, and in a multi-component environment, it means a whole lot!<br /><br />And that's when we are talking "inside the platform" components developed in the same language. Once you work with a system that runs on a different platform or developed in a different language - our type system doesn't normally stretch across the communication boundary. The other system may not even have static types, and since we are only as strong as the weakest link, our static types don't really help us. I think every time we try to encode types into communication between systems we end up with a monster like CORBA or Web Services. But there's another (unfortunately popular) extreme of just sending a string over and hoping for the best - with no checking on our side at all. Then we are relying on the other system to stop us from doing damage, and there's no way to correctly blame the component that made an error - was it a wrong string or an unexpected change on the other side? I think that ideally type or contract checking and conversions can be done dynamically on both sides, and not as part of the protocol. This results in light and flexible data-exchanging protocols (like HTTP or ATOM) which are easier to work with and I think will win in the end. On the more theoretical level I like <a href="http://www.cs.utah.edu/%7Ekathyg/interop.pdf">this model for intercommunication</a> and of course there are <a href="http://gbracha.blogspot.com/2008/12/unidentified-foreign-objects-ufos.html">Aliens</a>, that model external system as a special object in our system.<br /><br />So as far as I see - components simply require a dynamic environment, they may be statically checked inside, but act as "dynamic" to the outside world. Sort of hard skeleton and soft shell. Indeed soft parts are much easier to fit together and less breakable, due to flexibility - this is used often in mechanical engineering and in nature, so <span style="font-weight: bold;">why not in software?</span><br /><br /></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com1tag:blogger.com,1999:blog-8866592669665585195.post-58395679268948443112008-12-11T17:02:00.005+02:002008-12-11T21:10:21.938+02:00How not to implement ComparableI have already blogged about the <a href="http://sensualjava.blogspot.com/2007/11/beware-overflows-in-numeric-operations.html">danger of numeric overflows</a>. I recently came across this example in Java course materials (!!!):<br /><pre>public class Foo implements Comparable<Foo> {<br />private int number;<br />public int compareTo(Foo o) {<br /> if (this == o) return 0;<br /> return number - o.number;<br />}<br />}<br /></pre>How do you think Integer.MAX_VALUE compares to negative numbers? It will appear smaller. This reminds me of even worse case we encountered in a real codebase. Look at this:<br /><pre>public class Foo implements Comparable<Foo> {<br />private long id;<br />//...<br />public int compareTo(Foo o) {<br /> if (this == o) return 0;<br /> return (int)(id - o.id);<br />}<br />public boolean equals(Object o) {<br /> return o != null && (o instanceOf Foo) && compareTo((Foo)o) == 0;<br />}<br />}</pre>How do you think <span class="Apple-style-span" style="font-family:'courier new';">new Foo(8325671243L)</span> and <span class="Apple-style-span" style="font-family:'courier new';">new Foo(25505540427L)</span> compare? They are equal, but I will do it ala <a href="http://www.weiqigao.com/blog/tags/java/">Weiqi Gao</a> and leave you to find out why... :-)Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com4tag:blogger.com,1999:blog-8866592669665585195.post-38809318363722204282008-12-11T16:01:00.004+02:002008-12-11T16:55:26.294+02:00Static initializers - updateAfter some interesting comments to my <a href="http://sensualjava.blogspot.com/2008/12/case-against-static-initializers.html">previous write-up</a> I decided to make a follow-up post with some additional details.<div>Here is the code from <a href="http://java.sun.com/docs/books/effective/">Effective Java</a>:</div><br /><pre>public class Person {<br /> private final Date birthDate;<br /> //...<br /> private static final Date BOOM_START;<br /> private static final Date BOOM_END;<br /><br /> static {<br /> Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));<br /> gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);<br /> BOOM_START = gmtCal.getTime();<br /> gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);<br /> BOOM_END = gmtCal.getTime();<br /> }<br /><br /> public boolean isBabyBoomer() {<br /> return birthDate.compareTo(BOOM_START) >= 0 &&<br /> birthDate.compareTo(BOOM_END) < 0;<br /> }<br />}<br /><br /></pre><br /><div>and here's how I would have changed it:</div><br /><pre>public class BabyBoom {<br /> private static final BabyBoom boom = new BabyBoom();<br /> private Date start = null;<br /> private Date end = null;<br /><br /> private BabyBoom() {}<br /><br /> public static BabyBoom getInstance() {<br /> if (boom.start == null || boom.end == null) {<br /> Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));<br /> gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);<br /> boom.start = gmtCal.getTime();<br /> gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);<br /> boom.end = gmtCal.getTime();<br /> }<br /> return boom;<br /> }<br /><br /> public boolean contains(Date birthDate) {<br /> return birthDate.compareTo(start) >= 0 && birthDate.compareTo(end) < 0;<br /> }<br />}</pre><pre><br />public class Person {<br /> private final Date birthDate;<br /> //...<br /> public boolean isBabyBoomer() {<br /> BabyBoom boom = BabyBoom.getInstance();<br /> return boom.contains(birthDate);<br /> }<br />}</pre><br />I didn't synchronize <span class="Apple-style-span" style="font-family: 'courier new';">getInstance</span>, because initializing the dates twice does no harm, so it's not worth the price of synchronization. However I did check that both fields are initialized before returning the object in <span class="Apple-style-span" style="font-family: 'courier new';">getInstance</span>. <div></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com2tag:blogger.com,1999:blog-8866592669665585195.post-77706551192208252012008-12-07T22:05:00.005+02:002008-12-09T10:58:53.152+02:00A case against static initializers<div>"Effective Java" is an excellent book. I recently bought the 2nd edition, and it is absolutely fabulous, priceless. However after quite some time in the industry, I've learnt not to take any advice blindly. First edition was also excellent, but several of the items were revisited since then. So here's an item that I have mixed feelings about - <span class="Apple-style-span" style="font-weight: bold;">A</span><span class="Apple-style-span" style="font-weight: bold;">void creating unnecessary objects</span>. The advice is to use static initializers for the expensive computation. </div><div><br /></div><div>Static initializers are double-edged sword. It's like with the stock exchange in times of crisis - for a particular individual it may be a good idea to sell the stock, but the trouble is that everybody's doing it, and in the end everybody's losing big-time. Same applies to static initializers. One or two may seem harmless, but they add up and together create a big problem. The fact that static initializers <strike>are</strike> <span class="Apple-style-span" style="font-style: italic;">(edit) </span>may be invoked at program start-up affects everybody and since they potentially interfere with classloading, it's <strike>very hard</strike> <span class="Apple-style-span" style="font-style: italic;">(edit)</span> harder to debug them if anything goes wrong.</div><div><br /></div>Here is how it usually gets out of hand: people start with initializing static members in static blocks. Map of values, sort of configuration details. That alone sounds harmless. But soon comes the time when the values in a map need to be read from a properties file, so here we got IO within static block. Uh oh, better catch these exceptions. Before you notice the whole thing turns into a <a href="http://www.javapuzzlers.com/">puzzler</a>. Don't believe me? Here's a real problem I had.<div><br /></div><div>Server in Java, client is either applet or JNLP. On certain machines, only one of them can run. You run server first - client never comes up, no error whatsoever. You reboot and connect as client to another machine - no problem. But if you try to start up the server locally - silent death. A team in India spends months on it. In vain. The whole release is detained, escalation to senior management. The thing ends up on my desk after a ruthless blame game between teams. Long story short: it's a DirectX problem. Why the **** does the server need DirectX? Ah. What's next after reading defaults from a properties file? Reading them from the database. Oh, but it's a different process, and the database needs to be up. So we not just connect to database from initialization block, we wait for the database process to be up. Great idea. How? We follow "best coding practices" and reuse: find a poller utility somewhere in the JDK. Apparently there is a java.awt.Timer. Why not? Great idea. Apparently, a touch of one AWT class causes a bunch of other AWT classes to load, which in turn loads DirectX and OpenGL dlls. And guess what - Windows on some machines has a <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4455041">nasty bug</a>, that only allows to load them once per machine, regardless of the user. And when another user tries to do it - the loading gets stuck. And our server is of course a system process, while the client belongs to the logged in user. </div><div><br /></div><div>Since it was a last minute fix, we solved it with some JVM flags that disabled DirectX and OpenGL. The problem was not the fix, but the diagnosis. If it was part of the regular code, it would have been easy to connect with a debugger, see what call gets stuck, investigate it from there. But as it was part of start-up, people didn't know where to look. Not to mention the man-months accumulatively spent by developers who waited for the server to restart when testing. </div><div><br /></div><div>So... what's the lesson here? <a href="http://gbracha.blogspot.com/2008/02/cutting-out-static.html">Life is better without static</a>, avoid it as much as you can. <br /><div><div><br /></div></div></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com9tag:blogger.com,1999:blog-8866592669665585195.post-29241760686098544222008-12-07T14:24:00.000+02:002008-12-07T14:26:21.354+02:00Java... tea?<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQZGQh6Q785S44MPefURiH53CqLYMVXIjomelWKZTqZDdbGia1zuNsLYko0aH4dm1G1BLneJnTL14fun0gR0fJf9YEdP_6YGNp15q7ojm9ObIF7upM91G3IrWrFCtaIJSyMDSge3nf-Jk/s1600-h/green_java_tea.jpg"><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 252px; height: 320px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQZGQh6Q785S44MPefURiH53CqLYMVXIjomelWKZTqZDdbGia1zuNsLYko0aH4dm1G1BLneJnTL14fun0gR0fJf9YEdP_6YGNp15q7ojm9ObIF7upM91G3IrWrFCtaIJSyMDSge3nf-Jk/s320/green_java_tea.jpg" border="0" alt="" id="BLOGGER_PHOTO_ID_5277023318428351730" /></a>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com2tag:blogger.com,1999:blog-8866592669665585195.post-53486837793009716462008-12-07T12:40:00.011+02:002008-12-07T16:37:35.853+02:00No clone for you!<a href="http://www.javapractices.com/home/HomeAction.do">Java Practices</a> call <a href="http://java.sun.com/javase/6/docs/api/java/lang/Cloneable.html">Cloneable</a>/<a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#clone()">Object#clone</a> API <a href="http://www.javapractices.com/topic/TopicAction.do?Id=71">pathalogical</a> and suggest to avoid it. I have to agree. Here's my little story. <div><br /></div><div>I have a method that receives a certain object, which is Cloneable. Now I want to actually clone that object, so I am calling the clone method. Makes sense, no? Apparently not. My slightly outdated version of IDEA was confused, just as I was, and did not complain. But Javac was cruel and uncompromizing. No clone for you. </div><div><br /></div><div><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMDGfDUOMOHEPFq-4EPz6f7GVy6DALgKXOQXewa5h7qkud29_oC0ISHn0psNCy_pJp1ce9XjA7UcEoPHBcLoaA2xfaGguKGp4ldvIEo3N71dX_q1VE8J6u9gYwnAdAZ7nHxSBSID6sLJU/s320/clone_nazi.jpg" style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 280px; height: 280px;" border="0" alt="" id="BLOGGER_PHOTO_ID_5277002438826242578" /></div><div><br /></div><div>Because Cloneable does not require a clone() method, and Object#clone() can be protected. WTF? My objects subclass different not-necessarily-cloneable classes, so they can't have a common cloneable superclass. So I'll define my own ReallyCloneable interface that has a public clone method, sounds simple enough...? Not!</div><div><div><pre>public interface ReallyCloneable extends Cloneable {<br /> public Object clone() _<br />}</pre></div><div>Now I realize there's <a href="http://java.sun.com/javase/6/docs/api/java/lang/CloneNotSupportedException.html">CloneNotSupportedException</a> to throw. A checked exception. I have 2 options: be a good girl, adhere to best practices and clone the signature of Object#clone, or ... not. Let's explore both options. <br /></div><div><div><pre>public interface ReallyCloneable extends Cloneable {<br /> public Object clone() throws CloneNotSupportedException;<br />}</pre></div><div>Now all my classes (let's assume they are simple enough to contain only primitives, Strings and arrays of the above) implement ReallyCloneable and add those 3 lines:</div><div><div><pre>public Object clone() throws CloneNotSupportedException {<br /> return super.clone();<br />}</pre></div></div><div>But whoever clones my objects also needs to add:<br /></div><div><div><pre>try {<br /> //call clone<br />} catch (CloneNotSupportedException e) {<br /> //handle it... how???<br />}</pre></div></div><div>Because implementing Cloneable and all the rest means that JVM will not necessarity throw CloneNotSupportedException, but as far as Javac is concerned, it still may. So no matter what, the caller needs to prepare himself for the worst. Then why bother with interfaces and all that, I ask? People say Java is verbose. I don't mind verbose, but bloated with boiler-plate to this extent?! </div><div><br /></div><div>The other option is <span class="Apple-style-span" style="font-weight: bold;">not to declare the exception</span> in ReallyCloneable. This is possible because <a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.8.3">overriding rules</a> <a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#308526">do not require to throw the exceptions</a> of the overridden method.</div><div><pre>public Object clone() {<br /> try {<br /> return super.clone();<br /> } catch (CloneNotSupportedException e) {<br /> //hm...? <br /> }<br />}</pre></div><div>Even though JLS allows it, my IDE and static analysis tools will complain. So I have to either reconfigure them or add some "escape" annotations. More typing... By now I feel like a typomaniac. And wait, I should handle the exception - I don't want to swallow it. Besides, what if someone really objects to being cloned? There is a need for a runtime exception. </div><div><pre>public class CloneFailedException extends RuntimeException {<br />public CloneFailedException() {<br />super();<br />}<br /> public CloneFailedException(CloneNotSupportedException e) {<br /> super(e);<br /> }<br />}</pre></div><div>and</div><div><pre>public Object clone() {<br /> try {<br /> return super.clone();<br /> } catch (CloneNotSupportedException e) {<br /> throw new CloneFailedException(e); <br /> }<br />}</pre></div><div>Now at least the callers don't have to catch. But they will still have to cast, because there is no way to express a self type with Java's static types system. Sigh.</div><div><br /></div><div>And all this why? and for what? Couldn't we just have Cloneable with a public clone and a RuntimeException to throw if we didn't want to be cloned? Simple as that? </div><div><br /></div><div>This is yet another example of static type system's failed attempt to protect us from ourselves. </div><div><br /></div><div><br /></div></div><div><span class="Apple-style-span" style="font-family:Georgia;"><br /></span></div></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com10tag:blogger.com,1999:blog-8866592669665585195.post-600491550009091212008-11-29T17:15:00.002+02:002008-12-07T14:19:32.841+02:00Brains, bucks and programming languages<div style="text-align: right;"><span class="Apple-style-span" style="font-style: italic;">The title is supposed to be a paraphrase of "sex, drugs and <span class="blsp-spelling-error" id="SPELLING_ERROR_0">rock'n'roll</span>" in a geeky context.</span></div><div style="text-align: right;"><br /></div>This autumn I went to see <a href="http://sensualjava.blogspot.com/2008/10/two-days-in-life.html">Paul McCartney in concert</a> - a lifetime dream come true. For most people Paul McCartney is first of all an ex-<span class="blsp-spelling-error" id="SPELLING_ERROR_1">Beatle</span>. Indeed, during the concert he played many classic Beatles tunes to please the audience. And the audience was very pleased. Then, he cashed in the multi-million-dollar cheque and went back to England to do what he really likes - which at this point seems to be composing <a href="http://www.thefiremanmusic.com/">experimental electronic music</a>. To me it looks pretty fair. <div><br /></div><div>Recently I <span class="blsp-spelling-error" id="SPELLING_ERROR_2">listenned</span> to <a href="http://www.infoq.com/presentations/gosling-jvm-lang-summit-keynote">James Gosling's keynote</a> at the <span class="blsp-spelling-error" id="SPELLING_ERROR_3">JVM</span> Language Summit. I actually enjoyed the presentation very much. One of the things he said, was something like "My dream would be to implement <span class="blsp-spelling-error" id="SPELLING_ERROR_4">Fortran</span> over <span class="blsp-spelling-error" id="SPELLING_ERROR_5">JVM</span> ... ah, but I have a day-job". Now, not that JVM really needs a Fortran IMO. But think about it for a second. How many people in the world can design a programming language? How many of them can design a <span class="Apple-style-span" style="font-weight: bold;">good</span> programming language? And a <span class="Apple-style-span" style="font-weight: bold;">popular</span> one? Java is more popular than Beatles. <span class="blsp-spelling-error" id="SPELLING_ERROR_6">Uhm</span>, well... even if it's not, you get the idea. Now what can be more important for James Gosling to do during his day job than design a programming language of his choice, I should ask his employer? What? Throwing T-shirts at <span class="blsp-spelling-error" id="SPELLING_ERROR_7">JavaOne</span> attendants? No, really. Why is it that James Gosling can't do anything he freaking likes for the rest of his life?</div><div><br /></div><div>I think something in our business is unfair. I am not saying Microsoft model is right, I am very pro open-source and free software and all that. But I'm confused - something about it isn't right. Large IT companies make loads of money, and waste a lot of it on complete crap - I've seen this from inside. So how come <span class="blsp-spelling-error" id="SPELLING_ERROR_8">Gilad</span> <span class="blsp-spelling-error" id="SPELLING_ERROR_9">Bracha</span> <a href="http://gbracha.blogspot.com/2008/11/we-have-good-news-and-we-have-bad-news.html">cannot find funding</a> for <span class="blsp-spelling-error" id="SPELLING_ERROR_10">Newspeak</span> development? This is totally surreal!</div><div><br /></div><div>There goes another angry post.</div><div> </div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com6tag:blogger.com,1999:blog-8866592669665585195.post-49270180169029477032008-11-29T14:25:00.015+02:002008-12-08T23:12:27.302+02:00DSL - fuel for lifeDo you feel that your programming language is too bloated? I do, and I know I am <a href="http://www.cs.bgu.ac.il/~gwiener/programming/is-java-heading-for-a-fall">not alone</a>. <br /><br /><div>Let's take a look at Java. You may ask - what do you mean, when you say Java? Ah, good question. There is Java, the language, as described in <a href="http://java.sun.com/docs/books/jls/">the spec</a>. Java the Standard. Don't you wonder where's the new edition of the book, BTW? Anyway, then there's mini-edition, enterprise edition, real-time Java... there's a huge stack of official/certified technologies (e.g. all the <span class="blsp-spelling-error" id="SPELLING_ERROR_0">JEE</span> stuff - is <span class="blsp-spelling-error" id="SPELLING_ERROR_1">JSP</span> or <span class="blsp-spelling-error" id="SPELLING_ERROR_2">JSF</span> Java? is <span class="blsp-spelling-error" id="SPELLING_ERROR_3">JPQL</span>?), for which there are often multiple vendors. That's not all, there are all the popular open-source frameworks that don't bother getting Sun's approval, and yet they possess lion-share of the market (e.g. Eclipse, Spring). There's no chance to even keep track of all this, forget mastering. And yet, I don't feel that I have all I need. I have all that, and yet I can't write a descent program the way I'd like to, because I am missing some core features. What? Let's see - how about proper <span class="blsp-spelling-error" id="SPELLING_ERROR_4">modularity</span>, closures, <span class="blsp-spelling-error" id="SPELLING_ERROR_5">tuples</span>, local type inference, properties... </div><div><br /></div><div>Java made the grade in expanding layer by layer - to the extent where it reminds me the state of the Earth in <a href="http://en.wikipedia.org/wiki/WALL-E">Wall-E</a>. If you haven't seen the <a href="http://www.imdb.com/title/tt0910970/">movie</a>, I'll just say that the Earth drowned in human-produced garbage, and the garbage made it inhabitable for anything organic. The garbage in Java makes it impossible for the core, organic features of the language to grow. In the movie, people are leaving, and robots stay back to clean up - now you make the analogy. </div><div><br /></div><div style="text-align: center;"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjYJPv76p6RWAoamZ4AUpUi_9jy4Q9J4mbjoT_k01mfpE9lwRGLoq2_iFNScwseVSlXRyEJJfWFrYS2jwfZ_yWGAsF5SYodaUbxLOmi4fJt8pPc6qu6LANLLwJCuPCeWSdguM8IX41HCIg/s320/Wall_e1_small.jpg" style="cursor:pointer; cursor:hand;width: 192px; height: 200px;" border="0" alt="" id="BLOGGER_PHOTO_ID_5274076138690299554" /><br /></div><div>As a Java programmer I really identify with Wall-E. Moving tons of garbage around, day after day, in a desperate attempt to clean up the world - something obviously impossible. And man, I'd love to be that flying-<a href="http://cultofmac.com/walle-and-apple-a-match-made-in-heaven/2178"><span class="blsp-spelling-error" id="SPELLING_ERROR_6">iPod</span>-looking</a> Eve from outer space. She's so strong, so modern, so clean and shiny... And she has a mission!</div><div><br /></div><div style="text-align: center;"><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1ZvkMCEx__6EyU2rYnia369c3vvG-GVjS9IQ0EqnS5NHIu4G7sv89XwwdlP8i4x61988NpOp2Cg91exjpRUzqKTzLyWaq-t5i0CkTcip8Eh7169MDa-OG28hXqgf2Kh-m0i0-DSg13Ic/s320/eve_small.jpg" style="cursor:pointer; cursor:hand;width: 200px; height: 200px;" border="0" alt="" id="BLOGGER_PHOTO_ID_5274076456493778834" /><br /></div><div><br /></div><div>If Wall-E is my Java, then my Eve is no doubt <a href="http://newspeaklanguage.org/"><span class="blsp-spelling-error" id="SPELLING_ERROR_7">Newspeak</span></a>. </div><div><br /></div><div>So what does it mean in a wider sense of programming languages? I think good language should have a small core, as little redundancy as possible. And it should grow from then on. Here's Guy Steel at <span class="blsp-spelling-error" id="SPELLING_ERROR_8">OOPSLA</span> '98:</div><div style="text-align: center;"><br /></div><div style="text-align: center;"><embed id="VideoPlayback" src="http://video.google.com/googleplayer.swf?docid=-8860158196198824415&hl=en&fs=true" style="width:400px;height:326px" allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash"></embed> </div><div style="text-align: center;"><br /></div><div>I think that the best way of growing is via internal domain specific languages, <span class="blsp-spelling-error" id="SPELLING_ERROR_9">DSLs</span>, - you don't change the core language, yet you cover more and more domains. Anders <span class="blsp-spelling-error" id="SPELLING_ERROR_10">Hejlsberg</span> also talked about it at the recent <span class="blsp-spelling-error" id="SPELLING_ERROR_11">PDC</span> conference - adding features as a <span class="blsp-spelling-error" id="SPELLING_ERROR_12">DSL</span>; and then, if the <span class="blsp-spelling-error" id="SPELLING_ERROR_13">DSL</span> is very successful and popular, add syntactic sugar to the core language, as they did with <span class="blsp-spelling-error" id="SPELLING_ERROR_14">LINQ</span>. I don't think that you need that latter part if your language is well suited for <span class="blsp-spelling-error" id="SPELLING_ERROR_15">DSLs</span> to begin with. So the language should have a small core <span class="Apple-style-span" style="font-weight: bold;">and</span> be well suited for <span class="blsp-spelling-error" id="SPELLING_ERROR_16">DSLs</span>. Java isn't DSL-friendly. <span class="blsp-spelling-error" id="SPELLING_ERROR_17">Scala</span> is much better, e.g. the Actors library. Haskell, Ruby and of course Smalltalk are really good at it. </div><div><br /></div><div>The last part is getting rid of garbage as you grow, and again, <span class="blsp-spelling-error" id="SPELLING_ERROR_18">Gilad</span> has an <a href="http://sensualjava.blogspot.com/2008/07/software-live-and-let-die.html">idea how to do that</a>. </div><div><br /></div>I could go on forever and ever about <span class="blsp-spelling-error" id="SPELLING_ERROR_19">DSLs</span>, showing examples like <a href="http://gbracha.blogspot.com/2007/01/parser-combinators.html">parser <span class="blsp-spelling-error" id="SPELLING_ERROR_20">combinators</span></a>, unit-test and <span class="blsp-spelling-error" id="SPELLING_ERROR_21">SQL</span> libraries and so on. Martin Fowler <a href="http://martinfowler.com/dslwip/">is writing a book</a>. So, instead of boring you with repeating what's been said many times, and enumerating lots of references, I will just finish with this cutest <a href="http://courses.ece.ubc.ca/571f/index.html">quote</a>:<div><br /></div><img src="http://courses.ece.ubc.ca/571f/pooh-logo.jpg" style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 144px; height: 147px;" border="0" alt="" /><div><span times="" new="" roman="" style="font-family:Arial,;"><span class="blsp-spelling-error" id="SPELLING_ERROR_22">DSLs</span> are for making languages bear-able.</span><ul> <span times="" new="" roman="" style="font-family:Arial,;"> <em>For I am a bear of very little brain and long words confuse me.</em> [<a href="http://en.wikipedia.org/wiki/Winnie-the-Pooh">Milne 1926</a>] </span></ul> <p> <span times="" new="" roman="" style="font-family:Arial,;"> The premise of this subject is that computers should adapt to the ways of people, and not the other way around. </span></p><div><br /></div></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com2tag:blogger.com,1999:blog-8866592669665585195.post-46171328933836397972008-10-23T01:42:00.004+02:002008-10-23T16:14:37.443+02:00Types and other virtuesHere's a thought. Why do Java Generics attract so much bad vibes? If we're talking about types again, gotta visit our old friends - ML, Haskell. They are doing fine, they've got it all figured out. <a href="http://en.wikipedia.org/wiki/Type_inference">Hindley-Milner</a> etc., they've proved themselves to be right.<br /><br />But them and Java, it's apples and oranges. So to bring them to the same arena with object oriented languages, let's see how are they doing on the front of extensibility? Well, there are some recent advancements, <a href="http://caml.inria.fr/pub/docs/manual-ocaml/manual006.html#htoc41">polymorphic variants</a> in OCaml, <a href="http://www.haskell.org/haskellwiki/Extensible_record">extensible records</a> in Haskell, but it's not like the other stuff they've figured out ages ago, there's a slight hint of hesitation here.<br /><br />So having types and being object oriented at the same time - maybe it's just, hm, non-trivial. If Martin Odersky <a href="http://www.codecommit.com/blog/scala/is-scala-not-functional-enough#comment-4162">says it's hard</a> for the compiler (and he's a genius!) - then it really must be. Now look at it as a reverse Turing test - if the machine can't figure it out, how the **** are we supposed to? Which means we need an escape route. If declaring the right type is hard, we need an easy way out.<br /><br />Pre-generics Java didn't bother itself too much with complex static types, the trick was to fall back on the dynamic types whenever in doubt: arrays - ArrayStoreException, collections - ClassCastException. Some say it's broken. It's a hole in a fence, but it's a way out . "Oops"<br /><br />Then Generics came and fixed the hole in the fence. But, without realizing, they violated the status-quo, the eco-system, they stepped on a butterfly. Suddenly, the brain hurts, and the only way out is dumping all the angle brackets and jumping over the fence. It's a "No Exit"!<br /><br />What does Scala do? Ah! First of all Scala has a much more advanced type system to start with. But the real trick is <a href="http://www.scala-lang.org/node/130">implicit</a>s. If it's too hard to declare the right type, just <a href="http://rickyclarkson.blogspot.com/2008/01/trivial-display-of-how-scalas-type.html">imperatively describe the conversion</a>. Done deal, here's your way out. It's pretty cool, but implicits have their share of bad vibes too. Can't live with them, can't live without them, I guess.<br /><br />So how about implicits for Java 7? No, actually how about Scala for Java 7? It's been <a href="http://sensualjava.blogspot.com/2007/12/past-forward.html">done before</a>, you know...Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com10tag:blogger.com,1999:blog-8866592669665585195.post-81655477360525774072008-10-05T23:53:00.007+02:002008-10-06T02:13:29.490+02:00The Great DivideWhat hasn't been said about static vs. dynamic types in programming languages? Read on at your own risk, because here I <a href="http://sensualjava.blogspot.com/2008/06/typsy-turvy.html">go again</a>...<br /><br />When you think of static types what comes to mind? <a href="http://haskell.org/">Haskell</a>? <a href="http://caml.inria.fr/ocaml/">OCaml</a>? <a href="http://www.scala-lang.org/">Scala</a>? Dear friend, you are better than most of us, but you have clicked the wrong URL. Peace. See you in another post...<br /><br />Did you say Java? Still with me? Good. Listen, now when the others have gone, just between you and me, the guys from the previous paragraph - they're on to some good stuff. Check it out, you won't regret it. But don't quit your day job, not just yet. It's a bit complicated, but did you ever witness <a href="http://www.extremeprogramming.org/">extreme programming</a> methodology implemented in a big corporation? No? Then picture this: <a href="http://en.wikipedia.org/wiki/Elbonia">Elbonians</a> take over <a href="http://www.dilbert.com/">Dilbert</a>'s firm and make everybody do <a href="http://www.extremeprogramming.org/">XP</a>. They even send <a href="http://en.wikipedia.org/wiki/Pointy-Haired_Boss">pointy-haired boss</a> to a <a href="http://www.scrumalliance.org/view/certification">Certified Scrum Master</a> course. Get the outcome? It can only end like the implementation of <a href="http://en.wikipedia.org/wiki/Carl_Marx">Carl Marx</a>'s ideas <a href="http://en.wikipedia.org/wiki/Kolhoz">in Russian countryside</a>. I am trying to say - there are ideals, and there is reality. In reality, <a href="http://pab-data.blogspot.com/2008/05/haskell-academia-goes-bowling.html">Haskell programs have bugs too</a>.<br /><br />So Java, you say. How do you feel about dynamic types? Cool? Get out of here. No really, it's no fun preaching to the converted. See you!<br /><br />Oh no, heaven forbid, you won't touch them with a stick. You're my guy then. So let's rewind to Java 1.4 days, after all many Java developers still use 1.4 and many others look back at it with nostalgia. Are you one of them? Ok. So what about pre-generics collections, do you think they are statically typed? Hmmm... And what percentage of your code involves collections? So this code was not entirely statically checked. Now add all the reflection stuff...<br /><br />But then of course came Generics. And suddenly Java is much more complex. How do I make my code compile, gee, wildcards, captures... ?! I am trying to get something done, hello!... It's easy of course to blame Generics implementation, but if we learn something from the folks whom I kindly asked to leave in the beginning, they'll tell you that finding correct static type for every element in your program is hard. They of course think that hard is good, they are noble men with ideals, they like overcoming challenges. But you and I, we're just trying to make a living. So we curse Sun and back off to an untyped collection. Hm, maybe we're just doing the right thing? Maybe sometimes we just know that our program is correct, but the compiler demands more and more typing and wastes our time?<br /><br />Java 5 was all about improving type-checking. If pre-defined types were not enough, annotations came handy. Define your own and test it at compile-time or at run-time. Did it ever happen to you that there were so many annotations, that you couldn't see the code?<br /><br />See, more types is not always a good thing. Unless you're very keen on intellectual challenges. James Gosling said this about Scala - functional programs will make your brain hurt, they are for calculus lovers. He's right. It's the kind of pain you feel in your muscles when you start working out, you know, that indicates they are still alive... So working out is good, but we can't afford doing it all day, ha?<br /><br />Maybe the appeal of plain old Java was that it's a combination of static and dynamic checks? So it's not that all dynamic is evil, maybe it's a matter of how much and where?<br /><br />Give dynamic types a break. Who knows, you may find eventually that they're good for some things.<br /><br />Peace.<br /><br />P.S. I've done some role playing here, just for the record. I do love Generics, even though they were hard to master. Annotations are overall very useful. Right now I don't do as much Java as I used to, and I do other fascinating languages (static and dynamic) as I, for long time, wanted to.Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com8tag:blogger.com,1999:blog-8866592669665585195.post-68603901200292518562008-10-01T01:43:00.008+03:002008-10-01T10:25:54.438+03:00Two Days In A Life<div dir="ltr">The ban that Israel's government has put on The Beatles performance in the 60s disappointed not only Israelis, but many Jewish people who were part of The Beatles phenomena, like their legendary manager Brian Epstein. Over four decades later, Paul McCartney represented the Fab Four on stage in Park HaYarkon, Tel Aviv, and rocked the audience with a great show.<br /><br /><div style="display: block; text-align: center; margin-right: auto; margin-left: auto;"><a href="http://paulmccartney.com/scripts/imageFetch.php?src=44a58cca19cda60734cbc5abcdb3e6b9.jpg&w=470&h=264&sizing=crop" imageanchor="1"><img src="http://paulmccartney.com/scripts/imageFetch.php?src=44a58cca19cda60734cbc5abcdb3e6b9.jpg&w=470&h=264&sizing=crop" border="0" height="235" width="420" /></a></div><br /><div style="text-align: left;">Negotiations for the concert have been tough, but after a series of rumors and denials the deal was finally set. Ticket offices were stormed on opening, 50,000 tickets were sold eventually, filling the park with fans and music lovers.<br /><br />Read more in this <a href="http://sites.google.com/site/maccatelaviv/">illustrated account of Paul McCartney's visit to the Holy Land</a>...<br /><br /><br /></div></div>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com0tag:blogger.com,1999:blog-8866592669665585195.post-87397605533116413152008-09-30T23:21:00.006+03:002008-10-01T01:36:16.638+03:00Beware of the subsNo, I don't mean these cute <a href="http://www.beatles.com/core/music/yellowsubmarine/">yellow things beneath the waves</a>. I am going to talk about <a style="font-family: courier new;" href="http://java.sun.com/javase/6/docs/api/java/util/List.html#subList%28int,%20int%29">List#subList</a> and <a style="font-family: courier new;" href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#substring%28int,%20int%29">String#substring</a> methods in Java.<br /><br />Apparently many people are unaware of what exactly these methods do. Unfortunately their ignorance may lead to unpleasant consequences. So getting straight to the point: both methods <span style="font-weight: bold;">do not </span><span style="font-weight: bold;">copy</span> a portion of the original data, instead they create a <span style="font-weight: bold;">view</span>, or, in other words, a proxy to it. The important thing is that the new wrapper object holds a <span style="font-weight: bold;">strong reference to the original object</span>.<br /><br />The Javadoc of <a style="font-family: courier new;" href="http://java.sun.com/javase/6/docs/api/java/util/List.html#subList%28int,%20int%29">subList</a> at least admits that it's a view, as for <a style="font-family: courier new;" href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#substring%28int,%20int%29">substring</a>, the only way to find out is by looking at the source - the method redirects to this constructor:<br /><pre name="code" class="java">//Package private constructor which shares value array for speed.<br />String(int offset, int count, char value[]) {<br /> this.value = value;<br /> this.offset = offset;<br /> this.count = count;<br />}<br /></pre>So what's the problem? Let's look at the following snippet from a real code-base:<br /><pre name="code" class="java">List leaky = ...; //long list of big & hairy objects<br />leaky = leaky.subList(from, to);<br /></pre>Assuming that <span style="font-family:georgia;">leaky</span> wasn't referenced anywhere else in the code, there is no way for the programmer to access the elements that lie beyond the (from,to) range. But these bytes aint going to rehab, no, no, no - as far as JVM is concerned they are still strongly referenced. So if you really mean to extract a portion of a list (or string), and throw the rest away - <span style="font-weight: bold;">copy it manually</span> to a new list (or string). For example:<br /><pre name="code" class="java">List sneaky = ...;<br />sneaky = new ArrayList(sneaky.subList(from, to));<br /></pre>Is there any better way a "sub" could be implemented? Well, maybe the reference to the original data could be kept weak, and only when (if) the original object is enqueued for garbage collection then the data could be copied into the "view". This would require backwards references from "original" object to "views", which would also need to be weak, so... overall this doesn't seem worth the effort, and hence avoiding leaky lists and strings shall remain the responsibility of the programmer.<br /><br />Speaking of subList, another nasty thing about it is that sub-list is not Serializable, nor Cloneable or anything like that, even if the original list was. And speaking of leaky things that are caused by undercover strong references - never forget non-static inner classes that refer to their enclosing instance.<br /><br />Take care, and keep your head above the water :-)Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com1tag:blogger.com,1999:blog-8866592669665585195.post-45566521084453011532008-07-04T23:27:00.016+03:002008-12-07T14:19:45.108+02:00Software: Live and Let DieThis week I was lucky to attend Gilad Bracha's <a href="http://www.cs.huji.ac.il/site/?i=colloquium&lang=en">guest lecture on Networked Serviced Programming</a> at the Hebrew University. He has been <a href="http://video.google.com/videoplay?docid=-5886267052339478036">talking</a> about <a href="http://bracha.org/objectsAsSoftwareServices.pdf">Service Objects</a> for some time now, but nothing compares to hearing it live - Gilad's <a href="http://www.bracha.org/oopsla05-dls-talk.pdf">presentation</a> was witty and fun!<br /><br />So here is my interpretation and some take-aways.<br /><br />What's the problem with software? It is <span style="font-weight: bold;">too damn complex</span>. Projects crumble under their own weight. It happens to successful projects - our dearly loved Java, for example. Also look at Vista, if you dare. And it's certainly true for the monster-size projects I used to work on. Once upon a time our team took the corporate "quality improvement" policy seriously and decided to investigate what causes bugs in our multi-million lines of code project. We collected all sorts of statistics and ran all possible metrics (which was tricky 'cause some of the tools would choke on such a huge code-base) but long story short our finding was this: <b>the only</b> metric that correlated clearly with defectiveness was LoC. It is <a href="http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html">hardly news</a>, but a cure to the disease has yet to be found.<br /><br />There are certainly several things to be done, but what this talk focused on is getting rid of code which shouldn't be there, or in other words - dumping unused code and backwards compatibility. The way we work today - we are bound to not just specs and APIs, but to all the accidental behaviors and bugs in the previous version of our code. It seems that Gilad views code as if it was a live organism. Staying alive means being connected (and network plays a central role in his vision), but we should make way for evolution and some code should die - Gilad calls it "bit rot".<br /><br />So how do we turn software into a healthy living organism? According to Gilad, there are several things to be done on the technical front first.<br /><ul><li><span style="font-weight: bold;">Take advantage of the network</span>: maintain a bi-directional connection with the control center - let programs pull upgrades from the net, but also send back operation statistics. This means that programming platform has to be aware of the network, and aware of the <a href="http://en.wikipedia.org/wiki/Fallacies_of_Distributed_Computing">fallacies of distributed computing</a>. This is cloud computing utopia: Internet as a platform, browser as an OS, and <a href="http://gbracha.blogspot.com/2008/04/everyone-is-talking-about-cloud.html">Javascript as the low-level programming language</a> into which other languages can compile (<span>in a <a href="http://code.google.com/webtoolkit/">GWT</a> kind a way</span>).<br /></li><li><span style="font-weight: bold;">Modularity: </span>it should be possible to extend and replace individual objects without interference to the whole organism. Gilad has a <a href="http://www.bracha.org/jigsaw.ps">well developed theory</a> about how modularity should be done in a programming language, based on principles of object-orientation using <a href="http://www.bracha.org/oopsla90.ps">mix-ins</a>, <a href="http://dyla2007.unibe.ch/?download=dyla07-Gilad.pdf">nested classes</a> and <a href="http://portal.acm.org/citation.cfm?id=141936.141940">inheritance hierarchies</a>; his new language, <a href="http://www.bracha.org/Site/Newspeak.html">Newspeak</a>, is going to implement it. <span style="font-style: italic;"></span></li><li><span style="font-weight: bold;">Explicit Dependencies </span>between modules<span style="font-weight: bold;"> </span>- <a href="http://gbracha.blogspot.com/2008/02/cutting-out-static.html">no static</a>, no imports, modules are truely independent and dependency management (wiring) is performed by passing other module instances as parameters to module constructors. This allows to maintain clear boundaries between modules and flexibility in module composition.<span style="font-style: italic;"></span><br /></li><li><span style="font-weight: bold;">Frequent Updates: </span>to allow the "clients" of the object APIs to deal with changes, in addition to maintaining modularity, the changes should be made small and frequent. Call it agility, if you like. That means that we can't afford reboots, and we need to find out when the system is quiescent so that upgrade can be performed, which brings us to the next point...<br /></li><li><span style="font-weight: bold;">Reflection and Hot-swapping</span>: objects should allow other objects to find out both static and run-time information about them without breaking the encapsulation. Objects should also allow other objects to modify them "live". Gilad and <a href="http://news.squeak.org/2007/01/29/taking-the-beat-of-cadence/">his team at Cadence</a> are building the support for these features in Newspeak using <a href="http://www.bracha.org/mirrors.pdf">Mirrors</a>, a concept that originates in <a href="http://research.sun.com/self/language.html">Self </a>programming language. It's worth noting that there exist dynamically typed languages that implement hot-swapping today - <a href="http://www.erlang.org/">Erlang</a> being one of them. <span style="font-style: italic;"></span><br /></li><li><span style="font-weight: bold;">Security </span>is important in any distributed system, and even more so if we allow remote objects to mess with the program. So in addition to dynamic typing and pointer safety, Gilad proposes mirrors to be guarded by <a href="http://en.wikipedia.org/wiki/Capability-based_security">capability-based security</a>, similar to the one in <a href="http://erights.org/">E</a> programming language.</li><li><span style="font-weight: bold;">Synchronization: </span>many programs need to work with persistent data and it is important to keep the program and the data in-sync. Gilad proposes orthogonal synchronization, based on Smalltalk <a href="http://en.wikipedia.org/wiki/System_Image">orthogonal persistence</a> idea, where objects are split into transient and persistent ones by marking object tree roots accordingly. Persistent objects are upgraded whenever the corresponding part of the program is upgraded, and transient objects are lazily recomputed. If the data is ever to outlive the service, it would be exported into some generic format, such as XML.<br /></li><li>The most extreme and bold part of this vision is probably <span style="font-weight: bold;">No Versions</span> and <span style="font-weight: bold;">No Releases</span> - there would be only one version for every program out there. Gilad sees software becoming more of a service than a product, but in order for this to realize we'll have to overcome not just technological, but also psychological and economical barriers - we will have to change the way we develop software and the way we make money of it.<br /></li></ul>Bottom line, all this may sound too futuristic, but "<a href="http://www.infoq.com/SaaS">software as a service</a>" and "<a href="http://www.salesforce.com/platform/">platform as a service</a>" are making their way in the industry and this wave, if strong and successful enough, may bring the significant change Gilad is predicting.<br /><br /><span style="font-style: italic;">P.S. As for the rest of us, living in the JVM world, some of the ideas ring a bell. We hope that modularity JSRs and OSGi will improve Java. Those of us who survived Ant and Maven, and felt the weight of a DI framework, will probably appreciate the amount attention Gilad is putting into software composition. It's worth noting the attempts to address hot-swapping on JVM, such as </span><a style="font-style: italic;" href="http://www.zeroturnaround.com/javarebel/">JavaRebel</a><span style="font-style: italic;"> and </span><a style="font-style: italic;" href="http://jonasboner.com/2008/06/16/erlang-style-supervisor-module-for-scala-actors/">Jonas Boner's experiments with Scala Actors and Terracotta</a><span style="font-style: italic;">. </span><a style="font-style: italic;" href="http://www.aosd.net/2007/program/industry/I1-ClusteringJVMUsingAOP.pdf">Terracotta server</a><span style="font-style: italic;"> also utilizes some ideas which (in my mind at least) look quite similar to the orthogonal synchronization scheme. </span>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com1tag:blogger.com,1999:blog-8866592669665585195.post-63126877977160919782008-06-25T15:25:00.002+03:002008-12-09T08:45:27.069+02:00JunkedInIndeed <a href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-5234&yr=2008&track=">LinkedIn runs on Java</a>, no doubt about it:<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhw6nwdziYJlt9JjTXnzzP8uaHSUZ7p88tZP6Qvx44HwKo_8ZVVGqh34Lj6tyCMMNjEqvgRujwFhHqpOetR2m7NXQTMlmuhOsObPOIlfXme8ac2jz80rHoeVBaO-_1fJdKqdMKXtkhTeg0/s1600-h/JunkedIn.JPG"><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhw6nwdziYJlt9JjTXnzzP8uaHSUZ7p88tZP6Qvx44HwKo_8ZVVGqh34Lj6tyCMMNjEqvgRujwFhHqpOetR2m7NXQTMlmuhOsObPOIlfXme8ac2jz80rHoeVBaO-_1fJdKqdMKXtkhTeg0/s320/JunkedIn.JPG" alt="" id="BLOGGER_PHOTO_ID_5215794790532013170" border="0" /></a>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com3tag:blogger.com,1999:blog-8866592669665585195.post-4748580550854220672008-06-17T14:37:00.004+03:002008-12-09T08:45:27.254+02:00Noble cause<a href="http://jduchess.org/">Duchess</a> is an on-line community of female Java developers with members from all over the world, but currently active mainly in the Netherlands. I figured they could use some promotion, besides it's a perfect excuse to put this cute mascot on my blog:<br /><br /> <a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://jduchess.org/"><img style="cursor: pointer;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgiOYL6szzYvTAOROrWC2pjUgxjCTEsePHEE7ru-yOgR2uP9JFV88hizEFkXb0X19V7oRNqADr5zysYPTAXN2AOn4pdJOHZ7qHlaYy-8xNQ71HY_snjcQCdqxK5zGvuNQGkc3ooDKYm3o4/s320/javaduchess.png" alt="" id="BLOGGER_PHOTO_ID_5212818512682212178" border="0" /></a>Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com1tag:blogger.com,1999:blog-8866592669665585195.post-759740136565218102008-06-05T23:30:00.007+03:002008-12-09T08:45:27.841+02:00Typesy Turvy<a href="http://lambda-the-ultimate.org/">Lambda The Ultimate</a> feed just notified me that <a href="http://lambda-the-ultimate.org/node/2828">types are considered harmful</a>. Ah yes, I heard this before, so what's the news? The news is that it's not <a href="http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html">Stevey</a> vs. <a href="http://beust.com/weblog/archives/000483.html">Cedric</a> or anything like that, this is <a href="http://www.cis.upenn.edu/%7Ebcpierce/">Benjamin C. Pierce</a> in his own write. Benjamin C. Pierce, from "<a href="http://books.google.com/books?id=ti6zoAC9Ph8C">Types and Programming Languages</a>" and "<a href="http://books.google.com/books?id=A5ic1MPTvVsC">Advanced Types and Programming Languages</a>", King of ML, Lord of the Functional Programming Commonwealth, Defender of Type Systems Faith!<br /><br />Nice <a href="http://www.cis.upenn.edu/%7Ebcpierce/papers/harmful-mfps.pdf">presentation</a>, BTW. I think it's one of these situations when a big shot computer scientist is confronted with a real life problem. So you say the language is perfect for writing a compiler - good for you. How about a database application with a web front-end?<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.hazelcast.com/brave-developer.jpg"><img style="cursor: pointer;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3ZZZtOloHPqz3EdpyutSTpXCNvQYvvSbHks8kwx7RTWOy7wshvqT8bhnJ-aFBAhwnnkUClwqUHaUMoRVscxsdPg4dt3guHM8DujH1S6oCImRUW3rcnbJl5j2a2tIaNUAADslHq1Hqeq4/s320/brave-developer.jpg" alt="" id="BLOGGER_PHOTO_ID_5208505492541000722" border="0" /></a><br />(<a href="http://www.hazelcast.com/brave-developer.jpg">click to see full-size</a>)<br /><br />Mr. Language Designer, where are you in this picture? Yes you, who designed the mousetrap which "the bug" has safely escaped from. Now it is here, so are you at least by the developer side, handing him something heavy to throw at "the bug", or are you on the bed with the rest of the crowd going "ah ah ah, what do they teach computer science graduates these days..."?<br /><br />One thing that impressed me during otherwise boring (let me just read you aloud the tutorial) JRuby on Rails preso I <a href="http://il.sun.com/sunnews/events/2008/javaday/agenda.jsp">recently attended</a> - here is a system that tries to serve the needs of the developer. Not server vendor, not language designer, not JSR politician, not some brandthirsty marketing person or buzz-oriented architect, THE DEVELOPER. I am not used to that. So all I have to say - programmers of the world, unite! Stand for your rights! We deserve better tools, because we are the ones getting the job done.<br /><br />Thank you for reading.Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com1tag:blogger.com,1999:blog-8866592669665585195.post-87105824277180940902008-05-15T19:17:00.004+03:002008-05-15T21:58:44.226+03:00In whining there is truth?What do Java developers want? Hard to say. But here is what Java bloggers <span style="font-weight: bold;">don't</span> want Sun to do:<br />No evolving Java syntax - no properties, no closures, etc. - fix what is already there first.<br />No extending Java capabilities via annotations.<br />No investing in a new JVM language (JavaFX, or JRuby in the past)<br />Ok, maybe add Groovy, but don't change JVM spec.<br />Hey, wait, why are key people leaving Sun? We didn't want that either!Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com5tag:blogger.com,1999:blog-8866592669665585195.post-43728820890578000862008-05-13T15:20:00.016+03:002008-12-09T11:56:05.713+02:00Girl PowerI have been reading recently that women are abandoning computer science, and that percentage of women in our profession is not just low, but getting lower. I'm not sure actually that the situation here is as bad as in North America, but it's certainly true that software engineering and computer science are not very popular among women. Why? To be honest, I don't have the answer.<br /><br />Here is what comes to mind:<br /><ul><li>Geek-ness is viewed in the society as the opposite of being attractive; this is much more important for young women, than for men. For a guy - a nice high-tech salary will provide the attraction instead.<br /></li><li>Sitting in a cube by the computer all day and doing one thing, coding, is probably not very attractive for most people, but for women especially, since most of us are better at performing a variety of tasks and interacting with people - I mean there has to be an explanation why "secretary" or "teacher" are such typical women professions.</li><li>Hi-tech jobs are very demanding, too demanding. For most women family life is at least as important as professional life, and usually family comes first. But there just aren't many positions you can find after getting computer science degree that allow you easily balance work and family life.<br /></li><li>Hi-tech is for young people - look around, how many programmers you know are over 45? Why? For the same reason you don't see many women - it's hard to compete with the smart kids when you are pregnant, or haven't slept for a week, or worried about some family matter.</li><li>But can't we just switch roles with the husband? well, go back to first bullet, double standards of the society certainly don't make it easier on us or our partners.<br /></li><li>People we are surrounded with (nerdy young men mostly) are pretty anti-social creatures in the first place, even more so with species of the other sex, even more so with the ones that don't fit social stereotype.<br /></li><li>Now suppose you survived all the obstacles, because you passionately love science and engineering. Did you watch <a href="http://www.youtube.com/watch?v=CmYDgncMhXw">the knack</a>? There's a grain of truth there... society became less tolerant of weirdness, and people who 100 years ago may have been referred to as crazy geniuses nowadays live "normal life" on prescribed medications. And for a girl it's even stranger to be a crazy genius then for a boy.</li><li>Male domination in the field - yes, it's chicken and egg problem. The field will change only if there will be enough women in it to drive the change from within and help other women. So I will devote the rest of the post to the ones who made it.</li></ul><span style="font-weight: bold;">Lady Ada (Byron) Lovelace<br /><br /></span><div style="text-align: left;"><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://en.wikipedia.org/wiki/Ada_Lovelace"><img style="margin: 0px auto 10px; text-align: center; cursor: pointer;" src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Ada_Lovelace_1838.jpg/225px-Ada_Lovelace_1838.jpg" alt="" border="0" /></a><br />She was more of a technical writer really, but she was a visionary.<br /></div><br /><span style="font-weight: bold;">Admiral Grace Hopper<br /><br /></span><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://en.wikipedia.org/wiki/Grace_Hopper"><img style="margin: 0px auto 10px; text-align: center; cursor: pointer;" src="http://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Grace_Hopper.jpg/200px-Grace_Hopper.jpg" alt="" border="0" /></a><br />The inventor of COBOL and debugging.<br /><br /><span style="font-weight: bold;">Professor Barbara Liskov<br /><br /></span><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://en.wikipedia.org/wiki/Barbara_Liskov"><img style="margin: 0pt 10px 10px 0pt; text-align: center; cursor: pointer; width: 160px;" src="http://www.pmg.lcs.mit.edu/~liskov/images/LISKOV_crop2.jpg" alt="" border="0" /></a><br />The one from the substitution principle. I chose her among several prominent computer scientist women because she was the <span style="font-weight: bold;">first </span>female computer science Ph.D in the US.<br /><br /><span style="font-weight: bold;">SVP Jayshree Ullal<br /><br /></span><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.networkworld.com/power/2005/122605-ullal.html"><img style="cursor: pointer;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxc8wia2xmjlIFpJ_ZhrGt2R9gWbJ1_UZkgniurTQ7IHBHU5FS7oRaTCvmP9XXg4qtKA6le5ipf-6Mt7DqloOapNp8mTx9TdXn6I5MLzVplHhFxVMh3oDpcaA7cckrhvpThwFV-AWzjyo/s320/ullal-jayshree.jpg" alt="" id="BLOGGER_PHOTO_ID_5205531387607265234" border="0" /></a><br />I originally thought to put the <a href="http://www.sanfranmag.com/story/adventures-marissa">Google princess</a> here, but having personally met Jayshree (she was my manager's manager's manager at one point) and impressed by her personality and professionalism (she is so clever, and yet such nice and humble person), I decided she's a better candidate to represent successful women in computer industry.<br /><br /><span style="font-weight: bold;">Alice, </span><span style="font-weight: bold;">Dilbert's </span><span style="font-weight: bold;">workaholic colleague</span><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://www.hpcnet.org/sdsmt/SiteID=199997"><img style="cursor: pointer;" src="http://www.hpcnet.org/upload/providers/168823_001127140329.jpg" alt="" border="0" /></a><br />What did she achieve exactly? Surviving in the office should not be underestimated! So I am going to honor another ex-colleague, although we never met, for providing inspiration for a character I can identify with :-)<br /><br />Keep coding girls!Yardenahttp://www.blogger.com/profile/15649241856669571499noreply@blogger.com6