Monday, May 12, 2008

Get smart with properties in Scala

Properties are easy to declare in Scala

class ShoePhone
    var vibrateOn = false
    var volume = 8

What does this really mean?

Here is the same code, written in a more cluttered way, illustrating the setters and getters which are automatically generated above
class ShoePhone
    private[this] var _vibrateOn: Boolean = false;
    private[this] var _volume: Int = 8;

    def vibrateOn: Boolean = _vibrateOn;
    def volume: Int = _volume;

    def vibrateOn_=(on: Boolean)
        _vibrateOn = on;

    def volume_=(vol: Int)
        _volume = vol;
Here the private fields are given names with an added underscore prefix. These names could be anything. This is just a convention I'd like to see. I don't like seeing a lot of one-off names (such as the ones I used for the setter method parameters, on and vol). If there is a simple way to eliminate the one-off names akin to what one finds in the Java idiom
please let me know.

The getter methods are defined without parentheses so they appear in code just as if they were fields. See previous post on the Uniform Access principle.

The setter methods are defined by adding
This suffix creates the method used when a variable is assigned using
Say we have a ShoePhone instance shoePhone and set its volume
shoePhone.volume = 0
You could write to the same effect

For an explanation of the access modifier private[this] see The Scala cone of silence.

Now playing: Yeasayer - 2080
via FoxyTunes

Version 1.1 (correction)

Update (May 22, 2008): Using the Java Class File disassembler javap on the ShoePhone class file, you can see what Scala does behind the scenes in the Java bytecode
javap -private ShoePhone

Compiled from "ShoePhone.scala"
public class extends java.lang.Object implements scala.ScalaObject{
    private int volume;
    private boolean vibrateOn;
    public void volume_$eq(int);
    public int volume();
    public void vibrateOn_$eq(boolean);
    public boolean vibrateOn();
    public int $tag();
There are private fields and public getter methods which use the same name. The setter method adds the suffix  _=  cryptically rewritten as  _$eq  to comply with Java naming rules.

If your setter method needs to do something special, you can always define it explicitly
class ShoePhone
    var _vibrateOn = false

    private[this] var _volume = 8

    def volume = _volume

    def volume_=(__volume: Int)
        _volume = __volume;
where I've used an underscore prefix to distinguish the private variable from the public getter method, again to avoid one-off names. I've used two underscores for the explicit setter method parameter. The use of underscores at the beginning of names is discouraged in Java. If anyone knows a better, less discouraged, more aesthetic way to do this, please let me know.

Update (May 23, 2008): If you need your ShoePhone available as a JavaBean, it's easy. Just use the annotation @scala.reflect.BeanProperty.
class ShoePhone
    var vibrateOn = false

