PDA

View Full Version : Best practices: where to place code?



RobertSF
12-20-2017, 08:07 PM
I'm using Excel, but this is a general coding question. I have a user form that displays a list of records. On that same form, I have buttons to add, edit, and delete records -- your basic CRUD. Let's focus on the Add function. When you click the Add button, a second form pops up that lets you enter the data for the record. My question is, which is the better place to put the code that actually adds the record, in the second form or in the calling form?

In other words, would you black-box the Add form as a complete Add function? Or would you treat the Add form merely as an input device?

In PHP (which I know better than VBA), especially under a Model-View-Controller paradigm, the form is just a view -- it accepts data, it validates data, and it returns data, but the actual processing happens in the controller. Maybe that's my answer, but I don't know VBA well enough.

I realize this is an opinion topic, but all opinions are welcome. I don't have a "right" answer in mind.

Logit
12-21-2017, 07:18 PM
.
In your given example, my preference would be to place the ADD Macro code in the ADD FORM. Makes it easier to trouble-shoot later if there is an issue
with the code / command button / text field (i.e., controls) connections.



Hope that makes sense.

SamT
12-22-2017, 10:02 AM
I would only use one Form since it already has controls and methods to retrieve records and edit them. THose same Controls can be used to enter the data for a new record.

Depending on the complexity of the whole Project, I might place all the retrieval, Change saving and record adding code in one or more standard Modules. That would depend on how many Procedures are used in other code... And how I felt at the time.

I am also beginning to think that all Sheet Accessing code go in the Sheet's Code Module, since Workbook code, Sheets' Code, Forms' Code, and Class Modules' Code all run in separate threads when available. This also has the advantage that all these Code Modules can have Procedures with the same names, so one can copy procedures to different "Data Base" sheets.

Example Worksheet Public Functions and Subs
Public Function ListRecords(Optional WhichSet As String = "Next", _
Optional NumRecords as Long = 10) As Variant

Public Function GetRecord(PrimaryKey) As Variant
Public Function NextRecord(PrimaryKey) As Variant
Public Function PreviousRecord(PrimaryKey) As Variant
Public Sub DeleteRecord(PrimaryKey)
Public Sub AddRecord(Record As Variant)

RobertSF
12-22-2017, 04:45 PM
Thanks Logit and SamT. I didn't know that workbook, sheet, form, and class code ran in separate threads if possible. Merry coding to all! :)