Reputation: 65
So I have a bunch of methods, all of which take in various parameters of different data types, what i'm trying to achieve is a way to call into another method, passing in all the parameters that the current method takes in as well as its values, and in that method i will eventually be doing different types of validation based on the data type of the parameter. The idea being that I will have one validation method that I will be able to call at the beginning of each method, rather than going through each method and validating the parameters one at a time within each method. Below is a rough outline of what i'm trying to achieve, i've looked around and seem to found some uses with Reflection, but it seems passing the parameter types as well as their values is a bit trickier and was wondering if anyone else had come into a similar form of problem.
public void doStuffA(int a, string b, string c, bool d)
{
var params = ?
if (validateInput(params))
{
// do stuff
}
}
public void doStuffB(string x, string y, int z)
{
var params = ?
if (validateInput(params))
{
// do stuff
}
}
public bool validateInput(? params)
{
// do validation
}
Upvotes: 0
Views: 3493
Reputation: 7117
You should checkout the Enterprise Library Validation Application block. It does supports code, attribute and configuration validation.
The Validation Application Block is designed to allow you to easily validate objects. In many situations, you can validate an object with a single line of code. You can use attributes within your classes to define your validation rules:
[StringLengthValidator(0, 20)]
public string CustomerName;
In addition to using the built-in validation attributest is also quite easy to implement your own custom validators.
Upvotes: 1
Reputation: 11595
Your question is a valid question.
Perhaps you can have a couple layers of validation. The first layer of validation will serve as your default validation layer. This layer will perform validations to handle null values, empty strings, etc.
I agree that this is not a responsibility of business objects even though the people that are commenting on this post continue to advocate separation of concerns.
Separation of concerns is valid and can be executed justifiably by considering this requirement as a cross-cutting concern for your application logic to manage and not your business objects.
In this case, consider using Aspect Oriented Programming as a technique to solve this problem.
I believe PostSharp can deliver you this solution if you are using .NET or WinRT. Specifically, you want to leverage the OnMethodBoundary aspect that this tool provides. When applying this attribute to your methods or classes, you provide your application the ability to execute logic before a method gets executed and/or after a method gets executed.
This approach will serve as your solution for argument assertions, logging, security, etc.
Upvotes: 0