Should Validation and Data Correction logic be done in business or data access layer? - business-logic

So I have this general question of where should I have certain logic for example -
var data=GetItems();
if(data==null)
//return some defaults
else
return values
//second case..
if(id<=0)
//throw some exception
else
return id
So should the above code should it be a part of data access layer (I think it should) or a par tof business layer. Also,validation of data should it generally be part of data access or business layer ?

I think the question is whether it should be between the business or the UI layer. The purpose of the data layer is to CRUD, so the logic should only be oriented towards that.
In the second example above, I'd say that's business logic. You're saying that a negative id has a meaning which should throw an exception. That meaning exists only within the logic of the application you're creating - there's nothing inherent to data storage that says that this should be the case.
So my vote is for business layer, and you should give some thought to the UI layer as well.

Related

diffrence between persistence layer and bussiness logic layer

Persistence layer is a group of files which is used to communicate between the application and DB. 2. Business logic layer is the rules of how to retrieve the data information from the database, and then the sever takes those information to display on the user presentation layer
This two layers look the same
What do they mean in real scenario? Also do they have difference in code?
The idea for layering a system is isolation. One layer is independent of the other.
How many different Databases are out there? Postgresql, MySql, MongoDB, Cassandra...
The persistence layer (or Data Access Layer) will provide an interface to your your system.
Let's say you system needs to find an User by its ID.
public interface UserRepository {
User findByID (Long id);
}
For each database, the implementation will change, but for the application consuming it, does it really matter? No, as long as the contract provided by the interface is not broken.
Once you have the data, the business logic will dictate what and how you will deal with it. For a MVC point of view, the business logic also defines the transaction scope (more at: Why we shouldn't make a Spring MVC controller #Transactional?).
Let's say that you have your User that you retrieved using the previous interface. But you need to return additional attributes, for example, its salary. But there is no Salary Attribute on the User POJO. And also, to calculate the salary, you system needs to call an external system. Your business logic will take care of that and then return the condensed object (known as Data Transfer Obejct) to the caller.
Some resources:
https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html

Spring where to throw exception

I am working on a new Spring MVC based application.
I have multiple flows where the controller will make request to business manager and further business manager will talk to DAO layer to retrieve data.
There can be possible cases where I don't get data back from the DAO.
I want to understand what is best way to deal with this situation.
1) When ever there is no data retrieved for a query then Throw back Custom Exception like 'Content Not Found' from DAO layer to Business Layer and then to Controller and let controller decide what to do.
2) Return blank/null Pojo object back to business manager and let manager throw the exception to Controller.
3) Controller receives null/blank from Manager and decides what to do with that.
I am finding 1st approach better as when the exception is thrown i have complete stack trace to understand where exactly the problem occurred but on downside I will end up cluttering my code with Exception in the signatures.
Number 3 will leave the code clean but I wont be able to pin point where exactly the data retrieval failed as there can be multiple calls to DAO from Business Layer.
Throw an exception on the level where the situation of not having matching records (in other words, no data to be processed) actually is exceptional.
This largely depends on the specifics of your domain, but it's often the best idea to simply return an empty container object from the DAO if there was no matching object in the database. That is: an Collections.emptyList(), Optional.empty() or something with similar semantics. Under no circumstances return null, it's 2015 after all.
If having no matching data is an exceptional situation in your business domain, translate that to a specific exception in the service layer and let the controller handle that by translating again: into an error HTML page, some specific XML or JSON response or whatever the interface your users use to interact with your system.
The DAO layer executes queries and returns the results. It doesn't care about the results, so "nothing found" cannot be an exceptional situation in the DAO layer. It can be in the business layer, but it doesn't have to.
I wont be able to pin point where exactly the data retrieval failed
If your use case is http://server/something/2 and something 2 doesn't exist in the database, then there simply is no failure on the server side. So if there is no exception, or only one in the controller, then you can be pretty confident that no data is returned to the client because no data exists.
I would suggest you to throw custom exceptions at each layer. Each layer should be aware of exception handling.
Its beautifully explained in the below link.
Handling Dao exceptions in service layer

MVC - where to put communication code

