Dart for Java Developers: The Model class

In my previous post, Dart for Java Developers: Into the code, we looked at two Dart source files, converter.dart and main.dart. Both contained so-called top level functions, that is, making code available without the need to put it in a class. Recall that each Dart file is a library. A library with a top level main() function is a script. Libraries are combined or grouped to form so-called packages. Packages can be easily distributed and reused. The Dart SDK comes with a package and asset manager called pub. Packages are described in a specification file named pubspec.yaml. It consists of, among other entries, a name, a version and a list of dependencies. For example, Temperature Converter relies on the internationalization package intl. A package can live anywhere. Some packages are on GitHub. Others reside at pub.dartlang.org. You can publish your packages there, too. Here is a description what you need to do: https://www.dartlang.org/tools/pub/publishing. The pub tool is invoked either through the plugin of your IDE (if you open a pubspec in IntelliJ you get a commands list at the top of the editor window), or from the console. If you fancy the shell, remember to include /bin in your PATH environment variable.

Now, let's turn to code. Recall that my original Temperature Converter app was written in Java using JavaFX. There is a Model class that uses Converter. So, Model has both state and behavior. The class is used as follows:

  1. Instantiate it
  2. Set the domain data (unit of input and output temperature and the temperature itself)
  3. Perform the calculation
  4. Grab the output string
  5. Back to 2.

Let's see how this looks like in Dart. We start with a library statement (which gives the library a name), followed by an import. We rely on the converter library you have encountered in the previous post. After that you see an enum definition. Compared to, for example Java, Dart enums allow less customization. Currently the string representation of the enum evaluates to enum_name.enum_value. To be able to more easily map user interface elements to enum values (you will see that later) I implemented a convenience method named enumFor(). Dart enums cannot be defined inside classes. Now let's take a look at the Model class (it's inside model.dart). Besides the lack of access level modifiers (more on that soon) the code looks comfortingly familiar. With two very welcomed exceptions. Have you spotted the get and set keywords? Dart has language level support for getters and setters.

In the next installment we will actually use the new Model class. But if you cannot wait to try it out, just grab the code from GitHub and start playing.

No comments:

Post a Comment