Decoupled Controllers and a Simple Event-Driven Design

app3 in Github

This post is about using multiple controllers inside an application, whose composition is determined dynamically, so that all the FXML files are completely independent of each other. This differs a bit from the idea of nested controllers where the application FXML ‘includes’ component FXML files via the <fx:include> tag. In practice, I don’t think there is much between them. If in doubt, go with the nested controller option, as it’s a bit simpler.

I first discovered the method detailed in this post through ignorance, before realising nested controllers were even possible. I still prefer my way over nested controllers, but I am weird.

App3 in the repository allows you to drag files into a ListView which then fires events processed by other controllers to update UI elements. This app has 4 controllers, one ‘application’ controller which manages the while UI on  behalf of the application, and three specific controllers:

  • FileListController – Handles a list of files, and supports dragging from the desktop
  • FilePropertiesController – responsible for displaying a single file’s properties
  • FileDataController – responsible for displaying a single file’s contents.

All the File* controllers communicate via a simple set of File Events, managed by Google Guava’s EventBus. To keep the sample code manageable, the events only flow one-way from the FileListController to the other controllers.

For complex applications, it’s best to partition the user interface elements into separate controllers, each controlling a particular set of functionality. How you slice and dice your user interface is a strictly personal affair. Once you do that, you realise that each FXML-controller pairing lives in splendid isolation from the rest of your application (assuming you don’t stuff your controllers with fields imported from everywhere).

This quickly becomes an issue for application-wide functions that span multiple views. Here is where an events-driven approach comes to the rescue.

I will discuss a simpler architecture for my first post on multi-controller applications, whereby controller created events are published to other events subscribers, who also happen to be controllers. Future posts will address more realistic layered architectures and how these can be made to use events.

Key Points

  • A single event bus for the entire application
  • No ‘service’ or ‘logic’ layer for controllers to delegate to
  • Controllers are decoupled from each other
  • Controllers are decoupled from FXML

Key Point – A Single Event Bus

For application-wide messaging, a single bus is all that is necessary. Some complex controllers (dialogs for example) may require their own dedicated event bus, but I won’t discuss that in this post.

The event bus is initialised in the ApplicationController – which is the top level controller managing the application UI and all other controllers. All the other controllers are constructed with this single EventBus object.

class ApplicationController { 
   ...
 ...
   // this bus is used application wide
   private val applicationEventBus = EventBus()
   private val fileListController = FileListController(applicationEventBus)
   private val fileDataController = FileDataController(applicationEventBus)
   private val filePropertiesController = FilePropertiesController(applicationEventBus)
   ...
}

Key – No Service/Logic Layer

For this simple example, there is no service or logic layer, as the focus of this application is to demonstrate how to load multiple controllers and how to use an basic event-driven design for controller communication. Any real application would use controllers that delegate to some sort of service layer.

Key – Controllers Are Decoupled From Each Other

Since controllers only interact via event messages, the only information that passed between them is the event itself (“A File was Added”) and any model object inside the event. Events can contain data, but this should be part of the application domain/data model and NOT controller specific.

Key – Controllers Are Decoupled From FXML

Defining the controller class in the FXML mandates a default constructor, requires a setter based dependency injection approach. This works, but I prefer constructor based dependency injection to ensure controllers are always in a consistent state – one less thing to get wrong. This makes unit testing controllers more straightforward as well.

Interestingly, this could also mean one controller is mapped dynamically to multiple FXML files – something I have never needed to do.

The ApplicationController class has a simple method setupController() for loading FXML files and linking them to a controller. This is done from the JavaFX method initialize().

@FXML
fun initialize() {
    ...
    val fileListPane = setupController("/app3/fileList.fxml", fileListController)
    val filePropertiesPane = setupController("/app3/fileProperties.fxml", filePropertiesController)
    val fileDataPane = setupController("/app3/fileData.fxml", fileDataController)
    ...
}

/**
* Utility function to load FXML and link it to its controller
*/
private fun setupController(fxmlPath: String, controller: EventAwareController): Pane {
   val loader = FXMLLoader(javaClass.getResource(fxmlPath))
   loader.setController(controller)
   return loader.load<Pane>()
}

Code Setup

Event Bus – Controller Registration

Each controller inherits from the EventAwareController class whose function is to store a reference to the event bus (for event publishing) and to register the controller with the evenBus (for event subscribing). Inheritance is just one way of doing this, but enables all subclasses to publish events via the EventBus.post() method.

abstract class EventAwareController(val eventBus: EventBus){ 
   init{
      eventBus.register(this)
   }
}

Event Definitions

The events themselves are defined as standalone classes which both inherit from an abstract SingleFileEvent:

abstract class SingleFileEvent(val file: File) 

class FileAddedEvent(file: File) : SingleFileEvent(file)

class FileSelectedEvent(file: File) : SingleFileEvent(file)

If necessary, all events can implement some sort of event interface as well. Up to you. I generally use different, layered event class hierarchies to enable event propagation and translation between application layers.

Event Handlers (Subscribers)

In this application, all the event handlers are controllers. For each event of interest, a controller implements a subscriber method for that event type, annotated with the @Subscribe annotation from the Guava Libraries Event Bus.

In the example below, a single controller handles two types of events, which happen to have the same implementation. 

@Subscribe
fun handleFileAdded(e: FileAddedEvent) {
   println("FileDataController processing FileAddedEvent")
   loadAndDisplayContents(e.file)
}

@Subscribe
fun handleFileSelectionChanged(e: FileSelectedEvent) {
   println("FileDataController processing FileSelectedEvent")
   loadAndDisplayContents(e.file)
}

Since both are SingleFileEvent subclasses, one handler could have processed both events, given they both do the same thing, but I think having them split is a bit neater.  Here is a possible handler for all types of SingleFileEvent events.

@Subscribe
fun imaginaryHandleAllFileEvents(e: SingleFileEvent) {
   println("Some subscriber processing all SingleFileEvents here")
   loadAndDisplayContents(e.file)
...
}

Events In Action

A FileEvent is Published

A File Event is created when:

  1. A file is dragged into the ListView (FileAddedEvent)
  2. An item in the ListView is selected (FileSelectedEvent)

Here are the two code sections that generate these events (complete file):

File Drag ==> FileAddedEvent

fileListView.onDragDropped = EventHandler { event -> 
    ...
    eventBus.post(FileAddedEvent(firstFile))
  ...
}

ListView Selection ==> FileSelectedEvent

// fire event on EventBus every time selection changes
fileListView.selectionModel.selectedItemProperty().addListener { _, _, newSelection ->
...

eventBus.post(FileSelectedEvent(newSelection))
...
}
}

The Event is Processed

For the FileAddedEvent, two controllers process the events in different ways:

  • FileDataController loads the file content and displays it
  • FilePropertiesController displays basic file properties

Here are the same event subscribers for both Controllers:

// from FileDataController
@Subscribe
fun handleFileAdded(e: FileAddedEvent) {
   println("FileDataController processing FileAddedEvent")
   loadAndDisplayContents(e.file)
}

// from FilePropertiesController
@Subscribe
fun handleFileAdded(e: FileAddedEvent){
  println("FilePropertiesController processing FileAddedEvent")
  nameLabel.text = e.file.name
  pathLabel.text = e.file.path
  sizeLabel.text = e.file.length().toString()
}

Summary

This post focused on a single application, app3, in my repo. Like the other applications in the repo, you run it with gradlew (checkout the repository README.md for setup details):

gradlew runApp3 

Hopefully I have given you an understanding of a way to separate your controllers from each other, and from any particular visual representation in FXML, and introduced the excellent EventBus library along the way.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s