Object Graph Validation

This sample shows how it is possible to validate an object graph.
The Engine is setup to validate Member and Club objects.
As part of the rules, a Club must have a President and the President must be a valid Member.
Also, all members of the Club must be valid members.

    class Program
    {
        public class Member
        {
            public string Name { get; set; }
            public string Email { get; set; }

            public Member(string name, string email)
            {
                this.Name = name;
                this.Email = email;
            }
        }

        public class Club
        {
            private readonly List<Member> _members = new List<Member>();
            public string Name { get; set; }
            public Member President { get; set; }

            public List<Member> Members
            {
                get { return _members; }
            }

            public Club(string name, Member president, params Member[] members)
            {
                this.Name = name;
                this.President = president;
                this._members.AddRange(members);
            }
        }

        static void Main(string[] args)
        {
            Engine engine = new Engine();

            engine.For<Member>()
                .Setup(member => member.Name)
                    .MustNotBeNullOrEmpty()
                .Setup(member => member.Email)
                    .MustNotBeNullOrEmpty();
            
            engine.For<Club>()
                .Setup(club => club.President)
                    .MustNotBeNull()
                    .CallValidate() //Calls engine.Validate for the President.
                .Setup(club => club.Members)
                    .MustNotBeNull()
                    .CallValidateForEachElement(); //Calls engine.Validate() on each element

            var chessClub = new Club("Chess Club"
                , new Member("athoma13", "athoma13@codeplex.com")
                , new Member("Arpad Elo", "arpad@hotmail.com")
                , new Member("Garry Kasparov", "garry@gmail.com")
                , new Member("Bobby Fischer", "bobby@aol.com")
                );
            
            //The club is valid...
            bool isValidClub = engine.Validate(chessClub);
        }
    }

Last edited Sep 6, 2011 at 11:26 AM by athoma13, version 1

Comments

No comments yet.