I am trying to build something that will allow us to configure "custom" validation for each customer. So if a customer wants to see a value contain a specific char, be specific length, or equal something else they just add a pre-created option. I wrote something that seems to be very primitive, but works. I would like it to be more dynamic. For instance, I can pass in actual C# code and it will perform that operation on the value input and being compared.
public class Operation
{
public object value { get; set; }
public OMagic perform { get; set; }
}
public class Magic
{
public bool Validate(object val, Operation operation)
{
switch (operation.perform)
{
case OMagic.Equal:
return (string)val == (string)operation.value;
case OMagic.NotEqual:
return (string)val != (string)operation.value;
case OMagic.LengthGreaterThan:
return (int)val < (int)operation.value;
case OMagic.LengthEqual:
return (int)val == (int)operation.value;
case OMagic.LengthLessThan:
return (int)val > (int)operation.value;
default:
return false;
}
}
}
public enum OMagic
{
Equal,
NotEqual,
LengthGreaterThan,
LengthEqual,
LengthLessThan
}
That is the primitive code, and here are the tests I wrote (using nunit)
[TestFixtureSetUp]
public void SetupTest()
{
//CurrentMessage = getMessage(WebIZ.Test.UnitTest.Properties.Resources.TestResponse1);
Magic = new Magic();
}
private Magic Magic;
[Test]
public void Text_Compare_Works()
{
Assert.IsTrue(Magic.Validate("yes", new Operation() { value = "yes", perform = OMagic.Equal }));
Assert.IsFalse(Magic.Validate("yes", new Operation() { value = "no", perform = OMagic.Equal }));
Assert.IsTrue(Magic.Validate("yes", new Operation() { value = "no", perform = OMagic.NotEqual }));
Assert.IsFalse(Magic.Validate("yes", new Operation() { value = "yes", perform = OMagic.NotEqual }));
}
[Test]
public void Int_Compare_Works()
{
Assert.IsFalse(Magic.Validate(7, new Operation(){value = 7, perform=OMagic.LengthGreaterThan}));
Assert.IsTrue(Magic.Validate(7, new Operation() { value = 8, perform = OMagic.LengthGreaterThan }));
Assert.IsFalse(Magic.Validate(7, new Operation() { value = 7, perform = OMagic.LengthLessThan }));
Assert.IsTrue(Magic.Validate(7, new Operation() { value = 6, perform = OMagic.LengthLessThan }));
Assert.IsFalse(Magic.Validate(7, new Operation() { value = 8, perform = OMagic.LengthEqual }));
Assert.IsTrue(Magic.Validate(7, new Operation() { value = 7, perform = OMagic.LengthEqual }));
}
Magic.Validate("yes", new Operation() { value = "yes", perform = OMagic.Equal })
rather than"yes".Equals("yes")
, etc. \$\endgroup\$.Equals()
it's about your goal. You want to know if something meets some condition. But ultimately,Assert.IsFalse(Magic.Validate(7, new Operation(){value = 7, perform=OMagic.LengthGreaterThan}));
is no different fromAssert.IsFalse(7 > 7);
- in other words, your.Validate()
method does nothing. There is no point even writing a more flexible one. For simple comparisons, just compare. \$\endgroup\$