Friday, February 22, 2013

Five Favorite Software Development Analogies

I find myself using analogies (or the closely related similes and metaphors) to illustrate points I am trying to make in various facets of software development, especially when talking with someone new to or less familiar with software development. These tend to be specific analogies rather than general software development analogies discussed in posts such as Software Development Analogies, Software Development Analogies, Using Analogies in Software Development, Tending Your Software Garden, and Writing Software is Like ... Writing. The just-listed posts cover analogies that are intended to describe the overall software development process. The analogies I look at in this post tend to describe narrower and specific portions of software development rather than describing the overall effort. As such, these analogies can even be useful to experienced developers.

Strong Coupling and Dependencies and the Slice of Pizza

When trying to explain how undesirable coupling can lead to dependencies that are difficult to break, I like to use the image of trying to take a slice of pizza and having the desired slice drag the cheese and other toppings of surrounding slices with it. The more tightly coupled the interdependent pieces of the code, the more difficult it is to extract a single slice of pizza (a method, or class, or other code construct) from the greater pizza (greater code module) without dragging parts of the greater along with it.

Brittle Software and the Game of Jenga

The game Jenga involves removing wood blocks from a structure and placing the removed blocks higher up on the structure until someone's misstep (either on removing a block or on placing it precariously on top of the destabilizing structure) leads to it crashing down. This to me is the perfect analogy for brittle software. I use the term "brittle software" in this context to mean software that developers are loathe to change for fear of breaking it or making it worse. This might be software that has thought-to-be-dead code that no one dares remove or code that desperately needs refactoring but involves too much risk to be refactored.

Although a good set of unit tests and regression tests can help reduce risk and fear of changing such code, it is always nice to see clean, understandable, maintainable code that developers dare change with confidence. The interesting thing is that many software projects seem to go through the Jenga game lifecycle. Changes are easy at first in both cases but become increasingly difficult and risky as the game or project goes on and the structure (Jenga tower or project code base) becomes unwieldy.

Concurrent or Not: Nine Women Making a Baby in One Month

Fred Brooks wrote in The Mythical Man-Month the well-known quotation that "The bearing of a child takes nine months, no matter how many women are assigned." I like this analogy for describing the same situation that Brooks uses it for: to point out that not everything can be done concurrently (in code or in assignments) and that some things must be done sequentially. However, I also like the analogy as a way to explain the basics of concurrency versus no concurrency.

Ignoring Warnings: Sweeping Dirt Under the Rug or Hiding Junk in the Closet

I like the analogies of sweeping dirt under the rug or hiding junk in the closet to explain why it's not a good idea to suppress warnings rather than fixing underlying code and why it's similarly not a good idea to ignore compiler warnings or IDE hints/inspections. Although sweeping dirt under the rug or stashing a pile of junk in the closet may make things appear superficially cleaner, the dirt and junk are still there and are still going to cause an eventual problem. Hiding them doesn't fix the real issue and is only a temporary workaround.

Comments are Deodorant for Stinky Code

I first heard the quote "Comments are deodorant for stinky code" (or "code smells") in Kevlin Henney's presentation Programmer's Dozen: Thirteen Recommendations for Refactoring, Repairing, and Regaining Control of Your Code at SDWest 2005 and have liked the metaphor ever since. I do think some comments have value (such as Javadoc methods describing pre-conditions and post-conditions and other contract details), but in-method comments often do seem to be extraneous or redundant at best, downright misleading or out-of-date in other cases, or must exist because the code they describe is inscrutable without them. It is this last type of comment (the type of comments needed to make confusing or nearly impossible-to-read code understandable) for which this metaphor works best.

Conclusion

I have used this post to describe five of my favorite analogies for explaining particular aspects of software development: too high couple illustrated by pizza slice taking the rest of the pizza with it, Jenga game representing brittle software, nine women having a baby in a month representing ability or inability to run certain tasks concurrently, sweeping dirt under the rug or hiding junk in the closet representing ignoring of warnings and hints, and comments (sometimes) being used as the deodorant for stinky code (code smells).

Thursday, February 14, 2013

Miscellaneous Musings about RMOUG Training Days 2013

I was only able to attend a portion of Rocky Mountain Oracle Users Group (RMOUG) Training Days 2013, but this was my 13th year to attend all or part of this conference (and my 11th year presenting). I have always enjoyed meeting and talking to the people who attend even as my interests have diverged somewhat from the database-focus that formerly aligned so well for me with the conference. As I have posted on before, this year's conference had a lot of focus on mobile application development in addition to the normal breadth and depth of database-oriented topics. In this post, I look at some of the excellent questions (and my responses) I was asked at my presentation on JavaFX and Groovy and look at some other things I learned while attending.

