Do validators duplicate business logic? - asp.net

I know it's possible to use validators to check data input in the presentation layer of an application (e.g. regex, required fields etc.), and to show a message and/or required marker icon. Data validation generally belongs in the business layer. How do I avoid having to maintain two sets of validations on data I am collecting?
EDIT: I know that presentation validation is good, and that it informs the user, and that it's not infallible. The fact remains, does it not, that I am checking effectively the same thing in two places ?

Yes, and no.
It depends on the architecture of your application. We'll assume that you're building an n-tier application, since the vast majority of applications these days tend to follow that model.
Validation in the user interface is designed to provide immediate feedback to the end-user of the system to prevent functionality in the lower tiers from ever executing in the first place with invalid inputs. For example, you wouldn't even want to try to contact the Active Directory server without both a user name and a password to attempt authentication. Validation at this point saves you processing time involved in instantiating an object, setting it up, and making an unnecessary round trip to the server to learn something that you could easily tell through simple data inspection.
Validation in your class libraries is another story. Here, you're validating business rules. While it can be argued that validation in the user interface and validation in the class libraries are the same, I would tend to disagree. Business rule validation tends to be far more complex. Your rules in this case may be more nuanced, and may detect things that cannot be gleaned through the user interface. For example, you may enforce a rule that states that the user may execute a method only after all of a class's properties have been properly initialized, and only if the user is a member of a specific user group. Or, you may specify that an object may be modified only if it has not been modified within the last twenty-four hours. Or, you may simply specify that a string value cannot be null or empty.
In my mind, however, properly designed software uses a common mechanism to enforce DRY (if possible) from both the UI and the class library. In most cases, it is possible. (In many cases, the code is so trivial, it's not worth it.)

I don't think client-side (presentation layer) validation is actual, useful validation; rather, it simply notifies the user of any errors the server-side (business layer) validation will find. I think of it as a user interface component rather than an actual validation utility, and as such, I don't think having both violates DRY.
EDIT: Yes, you are doing the same action, but for entirely different reasons. If your only goal is strict adherence to DRY, then you do not want to do both. However, by doing both, while you may be performing the same action, the results of that action are used for different purposes (actually validating the information vs. notifying the user of a problem) , and therefore, performing the same action twice actually results in useful information each time.

I think having good validations at application layer allows multiple benefits.
1. Facilitates unit testing
2. You can add multiple clients without worrying about data consistency.
UI validation can be used as tool to provide quick response times to the end users.

Each validation layer serves a different purpose. The user interface validation is used to discard the bad input. The business logic validation is used to perform the validation based on business rules.
For UI validation you can use RequiredFieldValidators and other validators available in the ASP.NET framework. For business validation you can create a validation engine that validates the object. This can be accomplished by using the custom attributes.
Here is an article which explains how to create a validation framework using custom attributes:
http://highoncoding.com/Articles/424_Creating_a_Domain_Object_Validation_Framework.aspx

Following up on a comment from Fredrik Mörk as an answer, because I don't think the other answers are quite right, and it's important for the question.
At least in a context where the presentation validation can be bypassed, the presentation validations and business validations are doing completely different things.
The business validations protect the application. The presentation validations protect the time of the user, and that's all. They're just another tool to assist the user in producing valid inputs, assuming that the user is acting in good faith. Presentation validations should not be used to protect the business validations from having to do extra work because they can't be relied upon, so you're really just wasting effort if you try to do that.
Because of this, your business validations and presentation validations can look extremely different. For business validations, depending on the complexity of your application / scope of what you're validating at any given time, it may well be reasonable to expect them to cover all cases, and guarantee that invalid input is impossible.
But presentation validations are a moving target, because user experience is a moving target. You can almost always improve user experience beyond what you already have, so it's a question of diminishing returns and how much effort you want to invest.
So in answer to your question, if you want good presentation validation, you may well end up duplicating certain aspects of business logic - and you may well end up doing more than that. But you are not doing the same thing twice. You've done two things - protected your application from bad-faith actors, and provided assistance to good-faith actors to use your system more easily. In contexts where the presentation layer cannot be relied upon, there is no way to reduce this down so that you only perform a task like "only a number please" once.
It's a matter of perspective. You can think of this as "I'm checking that the input is a number twice", or you can think "I've guaranteed that I'm not getting a number, and I've made sure the user realises as early as possible that they're only supposed to enter a number". That's two things, not one, and I'd strongly recommend that mental approach. It'll help keep the purpose of your two different kinds of validations in mind, which should make your validations better.

Related

What are the Spring Web Flow advantages?

Can someone help me understand the advantages of Spring Web Flow.
What I have understood is
All the flows can be centrally configured in an XML file.
Need not have an overhead of carrying over the data from one request to another as it can be done by flow scope.
It helps especially in cases like Breadcrumbs navigation.
Flows can be further divided into Sub Flows to reduce the complexity.
Are there any other ones which I am have not tweaked into?
I'm going to play devil's advocate and say don't use it for anything other than simple use cases. Simple use cases meaning no ajax calls, no modal dialogs, no partial updates just standard html forms/flows for simple persistence (i.e page A -> page B -> Page C where each 'page' maps to a view-state definition in a 1 to 1 relationship all defined in the same flow xml file).
Spring webflow cons:
Yes everything is in xml files in theory it is suppose to be simple but when you have multiple flow xml files each with multiple state definitions and possibly subflow definitions it can become cumbersome to maintain or easily determine what the sequential logic of a flow is. (kind of like the old "GOTO operator" where any part of a flow logic can jump back to any previously or later defined part making the flow logic although seemingly "sequential" in xml... un-intuitive to follow)
Some features of Spring Webflow's documentation are unintuitive or flat out undocumented leading to hours of trial and error. For instance, exception handeling, usauge of 'output' tag (only works in subflow->back to parent caller undocumented), sending back flash view responses to a user is also unintuitive and uses a different container than Spring MVC (many times when a flow ends you want to send a msg to the user that is defined in a controller outside of webflow... but since the flow ended you can't do it with in spring webflow using flashScope container), etc...
Adding subflows although sounds good does not reduce complexity actually increases it. Due to the way subflows are defined. Definitions are long and complex and can be confusing when you have many end-states in both the main parent flow and the child subflows.
Initial setup and configuration can be painful if integrating with certain 3rd party view frameworks like Apache Tiles or Theymeleaf... I recall spending a few hours if not days on this.
State snapshots (Saving the user's input between pages) although a powerful feature from Flow A's view-state_1 <-> Flow A's view-state_2 and vise versa. This does not work between Main Flow A <-> Sub Flow B and vise versa... forcing the developer to manually bind (or rather hack) saving a user's state between Parent main flow's <-> subflows.
Debugging application logic placed inside webflow can be difficult. For instance, in webflow you can assign variables and perform condition checks all using SPEL inside the xml but this tends to be a pitfall. Over time you learn to avoid placing application logic inside the actual webflow xml and only use the xml to call service class methods and to place the returned values in the various scopes (again this hard learned lesson/best practice is undocumented). Also, because you are executing logic using SPEL... refactoring classes, method names, or variables sometimes silently break your application significantly increasing your development time.
fragment rendering... a powerful but unintuitive feature of webflow. Setting up fragment rendering was 1 of the most painful things I had to do with webflow. The documentation was lacking. I think this feature could easily go in the pros side if it was better documented and easy to setup. I actually documented how to use this feature via stackoverflow... How to include a pop-up dialog box in subflow
Static URLs per flow. If your flow has multiple views defined with in 1 flow your URL will not change navigating from view-state to view-state. This can be limiting if you want to control or match the content of the page with a dynamic url.
If your flow is defined in "/WEB-INF/flows/doSumTing/sumting-flow.xml" and your "base-path" is set to "WEB-INF/flows". Then to navigate to your flow you goto http://<your-host>/<your-webapp-name-if-defined>/doSumTing . The flow file name is completely ignored and not used in the URL at all. Although clear now I found this unintuitive when I first started.
Spring Webflow pros:
concept of "scope" containers flowScope, viewScope, flashScope, sessionScope and having easy access to these containers WITH IN A FLOW gives the developer flexibility as these are accessible from anywhere and are mutable.
Easily define states view-state,action-state,decision-state,end-state which clearly defines what each state is doing but as mentioned in the cons... if your application is complex and has MANY different states and transitions constantly Going back and forth... this can clutter your -flow.xml file makes it hard to read or follow the sequential logic. It's only easy if you have simple use cases with a small number of state definitions.
Seldom used but a powerful feature of webflow is flow inheritance. Common flow functionality across multiple flows can be defined in a single abstract parent flow and extended by child flows (similar to an abstract class definition in java). This feature is nice with regards to the DRY principle if you have many flows that share common logic.
Easily defined validation rules and support for JSR-303 (but Spring MVC has this as well)
The output tag can be used to send POJOs back and forth between Main flow <-> subflow. This feature is nice because the parameters don't need to be passed through the url via get/post and can pass as many POJOs as you wish.
Clearly defined views. What the view name is and which model variable it is being mapped to (e.g <view-state id="edit" view="#{flowScope.modelPathName}/editView" model="modelObj"> ). Also in the example just demonstrated can use preprocessing expressions for viewnames or most arguments in webflow... nice feature though not very well documented :/
Conclusion: Spring Webflow project was a good idea and sounds great on paper but the cons make it cumbersome to work with in complex use cases increasing development time significantly. Since a better solution exists for complex use cases (Spring MVC) to me it is not worth investing heavily in web flow because you can achieve the same results with Spring MVC and with a faster development time for both complex and simple use cases. Morever, Spring MVC is actively maintained, has better documentation, and a larger user community. Maybe if some of my cons are addressed it would tip the scales in Webflow's favor but until then I will recommend Spring MVC over webflow.
Note: I might be missing some things but this is what I came up with off the top of my head.
Additionally, you can use the back button and retain state up to the number of snapshots you choose to store.
You also may find this related question useful.

What logic must I cover in Collection.allow and Collection.deny to ensure it's secure?

So just started playing with Meteor and trying to get my head around the security model. It seems there's two ways to modify data.
The Meteor.call way which seems pretty standard - pretty much just a call to the server with its own set of business rules implemented.
Then there is the Collection.allow method which seems much more different to anything I've done before. So it seems that if you put an collection.allow, you're saying that the client can make any write operation to that collection as long as it can get past the validations in its allow function.
That makes me feel uneasy cause it's feels like a lot of freedom and my allow function would need to be pretty long to make sure it's locked down securely enough.
For instance, mongodb has no schema, so you'd have to basically have a rule that defines which fields would be accepted and the format those fields must be in.
Wouldn't you also have to put in the business logic for every type of update that might be made to your system.
So say, I had a SoccerTeam collection. There may be several situations I may need to make a change, like if I'm adding or removing a player, changing the team name, team status has changed etc.
It seems to me that you'd have to put everything into this one massive function. It just sounds like a radical idea, but it seems Meteor.call methods would just be a lot simpler.
Am I thinking about this in the wrong manner (or for the wrong use case?) Does anyone have any example of how they can structure an allow or deny function with a list of what I may need to check in my allow function to make my collection secure?
You are following the same line of reasoning I used in deciding how to handle data mutations when building Edthena. Out of the box, meteor provides you with the tools to make a simple tradeoff:
Do I trust the client and get a more responsive UI (latency compensation)? Or do I require strict control over data validation, but force the client to wait for an update?
I went with the latter, and exclusively used method calls for a few reasons:
I sleep better a night knowing there exists exactly one way to update each of my collections.
I found that some of my updates required side effects that only made sense to execute on the server (e.g. making denormalized updates to other collections).
At present, there isn't a clear benefit to latency compensation for our app. We found the delay for most writes was inconsequential to the user experience.
allow and deny rules are weak tools. They are essentially only good for validating ownership and other simple checks.
At the time when we first released to production (August 2013) this seemed like a radical conclusion. The meteor docs, the API, and the demos highlight the use of client-side writes, so I wasn't entirely sure I had made the right decision. A couple of months later I had my first opportunity to sit down with several of the meteor core devs - this is a summary of their reaction to my design choices:
This seems like a rational approach. Latency compensation is really useful in some contexts like mobile apps, and games, but may not be worth it for all web apps. It also makes for cool demos.
So there you have it. As of this writing, my advice for production apps would be to use client-side updates where you really need the speed, but you shouldn't feel like you are doing something wrong by making heavy use of methods.
As for the future, I'd imagine that post-1.0 we'll start to see things like built-in schema enforcement on both the client and server which will go a long way towards resolving my concerns. I see Collection2 as a significant first step in that direction, but I haven't tried it yet in any meaningful way.
stubs
A logical follow-up question is "Why not use stubs?". I spent some time investigating this but reached the conclusion that method stubbing wasn't useful to our project for the following reasons:
I like to keep my server code on the server. Stubbing requires that I either ship all of my model code to the client or selectively repeat parts of it again. In a large app, I don't see that as practical.
I found the the overhead required to separate out what may or may not run on the client to be a maintenance challenge.
In order for the stub to do anything other than reject a database mutation, you'd need to have an allow rule in place - otherwise you'd end up with a lot of UI flicker (the client allows the write but the server immediately invalidates it). But having an allow rule defeats the whole point, because a user could still write to the db from the console.
The usual allow methods I have are these:
MyCollection.allow({
insert: false
update: false
remove: false
})
And then, I have methods which take care of all insertions. These methods perform the type checks and permission assessment. I have found that to be a much more maintainable method: completely decoupling the data layer from the code which runs on the client.
For instance, mongodb has no schema, so you'd have to basically have a rule that defines which fields would be accepted and the format those fields must be in.
Take a look at Collection2. They support schema checking at run-time before inserting documents into the Collection.

Implementing process workflow in PureMVC

I'm looking for suggestions regarding implementing process flow / work flow management in a PureMVC based application.
Our Flex application includes a number of processes such as account creation, payment processing, etc.
Within our team, there is some discussion of how rigidly we should adhere to the PureMVC model.
Within the PureMVC model, it seems reasonable that the current state in the process could be managed in a Proxy.
Commands are clearly responsible for processing the actions required of each node and for node transitions.
Mediators for managing the UI.
However, I think that there is an important bit still missing here: a ProcessController.
The approaches we've reviewed all seem to either violate the PureMVC model (even just slightly) or make unreadable code.
A proxy would maintain the state of the process. As such, it seems to be an appropriate way to implement the controller. However, this is putting a lot of business logic into the proxy.
The Mediator space makes more sense, but the controller in that space would not necessarily directly interact with any particular UI element but would instead coordinate/delegate to dedicated Mediators.
Yet another model would have us put process transition information into Commands. While this seems to be the best place for that work (given the role of commands relative to proxies and mediators), this approach looks to make some particularly heinous looking code with process transition logic distributed among scores of commands.
So how have others handled this problem?
Thank
Curtis
This is exactly the problem that PureMVC StateMachine Utility (and Finite State Machines in general) are meant to solve.
In a simple XML format, you can define states, valid transitions to other states, and the actions that trigger those transitions.
It is all notification-based, so you send StateMachine.ACTION notifications that cause the StateMachine to execute any entering/exiting guard logic that may be necessary (e.g., only allow exiting the FORM_ENTRY state if all the data valid, or only allow entry into the FORM_PROCESSING state if the user has admin rights, etc.). If a state change occurs, notifications are sent that can be used to organize the view or execute logic upon entering the new state.
Here is a StateMachine Overview presentation that will give you a better idea
http://puremvc.tv/#P003/
I think your idea of 'ProcessController' is probably the better way of doing it. Personally, I'm not a fan of PureMVC and don't use it because it doesn't allow enough flexibility or extension points to help with such problems.
Frankly, it's hard to advise on your issue because I don't know exactly what you're trying to accomplish. I do agree that the concern needs to be handled by one object. If you can, try to create a model that can store the data for the process and have another class just manage it throughout. Not sure if that makes sense, but then again, your problem isn't very clear either.
As an added extra, I would look into Dependency Injection. I'm trying to remember if PureMVC does it (I don't think it does), but with DI it would of been a fairly simple problem to solve. Frameworks like Parsley and Robotlegs are really good at that.
In pureMVC the State Machine Utility is probably the best choice for a process controller - and btw, according to the Implementation Idioms & best Practices doc. for PureMVC, it's perfectly fine to have mediators that don't manage a visible component

