Offensive vs Defensive Programming

ayozzhero

Well-known member
Joined
Apr 6, 2005
Messages
186
Location
Malaysia
Programming Experience
1-3
I know the term Defensive Programming, but I do not know what is the Offensive one :(

I am not asking which one is better... just wanna know what, coz when I googled, I couldn't find anything.

A stupid question it might be, but thank you for replying :D
 
It's a term I coined to mean being proactive to prevent errors from happening in the first pace. Validate the data... ensure everything is OK. Using error handles only for those extreme exception cases.

Defensive programming is the other side. It's when you start using error handling to control your program flow.

Does that help any?

-tg
 
Sounds like I have the wrong picture here. Look at this case:

User keys in filename to be opened. Instead of directly instructing the system to open the files (which may or may not exist), we check the file existence first. If the file is unavailable, a messagebox is poped up. If the file exist, we instruct system to open the file...

I always thought that this is defensive programming... From what you've explained, I understand that defensive programming is a kinda waiting for the error to happen when we instruct system to open the file (and the file does not exist), catch the error and inform user that the file does not exist.

I've been in darkness for such a long time :confused:
 
It seems I need to come up with new terms. My use ( & definition of defensive programing) is basicaly the opposite of what the Wikipedia has as its definition. http://en.wikipedia.org/wiki/Defensive_programming

Given your senario there, here's how DP vs OP would work (based on my definitions)
Defensive:
File is requested. System opens the file, file is not there, so an error is generated. The error is handled and a message shown to the user.
In this case, the system is being reactive, having to defend itself from the errors. IMHO this isn't the way to do it.

Ofensive:
File is requested. System checks to see if the file exists. If not, message to the user. If it does exist, it is opened.
No errors, no error handling. Program flow is natural and clean.

But maybe I need to rethink the terms and find something a bit more descriptive.

-tg
 
Back
Top