Ed's Big Plans

Computing for Science and Awesome

Borrowing Ruby ideas: Returning an object instance

with 3 comments

Brief: Ruby conventions were designed to be particularly satisfying and intuitive for the developer. One convention that Ruby adds to the object oriented world is for mutators (setters) to return the object instance — that is, calling an object’s mutators will not only alter the object, but will also return the object (not the mutated property). This is especially useful if you want to chain a bunch of mutators together for code legibility or developer convenience.

This would be a welcome shorthand for developers of C-derived object oriented languages such as Java and C#. The following chain…


…would become…


…a much more compact and what I feel is a more intuitive chain.

Eddie Ma

June 27th, 2010 at 3:00 am

Andre Masella says...

This is actually a SmallTalk convention. In SmallTalk, there isn’t a void return-type, so you always “return this;”

Eddie Ma says...

Interesting. You know, one can really tell that you’ve been programming longer than me 😀

Andre Masella says...

I started in grade 5. Although, I’ve never actually written a line of SmallTalk. What’s weird about Java is that some objects follow this conventions, like StringBuilder, but not all. Either syntax is kind of non-intuitive though. For property setters, something like:
a.{mass = 17; name = “cube”; face = null};
makes sense because writing “set” adds no value and we don’t really seem to care about the order. In fact, we are thinking of this kind of as a transaction.

Moreover, a.setMass(17).render(g).setName(“cube”).setFace(null).render(g); is probably a bad idea since we are mixing state changing methods and methods that are not changing the state of the object. It would be nice to insist that the returned value is the one that is returned…at least by the convention no one will follow.