JavaFX and Groovy

I started my session at 2:45 pm with about 10 people in attendance, but the audience reached about 25 people in size by the end. It was another good RMOUG Training Days audience with good questions that made me think they were understanding what I was trying to convey. I'll address some of those questions with my responses now.

One audience member asked how it worked in the JavaFX example that the overridden start method was never called from the static main function of the application. I explained that the same application class extends javafx.application.Application and, thanks to that inheritance, the start(Stage) method is invoked automatically as part of the JavaFX application lifecycle. That start(Stage) method is declared abstract in Application so concrete child implementations must inherit it. Only a call to one of the Application.launch methods was seen in my example, but the start(Stage) method overridden in the child class gets called via polymorphism during the application's execution.

Another question asked in my presentation had to deal with Oracle's use of JavaFX in their own tooling options such as JDeveloper, Oracle ADF, and the like. I obviously do not know the extent of this, but I was happy to speculate that Oracle would like to use JavaFX in more internal tools to leverage their investment in it. One attendee wondered if some of the Oracle ADF-based mobile applications shown in other sessions of this conference used JavaFX underneath. I don't know enough about that to confirm that.

Although I did not demonstrate it in my presentation, I did mention the availability of SceneBuilder. I also mentioned that while other IDEs such as JDeveloper can support JavaFX, NetBeans appears to be the current leader in JavaFX support.

One or two questions surrounded JavaFX's place in the competitive landscape. I attempted to contrast it with Flex, Silverlight, HTML5, Swing, other languages' graphics libraries, and other native mobile development platforms. In some ways, the determination of what JavaFX is competing against is based on how one wants to use it. In desktop applications, the most common "competitors" are pure Swing (without JavaFX), pure SWT (without JavaFX), Adobe AIR, and other languages' graphical libraries. In web application, obvious "competitors" are HTML5/jQuery and Flex. On mobile applications, obvious competitors include the web stack as well as native languages such as Objective-C for the iOS devices. It could be argued that it's a good thing that JavaFX has or soon will have so many different platforms to compete on, giving JavaFX developers flexibility to apply their skills easily to multiple platforms.

I talked about GroovyFX's support for concurrency as provided in the javafx.concurrent package and I referenced the Concurrency in JavaFX article. An audience member asked about Groovy's support for concurrency. I responded to this by briefly discussing gpars and explaining that gpars (Groovy Parallel Systems) is now bundled with Groovy (since Groovy 1.8).

Additional questions were asked that were, I thought, insightful, but I am not talented enough to write them down and respond to them at the same time and have now temporarily forgotten some of the others.

Before leaving coverage of my own presentation, I want to include two slides that I showed in the presentation and in a "slide show" that I had running while waiting for the start time to arrive. These slides summarize some key moments in the history of JavaFX and history of Groovy.

Thinking back upon the history of JavaFX and Groovy, it is easy to see some similarities between the two. Both started with significant enthusiasm that then seemed to wane for a while before resurgent interest and coming back stronger than ever. It seems to me that SpringSource has been a pivotal player in providing stability to Groovy and making it more popular than ever and Oracle has done the same for JavaFX (deprecating JavaFX Script and embracing standard Java APIs was bold but well played).

Oracle Fusion Application Development

I was able to attend Ann Horton's presentation "Web Development Techniques from an Oracle Fusion Applications Developer." Ann's presentation was filled with screen snapshots, making it easy to see how to use the graphical-based tools to build Oracle Fusion Applications and use Oracle Fusion Middleware. I don't have any experience with Oracle Applications, but a lot of people do. Although I probably won't have the opportunity to work with them anytime soon, I like to see what other technologies are out there and enjoyed seeing a different way of developing applications. As is the case with much of the software development that occurs, Oracle provides tools that make much of the creation drag-and-drop and selecting things with the mouse.

Ann described "Oracle Fusion Applications Suite" as the "next generation of Oracle Applications" and added that "Fusion" implies integration of multiple products "under a common umbrella and one look and feel." Ann showed via numerous screen captures (often annotated with arrows, underlines, or other markings to provide focus) how to build up an application using Oracle Fusion Applications Suite.

One of the things I like to do at a technical conference is find out what others are using for tooling. Ann mentioned that thousands of developers have worked on Oracle Fusion Applications Suite and that they have used tools such as ade (Application Development Environment), JUnit, Selenium, OATS, and JAudit in their work. I thought it was interesting that JSP and JSF fragments (.jspx and .jsff files) were shown in the presentation.

