2

Why do we sometimes add a new record to an object and then just return the variable and sometimes we insert it too. I am confused, can somebody clarify me on this?

3

There's actually three different designs: insert and return, return without insert, and optional insert and return. All of the methods are more or less the same, it's mostly a matter of preference.

The automatic insert design saves on code, as all the DML operations are self-contained. This also reduces flexibility, for example, you can't necessarily use these methods when testing callouts, or it may artificially increase DML operations. Also, sometimes you need a non-inserted object, such as testing a Visualforce controller that works on a new record.

The return without insert method increases the size of unit tests, but also increases flexibility, since developers are now in control of when they would like to use DML statements; they can also combine multiple DML calls in to a single operation. This is also better for situations where you only work on records in memory and no DML is necessary.

The optional insert design offers the best of the other two options. Developers can opt for automatic inserts when they need them, and still have the flexibility to combine DML operations or just create records that don't need to be inserted (such as testing some Visualforce controllers, etc).

The most important consideration should be consistency. All methods should use the same design, so developers don't need to read the source code for each method to see if they need to manually insert the records. Consistent unit test frameworks are more important than choosing a specific model, although I would strongly recommend not automatically inserting the records in any case, since it's often more convenient to have an option to insert or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.