Design – How to program for constraints/rules

constructsdesigndesign-patternsidiomsrules-and-constraints

First the background, during interviews in the past, many times I have been asked to design some or other variation of card game as programming puzzle, and I have tried to design it in OO way, but I have never been satisfied with my solutions. However it was not until recently that I realized that I had been approaching the problem from the wrong direction. Specifically I was trying to solve the problem by modeling individual card as an object.

Problem with this is individual cards don't have any non-trivial intrinsic behavior and therefore are not suitable (or primary) candidate as objects. What is interesting and important about cards are rules and constraints, such as there could be only four suits, or only thirteen cards in each suit. Of course, then there are any number of rules for games.

So my questions are

  1. Are there any idioms/constructs/patterns to program for rules & constraints.
  2. How many in 1 can be applied in conjunction with OO paradigm.

Best Answer

These guidelines/idioms are called Constrained Programming, which is not easy thing to do. It is used for modeling and solving combinatorial problems (NP-hard, NP-complete). I can recommend you one book - Principles of Constraint Programming. This book is one of the best books on the subject, but, still, after reading it you still won't be able to apply it in practice.
But, you will be able to do that by getting familiar yourself with Gecode - a toolkit for developing constraint-based systems and applications. Gecode provides a constraint solver with state-of-the-art performance while being modular and extensible.
I can say that this subject is very interesting, I'd say one of the best courses I had during my studies. Btw, the author of Gecode, was my professor, so I was very lucky :)