Ann talked about Fusion developers using and providing "Fusion Guidelines, Standards, and Patterns" (GPS). More details about the Oracle Fusion Applications can be found in Oracle Fusion Applications Developer's Guide.

Oracle ADF and Mobile Development

Until I read the abstracts for this conference, I had not even realized that Oracle ADF can be used to develop applications for iOS and Android devices, but the subject of Oracle ADF Mobile was a popular one at the conference. The main page for Oracle ADF Mobile describes it like this:

Oracle ADF Mobile is an HTML5 and Java mobile development framework that enables developers to build and extend enterprise applications for iOS and Android from a single code base. Based on a hybrid mobile architecture, ADF Mobile supports access to native device services, enables offline applications and protects enterprise investments from future technology shifts.

The Oracle ADF Mobile FAQ states that Oracle ADF Mobile is licensed "as part of the Oracle Application Development Framework (ADF)" and adds that "Oracle ADF can be licensed either as 'Oracle Application Development Framework and TopLink' item on the technology price list, or as part of the Oracle WebLogic licenses." The FAQ also addresses device support: "Both iOS (5.x and above) and Android (2.3.x and above) devices are supported. Furthermore, both the tablet and smart phones running these mobile operating systems are supported."

One of the audience members asked me how using JavaFX differed from using Oracle ADF Mobile and licensing is obviously one of the major differences.

Other Blog Posts on RMOUG Training Days 2013 Conclusion

I would have liked to attend more sessions at RMOUG Training Days 2013, but enjoyed the brief time I was able to spend there this year. It was good to see people I've known for a number of years and to meet new people. It is always good to remember that there is much more to software development than the relatively narrow view one can get when working in the same circles and communities all the time.

Wednesday, February 13, 2013

Styling JavaFX Pie Chart with CSS

JavaFX provides certain colors by default when rendering charts. There are situations, however, when one wants to customize these colors. In this blog post I look at changing the colors of a JavaFX pie chart using an example I intend to include in my presentation this afternoon at RMOUG Training Days 2013.

Some Java-based charting APIs provided Java methods to set colors. JavaFX, born in the days of HTML5 prevalence, instead uses Cascading Style Sheets (CSS) to allow developers to adjust colors, symbols, placement, alignment and other stylistic issues used in their charts. I demonstrate using CSS to change colors here.

In this post, I will look at two code samples demonstrating simple JavaFX applications that render pie charts based on data from Oracle's sample 'hr' schema. The first example does not specify colors and so uses JavaFX's default colors for pie slices and for the legend background. That example is shown next.

EmployeesPerDepartmentPieChart (Default JavaFX Styling)
package rmoug.td2013.dustin.examples;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * Simple JavaFX application that generates a JavaFX-based Pie Chart representing
 * the number of employees per department.
 * 
 * @author Dustin
 */
public class EmployeesPerDepartmentPieChart extends Application
{
   final DbAccess databaseAccess = DbAccess.newInstance();

   @Override
   public void start(final Stage stage) throws Exception
   {
      final PieChart pieChart =
         new PieChart(
            ChartMaker.createPieChartDataForNumberEmployeesPerDepartment(
               this.databaseAccess.getNumberOfEmployeesPerDepartmentName()));
      pieChart.setTitle("Number of Employees per Department");
      stage.setTitle("Employees Per Department");
      final StackPane root = new StackPane();
      root.getChildren().add(pieChart);
      final Scene scene = new Scene(root, 800 ,500);
      stage.setScene(scene);
      stage.show();
   }

   public static void main(final String[] arguments)
   {
      launch(arguments);
   }
}

When the above simple application is executed, the output shown in the next screen snapshot appears.

I am now going to adapt the above example to use a custom "theme" of blue-inspired pie slices with a brown background on the legend. Only one line is needed in the Java code to include the CSS file that has the stylistic specifics for the chart. In this case, I added several more lines to catch and print out any exception that might occur while trying to load the CSS file. With this approach, any problems loading the CSS file will lead simply to output to standard error stating the problem and the application will run with its normal default colors.

EmployeesPerDepartmentPieChartWithCssStyling (Customized CSS Styling)
package rmoug.td2013.dustin.examples;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * Simple JavaFX application that generates a JavaFX-based Pie Chart representing
 * the number of employees per department and using style based on that provided
 * in CSS stylesheet chart.css.
 * 
 * @author Dustin
 */
public class EmployeesPerDepartmentPieChartWithCssStyling extends Application
{
   final DbAccess databaseAccess = DbAccess.newInstance();