    var volume = 8
The setters and getters will then be generated automatically for you by the Scala compiler.
javap ShoePhone

Compiled from "ShoePhone.scala"
public class extends java.lang.Object implements scala.ScalaObject{
    public void setVolume(int);
    public int getVolume();
    public void setVibrateOn(boolean);
    public boolean isVibrateOn();
    public void volume_$eq(int);
    public int volume();
    public void vibrateOn_$eq(boolean);
    public boolean vibrateOn();
    public int $tag();

Friday, May 09, 2008

The Scala cone of silence

I've been waiting so long for this. Now with Scala you can restrict access to your classes by package name, allowing only a package and its nested packages access. Say you had the packages,

Then the access modifier private[agent] would limit access to the last two packages only.

You can also define members as object-private with the access modifier private[this]. This restricts access to the specific instance. In Java, other instances of the same class can access private fields. Did you realize that?

What a wonderful cone of silence!

Wednesday, April 02, 2008

Gaga over Scala

Scala, scala, scala....

I'll try to comment more once I collect myself, if I ever do.

Scala blends functional and object-oriented programming into one language, which runs on a JVM, interoperably with Java. Why functional programming (FP)? What's functional programming? Here's an interesting summary - Functional Programming for the Rest of Us.

Update (Apr 9, 2008, 10:40 am Central):
Here's an excellent audio overview by one of the authors of the book Programming in Scala (whom I had the privilege of mountain biking with in August 2001 at Crested Butte, Colorado, while attending a week-long seminar on Design Patterns he and Bruce Eckel taught) This introduction, which I just listened to, includes most all the key points I mentioned to a friend of mine in an enthusiastic conversation yesterday evening. Venners captures much of the unrest in the Java community that I have sensed over the past several years. He captures well my own hesitation to jump into Ruby, Python, and Groovy as solutions to this angst and my immediate determination that Scala is it, the language we've been waiting for - Bill Venners on the rise of Scala

Update (Apr 28, 2008, 2:10 pm Central): I've read Programming in Scala cover-to-cover, and I'm still gaga.

My guess is that Scala is "it", the language that will supercede Java, more speedily if it markets itself like Spring, by putting forward the Actor library as the entry point and not forcing people to adopt everything all at once, given its interoperability with Java.

X10 is also interesting. Might Scala adopt x10's notion of a clock? Perhaps there'll be some sort of interoperability between X10 and Scala, or even a hybrid. I imagine Lex Spoon has some things to say on this matter, having been involved with both projects. Indeed, I see from Spoon's CV that he "assisted with the ongoing design of X10, a language for high-performance computing, both in its pure form and with a Scala-like front-end."

I have questions about Scala's classloading and security. Do they differ from Java's?

Update (May 9, 2008, 1:50 pm Central): Odersky, Spoon, and Venners published a new version of their Pre-Print edition this last Sunday, May 4. And what do you know? They added a new section on clocks in chapter 30 "Actors and Concurrency". I'd like to think one of the comments I had submitted to them online sparked this addition, but I don't know. I read it yesterday. It's great.

Update (May 9, 2008, 5:52 pm Central): Here's one small example of some code in Scala that speaks to its power. It's based on an example from the book.

val name = "Agent 99"
val nameHasDigit = name.exists(_.isDigit)

Here the String type is implicit in the first line, but it could be spelled out explicitly, along with a semi-colon at the end of the line
val name: String = "Agent 99";

In the second line, the method exists applies a boolean function to a sequence of objects, returning true if at least one of the results is true. Since name is a string not a sequence, it's implicitly converted to a sequence of characters. The function is described by a function literal, but it could have been defined using the symbol f with some code like this
def f(ch: Char): Boolean = ch.isDigit();
val nameHasDigit: Boolean = name.exists(f);
or alternatively
def f(ch: Char) = ch.isDigit
val nameHasDigit = name.exists(f)
Notice how clean the code becomes, how much more readable it is, when obvious things can be removed.

Details, details, details...

A function literal, by the way, is also known as a predicate when it returns a Boolean, as _.isDigit does above.

One detail. If you already know Scala, can you find the error in my expanded pedagogic code for defining the function f?

In Scala, there is a coding convention for differentiating between commands and queries (see Bertrand Meyer's writing on the Command-Query Separation principle). Queries return information without causing "side-effects". Commands change objects. The convention in Scala is to only include empty parentheses when the method has side-effects. When it returns information without changing things, returning say a conceptual property of an object, then it's a query, and, again in the spirit of Bertrand Meyer's writing, in this case on the Uniform Access principle, the parentheses are removed. That's the Scala convention.

If the code defining the method specifically omits parentheses however, then this isn't optional. It's enforced, as in the case of isDigit. You'll see a compile-time error if you try to call the method with empty parentheses.

I also didn't mention that scala.Char is implicitly converted to scala.runtime.RichChar, behind the scenes. Implicit conversion makes for more intuitive, succinct code. It also allows you to wrap code from pre-existing libraries using traits. Traits are akin to Java interfaces, however they can include concrete implementations, and so they're mixins.

Another detail - the implicit conversion for exists actually requires an Iterable. A sequence is, more precisely, a Seq, a subtrait of Iterable. The conversion is made from String to a RandomAccessSeq, a subtrait of Seq, by one of the implicit conversion functions in a singleton object called Predef, where many such common conversions are defined.

In Scala, by the way, in addition to defining a class, you can define an object, which is just a singleton. You can define a class and an object using the same name, in which case the object is the companion object to the class. So every Scala class can have an associated singleton object.

Update (May 13, 2008, 8:15 pm Central):
I noticed an announcement for the first meeting of a new Scala User Group for the San Francisco Bay Area. It's scheduled to meet at this very moment. Wish I were there. Maybe their next meeting, or the meeting after that....

Here in Minneapolis, I hope to meet other Scala users at the OTUG meeting next week, where Ted Neward is making a presentation - The Busy Developer's Guide to Scala
The Java platform has historically been the province of object-oriented programming, but even Java language stalwarts are starting to pay attention to the latest old-is-new trend in application development: functional programming. In this lecture, Ted Neward introduces Scala, a programming language that combines functional and object-oriented techniques for the JVM. Along the way, Ted makes the case for why you should take the time to learn Scala — concurrency, for one — and shows you how quickly it will pay off.
So far I only know one other programmer in the Twin Cities who's interested in Scala, and I had a coffee klutch with him yesterday evening on the subject. It'd be great to get a Scala User Group going here, starting with some of the attendees of Neward's talk.

Tuesday, November 20, 2007

The ground is shaking beneath Java

The ground is shaking beneath Java on two ends. On one end is Android, on the other X10.

As previously discussed, I'm attracted to the Harmony implementation of Java because of its Apache licensing. Android fits into this strategy nicely as it incorporates much of Harmony. Openness wins. Distributed computing and onerous licensing are inimical. Android has been released under the Apache v.2 license.

As the world moves towards multi-core, IBM's experimental concurrent programming language X10, an offshoot of Java (shy generics for now[1]), is poised for action. According to Vijay Saraswat's Report on the Experimental Language X10, Version 1.1, June 30, 2007,

X10 may be thought of as (generic) Java less concurrency, arrays and built-in types, plus places, activities, clocks, (distributed, multi-dimensional) arrays and value types. All these changes are motivated by the desire to use the new language for high-end, high-performance, high-productivity computing.
X10 is licensed under the Eclipse Public License 1.0.

Licensing, that's a go.[2] Java-based security. Shall we assume that's a go?[3] Now it's time to delve in.

I'm sure Java will come out of all this tumult strengthened, though perhaps reincarnated.


I hope both of these movers and shakers do come up with better names. Android?? It's a bit embarrassing to put on your resume, like Groovy. And the name X10 makes it difficult to do Google searches due to the ubiquitous information about that other X10.

  1. Generics, that revolution with which Java shook itself, is expected anytime soon in X10's next release. Android includes generics.
  2. Maybe not. See the 4th bullet in the update and errata section at the end of Dalvik: how Google routed around Sun's IP-based licensing restrictions on Java ME.
  3. Maybe not completely with Android, but perhaps enough for working with distributed code.

Update (Nov 26, 2007): Interesting post on Android, OSGi, and classloading - OSGi on Google Android using Apache Felix

Thursday, August 23, 2007

Java and the dangers of GPL

Don't get me wrong. I am a GPL fan in spirit when it's combined with a linking exception. Initially I applauded Sun's choice for Java's open-source license. I am also grateful for the monumental efforts of Richard Stallman and Eben Moglen in helping move the world of software forward. However, GPL version 3, released two months ago, suffers from 2 flaws, fatal flaws, fatal not only to the healthy evolution of GPL but also to that of Java.

Flaw #1 - The anti-tivoization clause for consumer hardware is a limitation inimical to free software. I agree with Linus Torvalds that this clause is a critical mistake. I may write about this in more detail later, but for now, consider only how this stunts development of security for distributed applications. My objection is not merely practical. My objection is in principle. Freedom in bits, freedom in property, no control over how I use bits in my own property or how others use them in theirs, that's where this world is heading. Dictating what I can or can't do with the software in certain hardware smells of controlliness (yes, that's a word I just made up, but I bet you know what I mean), inimical to the type of flexibility we need to move this world ahead... fast.

Flaw #2 - Here's the clincher, a flaw that even shows a high degree of, dare I say, hypocrisy (Torvalds dared). The license itself is not open to changes. You will be punished if you use a license with flaw #1 corrected. Richard Stallman and Eben Moglen will not let you fork it. I was shocked to find this out. No free-software heretics welcome. You're locked in for the ride no matter how arbitrary the car driver. This is the GPL trap. (See the video below.)

What to do? Sun currently licenses Java under GPLv2 with the linking exception. I do hope that Sun adds another open-source license for Java and does not merely move to GPLv3 unthinkingly. I also hope that the Creative Commons adds another open-source software license to its repertoire. In the meantime, I'll continue to use Java as is, but I'll be keeping my eye on Apache Harmony, though it's currently lacking a Mac version. In the grid world to come, the freedom to securely ensure that software be accountable is essential, no matter where it runs.

I find it sad since I find exciting value in the GPLv3 apart from these 2 dissuasive defects.

Here is an excellent, informative presentation on GPLv3 given by Sapna Kumar in June to the Triangle Linux Users Group. According to Kumar (1:13:03), Stallman will not let you modify the GPL license on your own even if you call it by another name. The Free Software Foundation enforces this through copyright.

Monday, January 15, 2007

Newton Discovery

I've discovered Newton, and now Newton's downloading on my Apple.

Newton uses OSGi for local components and Jini for remote components, combining them both into a distributed component framework, with some SCA thrown in for good measure to describe how to assemble the components all together.

A good starting point to learn about Newton is The Newton Component Model.

Newton is available under a GPL or commercial license.

Here's a presentation on Newton from the 10th Jini Community Meeting last year.

Hat tip: Fun with OSGi

See also: OSGi in a dynamic service grid

Sunday, December 03, 2006

French Roast

Well, I've ordered my first French book on Java, Spring par la Pratique.

In his preface to the book, Rod Johnson, the founder of Spring, writes,

The content is not only up to date, but broad in scope and highly readable. Enterprise Java is a dynamic area, and open source projects are particularly rapidly moving targets. Spring has progressed especially rapidly in the last six months, with work leading up to the final release of Spring 2.0. The authors of this book have done a remarkable job of writing about Spring 2.0 features as soon as they have stabilized.

According to one Amazon review, "un must have !" The reviewer, Levy, writes,
Excellent ouvrage, clair, précis, pédagogique et très complet.
Non seulement ce livre expose de manière simple les principaux concepts de Spring (conteneur léger, IOC, AOP, Spring MVC, Acegi security...) mais il aborde également, avec des exemples précis de mise en oeuvre, des thèmes plus rarement abordés dans les autres ouvrages : support d'AJAX et DWR, d'XML et des web services, de JMS, JCA et JMX.
A possèder absolument dans sa bibliothèque si on ne veut pas passer à côté de la révolution technologique qui s'opère autour des architectures J2EE.

Here's my translation of Levy's review,
Excellent work, clear, precise, instructive, and very complete. Not only does this book explain simply the principle concepts of Spring (lightweight containers, IOC, AOP, Spring MVC, Acegi security...), but it also tackles, with specific implementation examples, some topics rarely addressed in other works: AJAX and DWR support, support for XML and web services, and support for JMS, JCA, and JMX.

Definitely a book to have in your library if you don't want to be passed by in the technological revolution sweeping the world of J2EE architectures.