I want to try to write (amateur here!) a multiplayer game, and now at designing I decided to use the MVC-pattern.
Now my question is: where should I put my networking code? In the Model or the Controller? (Obviously not the View)
EDIT:
Sorry, for the hundredst time my question was unclear.
The game itself will be MVC, and it will firstly communicate with a server (find player), and later with that player (send your turn and get other's turn). So where should I do that?
The MVC design pattern is actually a combination of two layers: presentation layer and model layer. Presentation layer usually deals with user interface (updates it and reacts to user's interaction). The model layer deals with domain business logic and persistence.
The networking code should go in the model layer.
To be exact, in the part of model layer, that deals with persistence, because there, from the standpoint of business logic, there is no difference where the data comes from. It can be from the SQL database, from opened network socket or detector on the mars rover. Those all are just data sources, which, often implemented as data mappers, are part of the model layer.
You could put the actual game itself in a new project and reference that between your MVC application, that way your game is entirely separated from your web application. This could be useful if you ever wanted to port it to WPF for instance. Another alternative is to have the game as Web Service which the MVC application requests information from and would provide scalability for additional languages to plugin in.
However, if you decide to keep everything as a whole in MVC then I would suggest the Model.
As a breakdown:
The controller takes care of all the web requests, i.e. GET and POST. It can also populate a model and return the appropriate view for that request.
The model contains the domain objects and logic to perform (i.e. extracting information from the repository and manipulating the data to be passed to the view).
The view returns the markup which is based upon the data stored within the model.
In certain implementations additional logic such as checking conditions and Repository calls also take place at the controller level, which is a technique known as Fat Controller Thin Model.
Edit:
You should be sending a request to the controller. I.e. In your games controller have a HTTPPost method that connects to the server and then sends the players turn info and gets the new information. For example:
[HttpPost]
public ActionResult SendPlayerTurnInformation(PlayerObject player)
{
// logic to connect to the Game Network
// connection.UpdatePlayerTurn(player);
//return success/fail
}
You could then do the same to get a specific players turn information and then update your model to be passed to the view which would contain the new information.

About software design: Where I must check parameters?

Imagine I have an application that request to the user a name, a category list. When user click on save button, application will save name and category to a database.
I have a layer that get name and category from UI. This layer check if there is a name (a string with length > 0). If this is correct, it will pass name a category to another layer. Note: category is a radiobutton list where one item is always selected.
On this second layer, application will select a suitable class to save name, depending on category.
On last layer, a class will save this name on a database. On this class I will check if name is empty or not.
My question is: where is the right place to check method's input parameters? on every layer? Maybe, I'm going to use these layers on others developments.
Is my example correct? Maybe, I can left validation on database layer and raise an exception to UI layer.
In general, in terms of the larger question about validating input that is ultimately persisted, it is best to:
Convert the input parameters to a
fully encapsulated business object as
soon as possible after you receive
it.
Validate early and fail fast then to
wait until you get to a lower layer
-- waste of resources, waste of time, possibly more complex (more things to
roll back).
Validate the business logic once and make that part of
your object instantiation process. (but note that validation of view logic and persistence logic may need to be done at the other layers and is separate from business logic)
Model how your object is persisted
using an ORM (e.g., Hibernate) so
that you could work purely at the
object level in memory and leave
persistence as an implementation
detail. Focus the business logic at
the object layer.
And in terms of method validation itself, I agree with Oded -- at every layer, and it should be done immediate upon method entry. Again, this is part of the fail fast methodology. But, as I noted above, this doesn't mean you validate business logic at every method (or every layer). I'm just referring to the basic practice of validating inputs (either by assertions or explicit checks and exceptions thrown).
where is the right place to check method's input parameters? on every layer?
Yes, on every layer. This is called defense in depth.
There are different reasons to do so on each layer:
UI/Client code: keep things responsive and avoid roundtrips when data is invalid
Business layer: Ensure business rules are kept
Data layer: Ensure that valid data is passed through
I disagree with the recommendation about every layer, all the time. It sounds too dogmatic to me.
All design represents a choice between functionality and cost. Your validation choices should reflect that as well.
I think your decisions should take into account the sharing and reuse of layers.
If the database is shared by more than one application, then the database cannot depend on every application validating properly. In that case, the database must validate to protect itself.
In this day and age of SQL injection attacks, I think binding and validating prior to reaching the persistence tier is a must. The schema should do what it must to ensure referential and business integrity (e.g. unique constraints on columns and required "not null"), but other validations should be done prior to hitting the database.
If the database is wholly owned by one and only one application, and there's a service that is the only gateway into the data, then validation can be done by the service. The cost of duplicating the validation on the database layer can be waived.
Likewise between the UI and the service layer.
Double validation on client and service tiers is common because the service is shared by many clients in a service oriented architecture. Today your service might be used by a browser based UI; suddenly there's a flock of mobile apps along side it that clamor for services, too. In that case the service absolutely must validate and bind each and every request.
No manufacturer polishes every surface to mirror quality. Sometimes a rough cast surface is permissible, because the benefit of grinding and polishing is negligible and the cost is too great.
Same with software.
I don't like dogmatic statements. It's better to understand the implications of your choices. Know the rules and when it's appropriate to break them.
If you're going for very loose coupling where other applications will also make use of these same layers, then I would recommend doing input checking at every step. Since each class/method should have no knowledge of expectation of the other classes/methods which ran before them in the stack, each one should enforce its requirements individually.
If the UI requires that a value be in the text box when the button is clicked, it should validate accordingly.
If the business logic requires that a name never be null/empty, it shouldn't allow a null/empty value to be placed in that property.
If the data layer has a constraint on that field requiring that a value be present, it should check that a value is present before trying to persist the data.

Where do you perform your validation?

Hopefully you'll see the problem I'm describing in the scenario below. If it's not clear, please let me know.
You've got an application that's broken into three layers,
front end UI layer, could be asp.net webform, or window (used for editing Person data)
middle tier business service layer, compiled into a dll (PersonServices)
data access layer, compiled into a dll (PersonRepository)
In my front end, I want to create a new Person object, set some properties, such as FirstName, LastName according to what has been entered in the UI by a user, and call PersonServices.AddPerson, passing the newly created Person. (AddPerson doesn't have to be static, this is just for simplicity, in any case the AddPerson will eventually call the Repository's AddPerson, which will then persist the data.)
Now the part I'd like to hear your opinion on is validation. Somewhere along the line, that newly created Person needs to be validated. You can do it on the client side, which would be simple, but what if I wanted to validate the Person in my PersonServices.AddPerson method. This would ensure any person I want to save would be validated and removes any dependancy on the UI layer doing the work. Or maybe, validate both in UI and in by business server layer. Sounds good so far right?
So, for simplicity, I'll update the PersonService.AddPerson method to perform the following validation checks
- Check if FirstName and LastName are not empty
- Ensure this new Person doesn't already exist in my repository
And this method will return True if all validation passes and the Person is persisted, False if Validation fails or if the Person is not persisted.
But this Boolean value that AddPerson returns isn't enough for me at the UI layer to give the user a clear reason why the save process failed. So what's a lonely developer to do? Ultimately, I'd like the AddPerson method to be able to ensure what its about to save is valid, and if not, be able to communicate the reasons why it's not invalid to my UI layer.
Just to get your juices flowing, some ways of solving this could be: (Some of these solutions, in my opinion, suck, but I'm just putting them there so you get an understanding of what I'm trying to solve)
Instead of AddPerson returning a boolean, it can return an int (i.e. 0 = Success, Non Zero equals failure and the number indicates the reason why it failed.
In AddPerson, throw custom exceptions when validation fails. Each type of custom exception would have its own error message. In addition, each custom exception would be unique enough to catch in the UI layer
Have AddPerson return some sort of custom class that would have properties indicating whether validation passed or failed, and if it did fail, what were the reasons
Not sure if this can be done in VB or C#, but attach some sort of property to the Person and its underlying properties. This "attached" property could contain things like validation info
Insert your idea or pattern here
And maybe another here
Apologies for the long winded question, but I definately like to hear your opinion on this.
Thanks!
Multiple layers of validation go well with multi-layer apps.
The UI itself can do the simplest and quickest checks (are all mandatory fields present, are they using the appropriate character sets, etc) to give immediate feedback when the user makes a typo.
However the business logic should have the lion's share of validation responsibilities... and for once it's not a problem if this is "repetitious", i.e., if the business layer re-checks something that should already have been checked in the UI -- the BL should check all the business rules (this double checks on UI's correctness, enables multiple different UI clients that may not all be perfect in their checks -- e.g. a special client on a smart phone which may not have good javascript, and so on -- and, a bit, wards against maliciously hacked clients).
When the business logic saves the "validated" data to the DB, that layer should perform its own checks -- DBs are good at that, and, again, don't worry about some repetition -- it's the DB's job to enforce data integrity (you might want different ways to feed data to it one day, e.g. a "bulk loader" to import a number of Persons from another source, and it's key to ensure that all those ways to load data always respect data integrity rules); some rules such as uniqueness and referential integrity are really best enforced in the DB, in particular, for performance reasons too.
When the DB returns an error message (data not inserted as constraint X would be violated) to the business layer, the latter's job is to reinterpret that error in business terms and feed the results to the UI to inform the user; and of course the BL must similarly provide clear and complete info on business rules violation to the UI, again for display to the user.
A "custom object" is thus clearly "the only way to go" (in some scenarios I'd just make that a JSON object, for example). Keeping the Person object around (to maintain its "validation problems" property) when the DB refused to persist it does not look like a sharp and simple technique, so I don't think much of that option; but if you need it (e.g. to enable "tell me again what was wrong" functionality, maybe if the client went away before the response was ready and needs to smoothly restart later; or, a list of such objects for later auditing, &c), then the "custom validation-failure object" could also be appended to that list... but that's a "secondary issue", the main thing is for the BL to respond to the UI with such an object (which could also be used to provide useful non-error info if the insertion did in fact succeed).
Just a quick (and hopefully helpful) comment: when you're wondering where to place validation, try pretending that, soon, you're going to completely recreate your UI layer using a technology you're not yet so familiar with**. Try to keep out of that layer any validation-like business logic that you know for certain you'd have to rewrite in the new technology.
You'll find exceptions - business logic that ends up in your UI layer regardless, but it's a useful consideration nonetheless.
** Mobile dev, Silverlight, Voice XML, whatever - pretending you don't know the technology of your "new" UI layer helps you abstract your concerns and get less mired in implementation details.
The only important points are:
From the perspective of the front-end(s), the Middle Tier must perform all validation, you never know whether someone is going to try circumventing your front-end validation by talking directly to your Middle Tier (for whatever reason)
The Middle Tier may elect to delegate some of that validation to the DB layer (e.g. data integrity constraints)
You may optionally duplicate some validation in the UI, but that should only be for the sake of performance (to avoid round-trips to the Middle Tier for common scenarios, such as missing mandatory fields, incorrectly formatted data, etc.) These checks should never take the place of doing them in the Middle Tier
Validation should be done at all three levels.
When I am in a project I assume I am making a framework, which most of the time is not the case. Each layer is separate and must check all layers input before doing an operation
Each level can have a different way of doing it, it is not necessary they all use the same, but ideally they should all use the same validation with the ability to customize it.
You never want to let bad data into the database. So you can never trust the data you are getting from the business layer. It needs to be checked.
In the business layer you can never trust the UI layer, and you must check it to prevent un-needed calls to the database layer. The UI layer works the same way.
I disagree with David Basarab's comment that the same validations should be present in all layers. This defies the paradigm of responsibility of layers for one reason. Secondly, though the main intention is to make the layers (or components) loosely coupled, it is also important that a level of responsibility (and hence trust) is endowed on the layers. Though it might be necessary to duplicated some validations in UI and Business Layer (since UI layer can be bypassed by hacking attempts), however, it is not advisable to repeat the validations in each layer. Each layer should perform only those validations which they are responsible for. The biggest flaw in repeting validations in all layers is code redundancy, which can cause maintenance nightmare.
A lot of this is more style than substance. I personally favor returning status objects as a flexible and extensible solution. I would say that I think there are a couple classes of validation in play, the first being "does this person data conform to the contract of what a person is?" and the second being "does this person data violate constraints in the database?" I think the first validation can, and should be done at the client. The second should be done at the middle tier. With this division, you may find that the only reasons the save could fail are 1)violates a uniqueness constrains, or 2)something catastrophic. You could then return false for the first case, and throw an exception for the other.
If tier R is closer to the user (or any input stream you don't control) than tier S then tier S should validate all data received from tier R. This does not mean that tier R shouldn't validate data. It's better for the user if the GUI warns him he's making a mistake before he attempts a new transaction. But no matter how bulletproof the validation in your GUI is, the next tier up should not trust that any validation has taken place.
This assumes your database in completely under your control. If not, you have bigger problems.
Also, you could have the UI pass the data needed to build a Person object through some sort of PersonBuilder object, so that object creation is consolidated in the domain/business layer, and you can keep the Person object in a state that is always consistent. This makes more sense for more complex entities, however even for simple ones, it is good to centralize object creation, just like you centralize persistence, etc.

Resources