title: What are approaches to refactore an application with mutable global state stored in a database?
body: <p>I am trying to refactor an application implemented with C++ that uses sqlite as an in-memory database to store and access its state. The goals of the refactoring are of course to make future modifications or fixes easier and to allow some degree of unit testing. (Do I need to mention that currently there are no unit tests at all.)</p>
  <p>The purpose of the application is to perform a number of tasks in a feasible order. These tasks are given in an unspecified order and they potentially depend on each other, meaning that some tasks require other tasks to be performed beforehand. There are three types of tasks with different dependency rules and lots of special cases to be handled. Sometimes it is required to actually perform a task in order to find out if a dependent task can be performed after that.</p>
  <p>Here's how the application currently works:</p>
  <ol>
  <li><p>Get the unsorted list of tasks and write it to the database. There are three main tables for the three task types and a few helper tables. In addition to the input data, the tables contain some additional fields (flags, counters) that are initialized with some values and later modified during the process.</p>
  </li>
  <li><p>Until any tasks are left or an error occurs: Find the next feasible task according to some rules, then mark it as done and update the database. This update involves modifying flags in existing entries but also adding the results of the tasks as entries to the database that might be required as input for subsequent tasks.</p>
  </li>
  </ol>
  <p>The whole logic is implemened as a mix of SQL queries and program workflow which makes it extremely hard to find out what is happening where. The SQL queries are built from hardcoded strings with variables being inserted into placeholders. There is some ORM like design, meaning that there is a data class for each table but that doesn't help very much. SQL queries are not spread all over the code but over maybe 25 percent of the  15.000 lines.</p>
  <p>You might wonder why a database is used after all. As mentioned, it is in-memory and not used for persistence. The idea was probably that the logic could be implemented in a simpler and more scalable way with SQL statements rather than by program workflow.</p>
  <p>Fortunately I do have a good understanding of the logic behind the application. However I can't find an attack point to start refactoring due to the global mutable nature of the database. Of course my emotional reaction is &quot;Let's throw it away and start from scratch.&quot; But then I know that this is practically never a good idea.</p>
  <p>I know that this is a tough question. If I need to provide more information, please ask.</p>