javascripthtmldesign-patternsdesign-principles

Design pattern for encapsulation of functions that draw / write an object


My specific case is a web application but I believe this would apply more generally:

I have data stored remotely in a database.

My application uses 'collection' objects that correspond to each table in the database and manage database interactions for that table. The collection object contains an array of 'row' objects corresponding to each row of data.

The collection and row objects are responsible for writing themselves to the page (in HTML) when requested ie. the collection table sets up the table and table headers (<table>,<thead>,<tbody>) and then tells each row in turn to write itself (<tr>,<td>).

All is working well, it's just starting to get unwieldy. The row object for example has more than 1000 lines of code to handle displaying different data types (radio buttons, checkboxes, images etc) as well as handling user interaction, validating data and dealing with image/file uploads.

I'd like to separate the code out so that display behaviours live in one place and interaction / data management behaviours live in another.

Do I:

  1. Keep the object structure 'as is' but have separate files containing the different types of behaviours eg. collection.js and collection_displayBehaviours.js

  2. Create a separate object class eg. 'htmlTableConstructor.js' that handles the production of html elements

  3. ?? Is there some approach I'm missing?


Solution

  • Read up on "refactoring"; and I'd start with "replacing switch statements with polymorphism". That's how to extract the "if type of data is 'sale-record' draw it this way" logic into a saleRecord class that includes a draw() method that knows how to render it.