# How to program for constraints/rules

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.
• I'm not convinced that just because individual cards don't have (as you claim) non-trivial behavior that they cannot be modeled effectively as individual objects. There are programming languages that model everything as an object, even primitive numbers. And there are many examples of lists of trivial objects in programming (which is what your card deck is). Jan 1, 2011 at 20:59
• To put it another way, if you don't store the suit and rank of each card in an object, where will you store it? You can also store the image of each card in the object itself. Seems like a very natural way to do it to me. Jan 1, 2011 at 21:00
• @Robert of course I didn't mean to say you couldn't model individual cards as objects, what I meant was such modelling doesn't address the crux of the problem which are rules and constraints. Even deck can be modeled in terms of these rules and constraints Jan 1, 2011 at 21:02
• @Gaurav: modelling cards as objects sounds like a fine way to treat the cards themselves, but you’re quite right that that doesn’t complete the job of modelling a card game. A card game is a separate thing from the cards used to play it (hence playing cards are used to play lots of different games). Jul 31, 2012 at 16:47
• You are looking for SMT or CSP solvers. Look at existing implementations.
– user
Sep 13, 2013 at 7:58