   @Override
   public void start(final Stage stage) throws Exception
   {
      final PieChart pieChart =
         new PieChart(
            ChartMaker.createPieChartDataForNumberEmployeesPerDepartment(
               this.databaseAccess.getNumberOfEmployeesPerDepartmentName()));
      pieChart.setTitle("Number of Employees per Department");
      stage.setTitle("Employees Per Department");
      final StackPane root = new StackPane();
      root.getChildren().add(pieChart);
      final Scene scene = new Scene(root, 800 ,500);
      try
      {
         scene.getStylesheets().add("chart.css");
      }
      catch (Exception ex)
      {
         System.err.println("Cannot acquire stylesheet: " + ex.toString());
      }
      stage.setScene(scene);
      stage.show();
   }

   public static void main(final String[] arguments)
   {
      launch(arguments);
   }
}

The chart.css file is shown next:

chart.css
/*
   Find more details on JavaFX supported named colors at
   http://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#typecolor
*/

/* Colors of JavaFX pie chart slices. */
.data0.chart-pie { -fx-pie-color: turquoise; }
.data1.chart-pie { -fx-pie-color: aquamarine; }
.data2.chart-pie { -fx-pie-color: cornflowerblue; }
.data3.chart-pie { -fx-pie-color: blue; }
.data4.chart-pie { -fx-pie-color: cadetblue; }
.data5.chart-pie { -fx-pie-color: navy; }
.data6.chart-pie { -fx-pie-color: deepskyblue; }
.data7.chart-pie { -fx-pie-color: cyan; }
.data8.chart-pie { -fx-pie-color: steelblue; }
.data9.chart-pie { -fx-pie-color: teal; }
.data10.chart-pie { -fx-pie-color: royalblue; }
.data11.chart-pie { -fx-pie-color: dodgerblue; }

/* Pie Chart legend background color and stroke. */
.chart-legend { -fx-background-color: sienna; }

Running this CSS-styled example leads to output as shown in the next screen snapshot. The slices are different shades of blue and the legend's background is "sienna." Note that while I used JavaFX "named colors," I could have also used "#0000ff" for blue, for example.

I did not show the code here for my convenience classes ChartMaker and DbAccess. The latter simply retrieves the data for the charts from the Oracle database schema via JDBC and the former converts that data into the Observable collections appropriate for the PieChart(ObservableList) constructor.

It is important to note here that, as Andres Almiray has pointed out, it is not normally appropriate to execute long-running processes from the main JavaFX UI thread (AKA JavaFX Application Thread) as I've done in this and other other blog post examples. I can get away with it in these posts because the examples are simple, the database retrieval is quick, and there is not much more to the chart rendering application than that rendering so it is difficult to observe any "hanging." In a future blog post, I intend to look at the better way of handling the database access (or any long-running action) using the JavaFX javafx.concurrent package (which is well already well described in Concurrency in JavaFX).

JavaFX allows developers to control much more than simply chart colors with CSS. Two very useful resources detailing what can be done to style JavaFX charts with CSS are the Using JavaFX Charts section Styling Charts with CSS and the JavaFX CSS Reference Guide. CSS is becoming increasingly popular as an approach to styling web and mobile applications. By supporting CSS styling in JavaFX, the same styles can easily be applied to JavaFX apps as the HTML-based applications they might coexist with.

Tuesday, February 12, 2013

JavaFX Coming Soon to an Android or iOS Device Near You?

There has been big news recently in the world of JavaFX regarding many more components of JavaFX being open sourced as advertised at JavaOne 2012. In February Open Source Update, Richard Bair compiled a table of JavaFX projects that have been open sourced as of that post's writing (Monday, 11 February 2013). As exciting as all that open sourcing is, there was something even more exciting highlighted below the table: "We’re also going to open source our iOS and Android implementations over the next couple months."

Bair adds some timing and background information to this significant announcement:

The first bits and pieces for iOS should be out next week, with the rest of iOS and Android coming out at about the same time as the rest of prism (there is some timing dependency there). Both our ports are based on an as-yet unreleased version of JavaSE Embedded for iOS/Android.

After expressing the expected caveat "I’m not a lawyer", Bair also addresses licensing issues on iOS and points out that "both OpenJFX and OpenJDK are both licensed with the same GPLv2 with Classpath Extension." He further describes his understanding of the licensing situation: "this means that if you take OpenJFX + OpenJDK (minus any binary stubs released under a different license), then you can safely combine this with your application and release your application under your own license as a single application co-bundle." I am sure we'll hear more about the licensing details in the future as this develops.

