Reputation: 910
Assume there is an Employee class, one of the business requirements is that the EmployeeName becomes unique. Now using the 3 Tier Architecture,
Tier 1 : Presentation
Tier 2 : Domain Model + Data Service Classes (Business Logic Layer)
Tier 3 : Data Access Classes + Stored Procedures (Data Access Layer)
Since the requirement above is a business requirement, where do you think the best place to put this rule is?
Option 1 : Unique key constraint in the database
Option 2 : Checking condition in the Data Service class in the business layer in order to keep the business logic encapsulated in this layer regardless of the data layer being used?
Upvotes: 6
Views: 3349
Reputation: 27974
In all three layers. However, what's important is the frequent fact that validation requirements (=the actual data constraints) differ from layer to layer. This because of the differing context and designed system boundaries.
In your example, the validation may be as follows:
The result is, that from a database perspective you check for a reasonable amount of constraints to keep the system consistent, but don't assume what's a matter of a higher-order logic. In fact, you don't limit future changes unnecessarily. From the business logic perspective, there's the complete set of constraints enforced. And, finally, from the presentation logic perspective, you don't overvalidate: only the simple validations to reduce unnecessary traffic to the business logic are performed, possibly preventing exceptions from the business logic layer, not duplicating anything more complex.
As a rule of thumb, it's always best practice to provide detailed validations at the facade of the business logic layer. That's the place where the (potentially untrusted) presentation layer and/or 3rd party (which may be just another corporate system) API consumers connect.
Further, some specific comments to the options you outlined in your question:
Option 1 : Unique key constraint in the database
Not only. It would work from the data correctness point of view, but by relying solely on database constraints, you are loosing semantics and would struggle providing a human understandable error message. Further, every bad input would travel down to the database, opening a potential hole for DoS attacks that could harm the whole technology stack.
Option 2 : Checking condition in the Data Service class in the business layer in order to keep the business logic encapsulated in this layer regardless of the data layer being used?
Yes, see above. However, don't compromise security, performance, and user experience by avoiding at least the basic, simple-to-evaluate validations in the presentation layer.
Upvotes: 8