Always Return Something Useful

From Zanecorpwiki

Jump to: navigation, search

AFAIK, in any modern object-oriented (OO) language, unused returns will be optimized out or otherwise have no real effect on code execution. That being the case, you should never use the return.

In OO languages, the object itself is often a useful return, so if there's nothing else to return, return the object. Doing so allows developers to write more compact code. Consider this example from GWT:

Label title = new Label("Title");
label.addStyleName("title");
panel.add(title);
HTML content = new HTML("some content");
content.addStyleName("This sounds good.");
panel.add(content);

We have to do this because the 'addStyleName(...)' method returns void. If we instead returned the object itself, we could rewrite those six lines in a much more compact and still very digestible two lines:

panel.add(new Label("Title").addStyleName("title"));
panel.add(new HTML("This sounds good.").addStyleName("content");
Personal tools