Domain Object in Views

We've been having a discussion at work about whether to use Domain Objects in our views (asp.net mvc 2) or should every view that requires data be sent a ViewModel?
I was wondering if anyone had any pros/cons on this subject that they could shed some light on?
Thank you
I like to segregate my Domain Objects from my Views. As far as I'm concerned, my Domain Objects are solely for the purpose of representing the Domain of the application, now how the application is displayed.
The presentation layer should not contain any domain logic. Everything they display should be pre-determined by their Controller. The ideal way to ensure this is always adhered to is to ensure the view only receives these flattened ViewModels.
I did ask a similar question myself. Here's a quote from the answer I accepted:
I think that there are merits to
having a different design in the
domain than in the presentation layer.
So conceptually you are actually
looking at two different models, one
for the domain layer and one for the
presentation layer. Each of the models
is optimized for their purpose.
If I have the domain objects for Customer > Sales > Dispatch Address, then I don't want to have to deal with the object traversal in my view. I create a flattened view model that contains all of the properties. There's almost no extra work in mapping to and from this flattened view/presentation model if you use the excellent open source project AutoMapper.
Also, why would you want to pass an entire domain object back to a view if you can create an optimised representation of that model?
If you use NHibernate or similar - your domain objects will most likely be proxies, serializing these dun work. You should always use a ViewModel and map your domain objects to DTOs within your viewmodel. Don't take shortcuts here. Setting the convention will alleviate the pain you'll suffer later on.
It's a standard pattern for a reason.
w://
It depends. In some case it will be fine to use instances of model classes. In other cases a separate ViewModel is the better choice. In my experience it is perfectly acceptable to have different models in your domain and in your views. Or to use the domain model in the view. Do what works best for you. Do a spike for each option, see what works and then decide. You can even choose a different option for each view (and/or partial).
There are definitely going to be simple little apps where it's fine to use the same models across all layers. Generally little forms over data apps. But for a proper domain, my thoughts on the subject are to keep the domain models and view models separate because you don't want them to ever impact each other when changed.
If the domain logic needs a small change to process some new business logic on the back end, you don't want to risk that altering your view. Conversely, if marketing or someone wants to make changes to a view, you don't want those changes leaking back into your domain (having to populate fields and maintain data for no other purpose than some view somewhere is going to use it).
I have a good comparision currently because I'm working on two projects using different approaches. I'm far from stating that "this is bad and this is good" because this is written in some patterns. I know patterns, I like patterns, but I never blindly follow them just to be right. I always use what do I need currently to achieve current goals.
In first app, using domain objects in view, development is very quick. Few changes in few places and you have additional properties, form inputs etc. You don't bother about the layers, just extends/change the code and pass to another problem.
In the second app, where there are always object for use here, there and somewhere else, there's a dozens of classes looking the same, doing the same, and a ton of conversion code between various version of the same objects. More bad is that some developers do some logic on "this version" of class, and other logic is done on "that version". Development is very painful and requires a lot of testing afterwards. Changing a simple thing requires a lot of attention and a lot of code need to be changed. I really don't like this app for that, because I've never yet seen a business benefits from this approach, at least during last year (and we are in the production stage from the year). This app is three-four times more expensive to develop and maintain than the first one.
So, my funny answer on the question is: it depends. If you work in 10-20 people team, you like to come into the work, drink few coffies, talk with friend, do few simple things and go home, a lot of intermediate objects and conversion code will be good for you. If your goal is to be fast and cheap, if you want to focus on business layer, new features, quick changes following, and more if you touch software business and want to cash your project (we do all this stuff to be finally sold, right?), the second approach would be probably better.