Being able to develop Android and iOS applications with JavaFX will likely be a game-changer for JavaFX. I echo Bair's concluding sentence: "I am looking forward to seeing what you all will do with this contribution, and hope to be running many Java apps on my phone / iPad in the near future." I look forward to using (and maybe even writing) some JavaFX-based apps on my Droid! I am presenting on JavaFX at Rocky Mountain Oracle Users Group (RMOUG) Training Days 2013 tomorrow, so the timing of this announcement couldn't have been better.

Monday, February 11, 2013

Hello GroovyFX

GroovyFX brings together two of my favorite things: Groovy and JavaFX. The main GroovyFX Project page describes GroovyFX as "[providing] a Groovy binding for JavaFX 2.0." GroovyFX is further described on that page:

GroovyFX is an API that makes working with JavaFX in Groovy much simpler and more natural. GroovyFX is focused on exploiting the power of the Groovy Builder pattern to make JavaFX development easier and more concise than what is possible in Java. GroovyFX also leverages Groovy's powerful DSL features and AST transformations to eliminate boilerplate, making GroovyFX code easier to write and, just as importantly, easier to read.

The just referenced main GroovyFX page includes a "Hello World" example. In this post, I look at an even simpler "Hello World" example using GroovyFX. After that, I look at a slightly more involved example of using GroovyFX to render a Pie Chart. Both of these are examples I intend to show at my RMOUG Training Days 2013 presentation ("Charting Oracle Database Data with JavaFX and Groovy") this coming week.

A bare-bones GroovyFX Hello World! example is shown in the next code listing.

import groovyx.javafx.GroovyFX
import groovyx.javafx.SceneGraphBuilder
import javafx.stage.StageStyle
import javafx.stage.Stage

GroovyFX.start
{
   stage(title: 'RMOUG Training Days 2013',
         width: 300, height: 100,
         show: true)
   {
      scene
      {
         stackPane
         {
            text('Hello GroovyFX!', x: 50, y: 40)
         }
      }
   }
}

Running the above script leads to the following output:

The code and screen snapshot show how the concise text of GroovyFX makes it easy in just a few lines of code to specify a fully functioning JavaFX graphical application.

The next code listing shows a slightly more involved examples that generates a JavaFX Pie Chart. The database access code is not shown here, but it is easily accomplished with JDBC or Groovy SQL.

import rmoug.td2013.dustin.examples.ChartMaker
import rmoug.td2013.dustin.examples.DbAccess
import groovyx.javafx.GroovyFX
import groovyx.javafx.SceneGraphBuilder
import javafx.stage.StageStyle
import javafx.stage.Stage

def databaseAccess = DbAccess.newInstance()

GroovyFX.start
{
   stage(title: 'Employees Per Department',
         width: 800, height: 500,
         show: true)
   {
      scene
      {
         stackPane
         {
            pieChart(title: 'Number of Employees per Department',
                     data: ChartMaker.createPieChartDataForNumberEmployeesPerDepartment(
                        databaseAccess.getNumberOfEmployeesPerDepartmentName()))
         }
      }
   }
}

The above GroovyFX code leads to the following screen snapshot.

The simple GroovyFX code shown above combines Groovy with JavaFX to render a pie chart representation of the number of employees per department in the Oracle 'hr' sample schema.

The next code sample indicates the roughly equivalent source code for a JavaFX application that does not use GroovyFX.

package rmoug.td2013.dustin.examples;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class EmployeesPerDepartmentPieChart extends Application
{
   final DbAccess databaseAccess = DbAccess.newInstance();

   @Override
   public void start(final Stage stage) throws Exception
   {
      final PieChart pieChart =
         new PieChart(
            ChartMaker.createPieChartDataForNumberEmployeesPerDepartment(
               this.databaseAccess.getNumberOfEmployeesPerDepartmentName()));
      pieChart.setTitle("Number of Employees per Department");
      stage.setTitle("Employees Per Department");
      final StackPane root = new StackPane();
      root.getChildren().add(pieChart);
      stage.setScene(new Scene(root, 800 ,500));
      stage.show();
   }

   public static void main(final String[] arguments)
   {
      launch(arguments);
   }
}

The code for the direct JavaFX example can be compared to the GroovyFX example to see how the GroovyFX syntax is more concise (as is expected for something based on Groovy) and arguably more readable than the straight JavaFX code (though I maintain the JavaFX code is fairly readable in its own right). Comparing the two code samples also helps to see how GroovyFX uses property names well-known to users of the JavaFX API.

I am a fan of Groovy and of JavaFX and GroovyFX brings them together.