What patterns are generally interesting to look at to handle validation? - c#

I'm creating an sudoku in c#.
A user can create an new sudoku.
My sudoku class:
public class Sudoku
{
#region Datamembers
private Field[,] grid;
private byte blockRows;
private byte blockColumns;
private Hashtable peers;
The user can save the newly created sudoku. When doing so, some validations are performed. For example: Look if not all fields are filled, look if not all fields are empty, look if no identical digits in same row, column, block, ...
My validation ends up looking like this: (it is situated in the sudoku class)
public bool IsValid()
{
bool isValidSetup = this.IsValidSetup();
if (!isValidSetup) return isValidSetup;
return this.IsTrulyValid();
}
private bool IsValidSetup()
{
bool isEntirelyFilled = this.Is_EntirelyFilled();
bool isEntirelyEmpty = this.Is_EntirelyEmpty();
bool hasIdenticalDigits = this.Has_IdenticalDigits();
this.Add_SetupValidationMessages(isEntirelyFilled, isEntirelyEmpty, hasIdenticalDigits);
return !isEntirelyEmpty && !isEntirelyFilled && !hasIdenticalDigits;
}
private bool IsTrulyValid()
{
this.Clean();
this.Solve();
bool hasNoSolutions = !this.Is_EntirelyFilled();
bool hasMultipleSolutions = false;
if (!hasNoSolutions) hasMultipleSolutions = this.Has_MultipleSolutions();
this.Add_TrulyValidationMessages(hasNoSolutions, hasMultipleSolutions);
return !hasNoSolutions && !hasMultipleSolutions;
}
I would like to split validation from sudoku, to make it OOP.
I looked into the strategy pattern, since that looked like something I could use, and is used a lot in validation. But as far as I understand the pattern, it's not what I need after all; Reason for that is because it's based on selecting a validation based on certain factors. I'm probably wrong, but I can't seem to realize why I would need that in my situation.
I Need one of the seperated validations (Is_EntirelyFilled() ) in another class. That's the only one not only used to validate the sudoku.
So, should I just put all this validation in 1 class? Or should make separate classes for each validation and call them seperatly? Any other suggestions?

You should have a ValidationHandle as Abstract Implement it differently for your needs and pass it to your client code. Something like that as I remember.
The IBrakeBehaveior should be your IValidationHandle
The sub ones are validation types.
Car is the cllient class and you need an instance of IValidationHandle in client code.
Where you need in client code you call IValidationHandleInstance.Validate()
by polymorphism it knows how validation execute.
Something like that
public interface IValidationHandle
{
bool Validate();
}
//TODOs: Separate classes
public class IsTrulyValidValidator:IValidationHandle;
public class IsValidValitor:IValidationHandle;
public class EntirelyFilledValidator:IValidationHandle;
class Client
{
private IValidationHandle validator=null;
public void SetValidationHandler(IValidationHandle validator)
{
this.validator=validator;
}
//Where You need call
validator.Validate();
}

Related

Updating Data in your model directly from a class

I'm making a simple game as a practice project based around random events, to make it easier to add new events I’ve decided to use a keyword system where each event gets keywords assigned to them that are then used to process the event, this can be as simple as displaying as message, changing data in the model or rolling again on the random table.
I have a class that randomly decides an event and returns a List of strings with keywords.
I want to make a class where all the keywords are stored as methods that can then be called with the list.
Something like this:
class Keyword
{
public void InputKeywords(List<string> Ikeywords)
{
foreach (var item in Ikeywords)
{
switch (item)
{
case "keyword0":
keyword0();
break;
case "keyword1":
keyword0();
break;
case "keyword2":
keyword0();
break;
}
}
}
private void keyword0()
{
//do something
}
private void keyword1()
{
//do something
}
private void keyword2()
{
//do something
}
}
Now the problem I’m facing is updating the data in the model from the keywords class.
Because the events are chosen at random I don't know for each event what data to send to the class to have it update it.
The solutions I've come up with myself:
Make my model static, no more issues with accessing data, Google tells me this is frowned upon and should be avoided.
Send the model to the Keyword class, do some magic, and return the model. Would be an easy solution but feels wrong to me, from what I've come to understand about MVVM is that the data should be updated from the viewmodel, but I could be thinking too much inside of the box.
Gather all possible data to be changed into a seperate class, send that to the keyword class and update the model afterwards. This sounds like a hassle and feels like I'm just moving the problem elsewhere.
I feel like I'm missing the "right" way of doing this. What would be the "best" approach?
First of all the naming of the keyword class feels misleading here. It is basically an event handler, so I would also name it like on (e.g. RandomEventGenerator)
To your problem I would also not recommend you to use static models. Your testability will suffer from it since you won't use dependency injection there. This being said your second approach seems to go into the right direction. I would suggest to use inject an EventInvoker Interface.
public interface IEventInvoker
{
public void RaiseEvent();
}
This can be implemented in an operator, which has access to your data model and has predefined actions to modify your data.
public class WeatherOperator : IEventInvoker
{
private readonly WeatherEngine _weatherEngine;
public WeatherOperator(WeatherEngine weatherEngine)
{
_weatherEngine = weatherEngine;
}
public void RaiseEvent()
{
StartSunshine();
}
public void StartSunshine()
{
_weatherEngine.RemoveClouds();
_weatherEngine.SetSunPosition(DayTimes.Noon);
}
public void LetItRain()
{
_weatherEngine.SetCloudes(CloudModes.FullCover);
_weatherEngine.SetRain(RainIntesity.Medium);
}
}
With a list of the IEventInvoker you can then go to your EventHandler.
public class RandomEventGenerator
{
private readonly List<IEventInvoker> _eventInvoker;
private readonly Dictionary<string, Action> _eventDictionary;
public RandomEventGenerator(List<IEventInvoker> eventOperator, List<string> keywords)
{
_eventInvoker = eventOperator;
_eventDictionary = RegisterKeywordsToRandomEvents(keywords);
}
private Dictionary<string,Action> RegisterKeywordsToRandomEvents(List<string> keywords)
{
var eventDictionary = new Dictionary<string, Action>();
foreach (var keyword in keywords)
{
var random = new Random();
var index = random.Next(_eventInvoker.Count);
eventDictionary.Add(keyword,_eventInvoker[index].RaiseEvent);
}
return eventDictionary;
}
public void EventByKeyword(string Keyword)
{
_eventDictionary[Keyword].Invoke();
}
public void RandomEvent()
{
var random = new Random();
var index = random.Next(_eventInvoker.Count);
_eventInvoker[index].RaiseEvent();
}
}
Please note that I, to keep it small, didn't used null checks or input validations here, which is highly recommended.
With this approach you have a clear cut bettween your model/data and your viewmodel/data accesor.

Is there a "right" way to abstract out my code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have been developing in C# for around 12 months now (from scratch, no previous dev experience apart from a little bit of PHP script hacking) and I like to think I have developed my skills to a level which I can write an app and it perform its function perfectly.
however, I am still a little confused about best coding practises, I understand that this code is bad:
class Example1
{
public static Alert GenerateAlert()
{
Alert AlertObject = new Alert();
AlertObject.AlertDatetime = DateTime.Now;
AlertObject.AlertHasRecords = false;
return AlertObject;
}
}
If for example AlertDatetime requires more than a simple line like DateTime.Now; I will end up bulking out a massive function. not good!
However, I cant see a problem with the following two examples (I favour Example 2)
class Example2
{
public static Alert AlertObject = new Alert();
public static Alert GenerateAlert()
{
PopulateAlertDate();
CheckForAlertRecords();
return AlertObject;
}
private static void CheckForAlertRecords()
{
AlertObject.AlertHasRecords = false;
}
private static void PopulateAlertDate()
{
AlertObject.AlertDatetime = DateTime.Now;
}
}
class Example3
{
public static Alert GenerateAlert()
{
Alert AlertObject = new Alert();
AlertObject.AlertDatetime = PopulateAlertDate();
AlertObject.AlertHasRecords = CheckForAlertRecords();
return AlertObject;
}
private static bool CheckForAlertRecords()
{
return false;
}
private static DateTime PopulateAlertDate()
{
return DateTime.Now;
}
}
Is one example better than the other, and if so why? or is there a completely different way of doing it?
Your first example is fine.
If, at a later time, AlertDateTime requires a more complex function to be initialized, you can always refactor your code to something like example 3. Until then, respect the KISS (Keep it simple) and YAGNI principles.
Note that the interface (the publicly available methods and their signature) does not change between examples 1 and 3. This is a good thing. It means that you can move between those styles without having to modify the code that uses your class.
Example 2, however, has a lot of problems:
The information hiding principle basically says that you should not expose something publicly without a good reason. Why would you store your newly generated Alert in a publicly accessible "global variable"?
Example 2 behaves differently: If you call GenerateAlert twice, it will return a reference to the same Alert object both times. (Think about what happens if you call it once today and again tomorrow.)
As a side note, the naming of your methods in Example 3 can be improved. Try to think of each method in isolation: PopulateAlertDate() does not populate the alert date. It returns a date that can be used to populate an alert date. The name GetDefaultAlertDate() might be more appropriate.
+1 for the great answer of Heinzi.
I'll add that in example 3 you are using a variation of the Façade pattern. You are wrapping a class with its complicated & repeated initializing logic, and also hide the interface of this object and expose new methods instead. If later you have several different ways to create the same object, you should consider the Factory pattern.
Pay attention: you should firstly favor placing some of the code in the original class' constructor, if there is no reason of using another variation at a time.
Example 2 resembles the Singleton anti-pattern, which serves another purpose - keeping one instance of a class. This is usually done for services you prefer being created once and for all. Even then, you better look at Dependency Containers for greater unit testing capabilities.
If there's more logic in these functions than just assigning true or false, you might want to use a factory and interfaces. A completely abstracted code following the solid principles would look like:
public class AlertFactory : IAlertFactory {
IAlertDatePopulator alertDatePopulator;
IAlertRecordsChecker alertRecordsChecker;
public AlertFactory(IAlertDatePopulator alertDatePopulator, IAlertRecordsChecker alertRecordsChecker) {
this.alertDatePopulator= alertDatePopulator;
this.alertRecordsChecker = alertRecordsChecker;
}
public Alert GenerateAlert() {
Alert alertObject = new Alert();
alertObject.AlertDatetime = alertDatePopulator.Populate();
alertObject.AlertHasRecords = alertRecordsChecker.Check();
return alertObject;
}
}
with
interface IAlertFactory { Alert GenerateAlert(); }
interface IAlertDatePopulator { DateTime Populate(); }
interface IAlertRecordsChecker { bool Check(); }
You can then add concrete implementations for these interfaces, for example:
public class DateTimeNowAlertDatePopulator : IAlertDatePopulator {
public DateTime Populate() { return DateTime.Now; }
}
public class SomeCalculationAlertDatePopulator : IAlertDatePopulator {
public DateTime Populate() { return /* something calculated */; }
}
resp.
public class AlwaysFalseAlertRecordsChecker : IAlertRecordsChecker {
public bool Check() { return false; }
}
public class SomeCalculationAlertRecordsChecker : IAlertRecordsChecker {
public bool Check() { return /* something calculated */; }
}
Then you can create configured factories:
public class DateNowAndRecordsFalseAlertFactory : AlertFactory {
public DateNowAndRecordsFalseAlertFactory ()
: base (new DateTimeNowAlertDatePopulator(), new AlwaysFalseAlertRecordsChecker()) { }
}
public class DateNowAndCalculatedRecordsAlertFactory : AlertFactory {
public DateNowAndCalculatedRecordsAlertFactory ()
: base (new SomeCalculationAlertDatePopulator(), new AlwaysFalseAlertRecordsChecker()) { }
}
And then just use your factory:
var alertFactory = new DateNowAndRecordsFalseAlertFactory ();
var myAlert1 = alertFactory.GenerateAlert();
var alertFactory2 = new DateNowAndCalculatedRecordsAlertFactory();
var myAlert2 = alertFactory2.GenerateAlert();
etc. This seems a lot of code for a simple functionality, but if you expect a lot of extensions with lots of logic coming up, then this is clean code following the open/close principle (to be open for extensions (by just adding new interface implementations) but closed for modifications (not needing to modify existing code anymore)).
Most effective when used with dependency injection. You'd then configure your factory like this:
public class DateNowAndRecordsFalseAlertFactory : AlertFactory {
public DateNowAndRecordsFalseAlertFactory (DateTimeNowAlertDatePopulator alertDatePopulator, AlwaysFalseAlertRecordsChecker alertRecordsChecker)
: base (alertDatePopulator, alertRecordsChecker) { }
}
And just do:
var alertFactory = someDiContainer.Resolve<DateNowAndRecordsFalseAlertFactory>();
You are trying to instantiate an object and I don't see a point of having static method for that (there is an answer already with factory, do you really need that?)
In place where you have to create this object simply do
var alert = new Alert();
If you want to customize some of properties after object is created with default values, then here is shortcut
var anotherAlert = new Alert() { AlertDatetime = DateTime.Now };
Normally you should create instance of object in the way usable at most, so if you always have to construct it with current date, this is what constructor normally does:
public class Alert
{
// do not add class name to property
public DateTime DateTime {get; set;}
// this don't need initialization if default value is false
public bool HasRecords {get; set;}
public Alert()
{
DateTime = DateTime.Now;
}
}

A single DTO with multiple constructors - does this seem like an appropriate solution?

I have an entity called "Set" which contains Cards. Sometimes I want to see the entire card and its contents (card view), when sometimes I just want to know how many cards are in the Set (table views). In my effort to keep things DRY, I decided to try and re-use my SetDto class with multiple constructors like this:
public class SetDto
{
public SetDto()
{
Cards = new List<CardDto>();
}
// Called via SetDto(set, "thin")
public SetDto (Set set, string isThin)
{
var setDto = new SetDto()
{
SetId = set.SetId,
Title = set.Title,
Details = set.Details,
Stage = set.Stage,
CardCount = set.Cards.Count
};
return setDto;
}
// Called via SetDto(set)
public SetDto(Set set)
{
SetId = set.SetId;
UserId = set.UserId;
Title = set.Title;
Details = set.Details;
FolderId = set.FolderId;
Stage = set.Stage;
IsArchived = set.IsArchived;
Cards = new List<CardDto>();
foreach (Card card in set.Cards)
{
Cards.Add(new CardDto(card));
}
}
/// property definitions
I originally had two different DTOs for sets - ThinSetDto and FullSetDto - but this seemed messy and tougher to test. Does the above solution seem ok, or am I breaking a known best-practice? Thank you for your time!
I would create three methods in the SetManager class (a class handling CRUD operations) not in the DTO.
The dto shold have no such a logic inside. Anyway I agree with you that the replication is useless (and evil).
public class BaseSetDTO
{
public BaseSetDTO()
{
Set();
}
internal virtual void Set()
{
//Do your base set here with base properties
}
}
public class SetDTO : BaseSetDTO
{
internal override void Set()
{
//Do a full set here
}
}
Create a base class, then let your types handle what they are supposed to set. Create a new on for your ThinSetDTO and override again.
Instead, I would prefer extension method by declaring all properties in Set class and modifying the properties by passing required parameters. Otherwise initialize a baseDTO and have various versions by adding required properties and call extension method to create required version DTO and return baseDTO.
public static Set SetDto(this Set set, bool isThin)
{
if(isThin)
{
}
return objSet;
}
A common solution to this is to have the repository (or equivalent) return the 'flavor' of the DTO/entity you want by either having different access methods ie: Get() ... GetSet(), or to enumerate your 'flavors' of the entity in question and pass that to your 'Get' (or equivalent) method ie:
enum ContactCollectionFlavors { Full, CountOnly, CountWithNames .... }
...
foo = ContactRepository.GetByLastName('Jones', ContactCollectionFlavors.CountWithNames);
This can get a little messy, from experience the entity in question should have some way of knowing what 'flavor' it is, which smells bad since it breaks encapsulation and seperation of concerns - but in my opinion its better hold your nose and keep some out of band data, so that later you can have lazy loading of the entity allowing you to turn 'light flavors' into fully populated entities.

Hash a delegate function in C#

How can I get a hash of a delegate function in C#. I want to be able to tell if different delegates are being sent into my function. My code looks something like this:
public string GetContent(Func<string, bool> isValid)
{
// Do some work
SomeFunctionToHashAFunction(isValid)
}
I would use .GetHashCode() but the .NET framework doesn't guarantee that these will be unique.
EDIT
I have some cached content that I'm validating, but I only want to validate it once. However, if the validation function changes, then I'll need to re-validate the cached content. I'm not sure if the ObjectIdGenerator will work in this instance since I need to identify if two anonymous functions have the same implementation.
By definition, a hash is not guaranteed to be unique, so hashing is not what you want.
Instead, you want to determine whether the instance of the delegate has been "seen" before. To do this, you could use ObjectIdGenerator:
private static readonly ObjectIdGenerator oidg = new ObjectIdGenerator();
public string GetContent(Func<string, bool> isValid)
{
bool firstTime;
oidg.GetId(isValid, out firstTime);
if (!firstTime)
{
...
}
}
However, even with this technique there are some pitfalls to be aware of:
ObjectIdGenerator stores a reference to each object you pass to it
Delegates to the same function are distinct objects, and would therefore return different IDs
Perhaps if you explain what it is you're trying to achieve, there may be a much better way to go about it.
EDIT: Given your updated requirements, I would just define the validation delegate as a property. If the property changes, you know you need to re-validate. GetContent() would therefore not need any parameters:
public Func<string, bool> IsValidHandler
{
get { return this.isValidHandler; }
set
{
this.isValidHandler = value;
this.requiresValidation = true;
}
}
public string GetContent()
{
if (this.requiresValidation && this.isValidHandler != null)
{
// do validation
this.requiresValidation = false;
}
// return content
}
You might even simplify further and do the validation when the IsValidHandler property is set (not in the GetContent method).
There is no (at least non completely hacky) way to hash anonymous function/delegate. Even if function implementation is the same, it might be a closure - so validation outcome might be different based on the context state. Consider this example:
public class Validator
{
public string SomeState { get; set; }
public Validator(string someState)
{
SomeState = someState;
}
public bool IsValid(string input)
{
return input == SomeState;
}
}
// assume your 'input' being validated is "foo"
GetContent((new Validator("foo")).IsValid); // IsValid returns true
GetContent((new Validator("bar")).IsValid); // IsValid returns false
So the only way be sure of whether the validation function is unique would be to have caller define uniqueness of validation implementation and have the caller pass that information to you. You would have to switch to using some kind of validator interface, something along these lines:
//
// Your code
//
public string GetContent(IValidator validator,
IEqualityComparer<IValidator> comparer)
{
// for tracking used validators, use instance
// of 'new HashSet<IValidator>(comparer)'
// this will give you a hashset of unique validators
}
public interface IValidator
{
bool IsValid(string input);
}
//
// Your callers code
//
public class Validator : IValidator
{
// same as Validator class code above
}
public class ValidatorEqualityComparer : IEqualityComparer<Validator>
{
public bool Equals(Validator v1, Validator v2)
{
return GetHashCode(v1) == GetHashCode(v2);
}
public int GetHashCode(Validator v)
{
int hCode = GetMyStringHash(v.GetType().GUID.ToString() + v.SomeState);
// as for GetMyStringHash() implementation for this example,
// you can use some simple string hashing:
// http://www.techlicity.com/blog/dotnet-hash-algorithms.html
return hCode;
}
}
Then you can call your method like this:
GetContent(new Validator("foo"), new ValidatorEqualityComparer());
So the most important part to note here, is that when implementing ValidatorEqualityComparer.GetHashCode() you use validator object state (object value based) hashing. Only this will ensure true uniqueness of validation logic.
Hashes are not intended to be unique. In terms of equality, the only thing you can use them for is to determine whether two objects are not the same. As such, they can be used as a quick first test; if the hashes are different, there is no use to do any further comparisons; the two objects are not the same. If the hashes do match, the objects may be the same, but they may also not be, so you need to perform some deeper analysis in order to determine equality.
Why not just use HashSet to store delegates? Then you can just use .Contains(isValid) to check if the delegate has been given already.
In other words, someone already solved this problem. No reason for you to also solve it.
GetHashCode WILL be unique between different object to a factor of 2^122, that seems pretty safe.
Otherwise, create a class, add a func property, and a bool that is, HasBeenSeen.
Should get the job done.

Best practice for giving back extra information from a Validate function

I have a class Employee. I want to be able to Validate() it before I save it to make sure all the fields have been populated with valid values.
The user of the class may call Validate() before they call Save() or they may call Save() directly and Save() will then call Validate() and probably throw an Exception if validation fails.
Now, my (main) question is this;
If my Validate() function returns a simple bool then how do I tell the user of the class what is wrong, i.e. "Email not filled in", "ID not unique" etc. For the purposes of this I just want the error strings to pass to the human user, but the principle is the same if I wanted a list of error codes (except that makes the use of a bitmap more logical).
I could use an Out paramater in my Validate function but I understand this is frowned upon.
Rather than returning a bool, I could return a string array from my function and just test if it was empty (meaning no errors) - but that seems messy and not right.
I could create a Struct just to return from this method, including a bool and a string array with error messages, but just seems clunky.
I could return a bitmap of error codes instead of a bool and look it up, but that seems rather excessive.
I could create a public property "ValidationErrors" on the object which would hold the errors. However, that would rely on me calling Validate() before reading it or explicitly calling Validate from the Property() which is a bit wasteful.
My specific program is in C# but this looks like a fairly generic "best practice" question and one I am sure I should know the answer to. Any advice gratefully received.
I could create a Struct just to return from this method, including a bool and a string array with error messages, but just seems clunky.
Why does it seem clunky? Creating an appropriate type to encapsulate the information is perfect. I wouldn't necessarily use a string to encode such information, though. An enum may be better suited.
An alternative would be to subclass the return type and provide an extra child class for every case – if this is appropriate. If more than one failures may be signalled, an array is fine. But I would encapsulate this in an own type as well.
The general pattern could look like this:
class ValidationInfo {
public bool Valid { get; private set; }
public IEnumerable<Failure> Failures { get; private set; }
}
I would probably go for the bitmap-option. Simply
[Flags]
public enum ValidationError {
None = 0,
SomeError = 1,
OtherError = 2,
ThirdError = 4
}
...and in the calling code, simply:
ValidationError errCode = employee.Validate();
if(errCode != ValidationError.None) {
// Do something
}
Seems nice and compact to me.
I would follow the pattern of the TryParse methods and use a method with this signature:
public bool TryValidate(out IEnumerable<string> errors) { ... }
Another option is to pull the validation code out of the object into its own class, possibly building on the Specification pattern.
public class EmployeeValidator
{
public bool IsSatisfiedBy(Employee candidate)
{
//validate and populate Errors
}
public IEnumerable<string> Errors { get; private set; }
}
I have found it a good approach to simply have a method (or a property, since C# has nice support for that) which returns all validation error messages in some kind of sensible, easy to use format, such as a list of strings.
This way you can also keep your validate method returning bools.
Sounds like you need a generic class:
public sealed class ValidationResult<T>
{
private readonly bool _valid; // could do an enum {Invalid, Warning, Valid}
private readonly T _result;
private readonly List<ValidationMessage> _messages;
public ValidationResult(T result) { _valid = true; _result = result; _messages = /* empty list */; }
public static ValidationResult<T> Error(IEnumerable<ValidationMessage> messages)
{
_valid = false;
_result = default(T);
_messages = messages.ToList();
}
public bool IsValid { get { return _valid; } }
public T Result { get { if(!_valid) throw new InvalidOperationException(); return _result; } }
public IEnumerable<ValidationMessage> Messages { get { return _messages; } } // or ReadOnlyCollection<ValidationMessage> might be better return type
// desirable things: implicit conversion from T
// an overload for the Error factory method that takes params ValidationMessage[]
// whatever other goodies you want
// DataContract, Serializable attributes to make this go over the wire
}
You could take a look at Rockford Lhotka's CSLA which has extensive business rule/validation tracking forr business objects in it.
www.lhotka.net
I agree with Chris W. I asked the same questions, before reading Rocky`s Expert C# Business Objects.
He has a brilliant way of handling business validation rules. The validation is done after each property is set. Whenever a rule is broken, the object`s state become InValid.
Your business class can implement the IDataError interface. Binding your UI controls to your business object properties will then notify your ErrorProvider control of any broken rules on your object.
I would really recommend you take the time and look at the validation section.
We are using spring validation together with an Windows Forms error provider.
So our validation function returns a dictionary with a control id and an error message (for every validation error). The error provider shows the error message in a pop up field near the control which caused the error.
I used some other validation schemes in the past - but this one works really well.

Categories

Resources