Creating a Fluent API


 

Resources: http://code.google.com/p/nasserter/

 

See Also: http://fluentvalidation.codeplex.com/ , http://nbuilder.org/ , 

 

 

    public static class Something

    {

        public static IConstraint<T> Has<T>(T something)

        {

            return new ConstraintImpl<T>(something);

        }

    }

 

    public class ConstraintImpl<T> : IConstraint<T>

    {

        private readonly T _something;

 

        public ConstraintImpl(T something)

        {

            _something = something;

        }

 

        public IConstraint<T> IsGreaterThan<TGt>(Func<T, TGt> callback, TGt greaterThan)

            where TGt : IComparable<TGt>

        {

            if (callback.Invoke(_something).CompareTo(greaterThan) >= 0) throw new ApplicationException("jkl");

 

            return this;

        }

 

        public IConstraint<T> IsTrue(Predicate<T> callback)

        {

            if (!callback(_something)) throw new ApplicationException("asdf");

 

            return this;

        }

    }

 

    public interface INestedConstraint<T, TParent>

    {

 

    }

 

    public interface IConstraint<T> : IHideObjectMembers

    {

        IConstraint<T> IsGreaterThan<TGt>(Func<T, TGt> callback, TGt greaterThan)

            where TGt : IComparable<TGt>;

 

        IConstraint<T> IsTrue(Predicate<T> x);

    }

 

 

 

            var customer = new Customer {Id = 200};

 

            Something.Has(customer)

                .IsTrue(x => x.Id == 200)

                .IsGreaterThan(x => x.Id, 199);