Refactor shiny apps

Goals

Agenda

  • Goals

  • Refactoring

  • Introduction to refactoring non-reactive code

  • Moving code into a python module

Goals

Learn some Shiny best practices:

Refactoring

Agenda

  • Goals

  • Refactoring

  • Introduction to refactoring non-reactive code

  • Moving code into a python module

Introduction to refactoring

From wikipedia:

In computer programming and software design, code refactoring is the process of restructuring existing source code - changing the factoring - without changing its external behavior.

For example:

  • Convert repeating scripts to a function
  • Split a long function into smaller functions
  • Separating code into python modules or shiny modules

Refactoring a shiny app

When should you refactor?

  • You’re trying to hold too much in your head
  • Changing the app is difficult
  • Other people don’t understand your code
  • You don’t understand your code!

Avoid premature refactoring

  • Start by just getting your app to work
  • Take small steps to avoid repetition
  • Ultimately you’re the one who needs to work with the code

Three main techniques

  1. Separate reactive and non-reactive code
  2. Use shiny modules
  3. Use functions to generate UI

Introduction to refactoring non-reactive code

Agenda

  • Goals

  • Refactoring

  • Introduction to refactoring non-reactive code

  • Moving code into a python module

Separate reactive and non-reactive logic

Most Shiny app code is non-reactive

  • Drawing plots
  • Summarizing data
  • Interacting with databases
  • (Really, everything except the actual reading of reactive inputs and calcs)

Note

It’s fine to include this code inside reactive functions.

But as your app grows you should separate them.

Reactivity makes everything harder

Reactive context makes them inherently harder to:

  • debug
  • test
  • document
  • reason about

Pull logic out of the reactive context

Non-reactive functions are familiar and predictable, since you can:

  • call them in a notebook
  • write unit tests
  • reuse them in other contexts

In turn, this makes your reactive code much clearer

Your turn

Moving code into a python module

Agenda

  • Goals

  • Refactoring

  • Introduction to refactoring non-reactive code

  • Moving code into a python module

What is a python module?

A python module could be as simple as a single python file.

You can import functions from this file into your shiny app.

Benefits:

  • Namespacing

  • Testing

  • Separation of functionality

  • Potential to re-use across multiple applications

Python module example

In a file example.py

def foo(x):
  # Do something with x
  return x

In your app:

from example import foo

foo(2)

Moving code from a shiny app to a python module

Note

  1. Keep your reactive code in the shiny app

  2. Move non-reactive code into python modules

Your turn