Lets say i am writing a web app that accesses user accounts in a database. If the account exist use that data. But if the account doesn't exist create a new one.

Should this be done with two or one methods.

One method would search by name and if found get the account, but it would have a try catch block and if the query returned empty it would create the account with the name passed in.

Two methods would simply search and the create.

The benefits of one method would benefit from simplicity and code reuse but then that method is doing multiple things. And I have been told that is a bad thing. Where as two methods would would be separated well but it would have no code reuse.


Definitely 2 methods.

If you have 2 methods, you can stack and arrange them, thus reuse them either in different sequence or even separate from each other.

If you have 1 method with both functionalities, you can only use it for whatever you designed to use it, hence no code reuse.

Also, these are different functionalities, thus they are better off being their own methods.

You can provide a wrapper method around these 2 to first do search, then add if search returned no results.

| improve this answer | |
  • What would i name a wrapper method that does that? Something like "find OrCreate"? Or is there some other naming convention that would be better to follow? – mattNit Jun 24 '15 at 19:34
  • UpdateOrInsert will do. – Alexus Jun 24 '15 at 20:27

"Update or create if doesn't exist" can be considered a single operation: upsert. The real thing to be concerned about when it comes to "doing multiple things" (also known as the Single Responsibility Principle: a class should only have 1 reason to change) is what's managing the interaction between the DB and programming objects. Whatever it is should be separated out into a Data Access Layer (DAL). The specific class that handles user-DB mapping should only declare the specific schema for users; another class (possibly an ancestor) would be responsible for creating/retrieving and running queries (which may include upsert, along with the basic CRUD operations of create, read, update and delete).

If possible, find and use an existing DAL library/framework for the platform. If you can't find something suitable, there are various DAL patterns, such as Data Mapper.

| improve this answer | |

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.