views:

108

answers:

3

Often in programming, it is a very common requirement that some piece of functionality will require a lot of conditional logic, but not quite enough to warrant a rules engine.

For example, testing a number is divisible by x but also a multiple of something, a factor of something else, a square root of something, etc. As you can imagine, something along these lines will easily involve a lot of ifs/elses.

While it is possible to reduce the clutter with more modern programming techniques, how do you quickly and, in a calculated fashon, deduce the required ifs/elses?

For example, in a program to deduce the necessary quote for a car insurance prospective customer (rules engines aside btw), there would be conditional logic for age, location, driving points, what age those points are collected at, etc. Is there any mental technique to quickly deduce the redundant conditional branches? Is it just plain experience and no special mental technique? This is important because pair programming there is a lot of noise and thus difficult to actually think something through or even get enough time to implement the idea.

Thanks

A: 

I would say you should use propositional logic. Suggest that: q = age is greater than 18
p = location is within 10 miles
r = driving points are less than 3
s = age is less than 18 when points are collected

you could say...
(^ is AND)
if (q ^ p ^ r ^ s) {
//you are eligible or something!
} else {
//get outta here
}

0x90
+3  A: 

I would suggest that trying to do this sort of thing in your head is asking for trouble, and trying to do it with a partner is going to make it much worse. Sometimes you have to sit and think and even make some notes on paper. If you don't like propositional logic, try decision tables.

High Performance Mark
That's the only reasonably useful answer I can imagine here.
JasonFruit
Good idea. I just need an example of using decision tables to model the logic and then the actual code.
dotnetdev
@dotnetdev: follow the link ?
High Performance Mark
I did, I was just hoping for an end-to-end example but I get the point. Very good technique!
dotnetdev
A: 

I would add simple, readable, short methods, such as:

IsMinor(..)  
IsRecordClean(..)

And then use them in conjunction to create new methods with meaningful names, such as:

IsMeetingPreReqs(..)   //which checks several "simple" conditions
IsValidForInsurance(..)   

(Sorry for the examples, I'm struggling with my English here, but you get the point..)

IMO that will make your code much clearer, and thus reduce the chances of being confused by distractions.
Not mental per se, but kinda..

Oren A
I don't think `IsDivisibleAndMultipleOf(..)` is a good name at all, as it's essentially meaningless except to test a seemingly arbitrary condition. In general, if you're tempted to put an "and" in function name, you're writing a bad function.
David Thornley
That method doesn't exist any more!
Oren A