What are the downsides to static methods?

What are the downsides to using static methods in a web site business layer versus instantiating a class and then calling a method on the class? What are the performance hits either way?
The performance differences will be negligible.
The downside of using a static method is that it becomes less testable. When dependencies are expressed in static method calls, you can't replace those dependencies with mocks/stubs. If all dependencies are expressed as interfaces, where the implementation is passed into the component, then you can use a mock/stub version of the component for unit tests, and then the real implementation (possibly hooked up with an IoC container) for the real deployment.
Jon Skeet is right--the performance difference would be insignificant...
Having said that, if you are building an enterprise application, I would suggest using the traditional tiered approach espoused by Microsoft and a number of other software companies. Let me briefly explain:
I'm going to use ASP.NET because I'm most familiar with it, but this should easily translate into any other technology you may be using.
The presentation layer of your application would be comprised of ASP.NET aspx pages for display and ASP.NET code-behinds for "process control." This is a fancy way of talking about what happens when I click submit. Do I go to another page? Is there validation? Do I need to save information to the database? Where do I go after that?
The process control is the liaison between the presentation layer and the business layer. This layer is broken up into two pieces (and this is where your question comes in). The most flexible way of building this layer is to have a set of business logic classes (e.g., PaymentProcessing, CustomerManagement, etc.) that have methods like ProcessPayment, DeleteCustomer, CreateAccount, etc. These would be static methods.
When the above methods get called from the process control layer, they would handle all the instantiation of business objects (e.g., Customer, Invoice, Payment, etc.) and apply the appropriate business rules.
Your business objects are what would handle all the database interaction with your data layer. That is, they know how to save the data they contain...this is similar to the MVC pattern.
So--what's the benefit of this? Well, you still get testability at multiple levels. You can test your UI, you can test the business process (by calling the business logic classes with the appropriate data), and you can test the business objects (by manually instantiating them and testing their methods. You also know that if your data model or objects change, your UI won't be impacted, and only your business logic classes will have to change. Also, if the business logic changes, you can change those classes without impacting the objects.
Hope this helps a bit.
Performance wise, using static methods avoids the overhead of object creation/destruction. This is usually non significant.
They should be used only where the action the method takes is not related to state, for instance, for factory methods. It'd make no sense to create an object instance just to instantiate another object instance :-)
String.Format(), the TryParse() and Parse() methods are all good examples of when a static method makes sense. They perform always the same thing, do not need state and are fairly common so instancing makes less sense.
On the other hand, using them when it does not make sense (for example, having to pass all the state into the method, say, with 10 arguments), makes everything more complicated, less maintainable, less readable and less testable as Jon says. I think it's not relevant if this is about business layer or anywhere else in the code, only use them sparingly and when the situation justifies them.
If the method uses static data, this will actually be shared amongst all users of your web application.
Code-only, no real problems beyond the usual issues with static methods in all systems.
Testability: static dependencies are less testable
Threading: you can have concurrency problems
Design: static variables are like global variables

Resources