<p>When writing code do you consciously program defensively to ensure high program quality and to avoid the possibility of your code being exploited maliciously, e.g. through buffer overflow exploits or code injection ?</p>

<p>What's the "minimum" level of quality you'll always apply to your code ?</p>

[{'answer_id': 6850, 'author': 'EndangeredMassa', 'author_id': 106, 'author_profile': 'https://Stackoverflow.com/users/106', 'pm_score': 0, 'selected': False, 'text': '<p>I always work to prevent things like injection attacks. However, when you work on an internal intranet site, most of the security features feel like wasted effort. I still do them, maybe just not as well.</p>\n'}, {'answer_id': 6857, 'author': 'Vaibhav', 'author_id': 380, 'author_profile': 'https://Stackoverflow.com/users/380', 'pm_score': 0, 'selected': False, 'text': '<p>Well, there is a certain set of best practices for security. At a minimum, for database applications, you need to watch out for SQL Injection.</p>\n\n<p>Other stuff like hashing passwords, encrypting connection strings, etc. are also a standard.</p>\n\n<p>From here on, it depends on the actual application.</p>\n\n<p>Luckily, if you are working with frameworks such as .Net, a lot of security protection comes built-in.</p>\n'}, {'answer_id': 6861, 'author': 'Justin Yost', 'author_id': 657, 'author_profile': 'https://Stackoverflow.com/users/657', 'pm_score': 0, 'selected': False, 'text': "<p>You have to always program defensively I would say even for internal apps, simply because users could just through sheer luck write something that breaks your app. Granted you probably don't have to worry about trying to cheat you out of money but still. Always program defensively and assume the app will fail.</p>\n"}, {'answer_id': 6862, 'author': 'abyx', 'author_id': 573, 'author_profile': 'https://Stackoverflow.com/users/573', 'pm_score': 5, 'selected': True, 'text': '<p>In my line of work, our code has to be top quality.<br>\nSo, we focus on two main things:</p>\n\n<ol>\n<li>Testing</li>\n<li>Code reviews</li>\n</ol>\n\n<p>Those bring home the money.</p>\n'}, {'answer_id': 6866, 'author': 'Tom', 'author_id': 20, 'author_profile': 'https://Stackoverflow.com/users/20', 'pm_score': 2, 'selected': False, 'text': '<p>Similar to abyx, in the team I am on developers always use unit testing and code reviews. In addition to that, I also aim to make sure that I don\'t incorporate code that people <em>may</em> use - I tend to write code only for the basic set of methods required for the object at hand to function as has been spec\'d out. I\'ve found that incorporating methods that may never be used, but provide functionality can unintentionally introduce a "backdoor" or unintended/unanticipated use into the system.</p>\n\n<p>It\'s much easier to go back later and introduce methods, attributes, and properties for which are asked versus anticipating something that may never come.</p>\n'}, {'answer_id': 6975, 'author': 'Mike Minutillo', 'author_id': 358, 'author_profile': 'https://Stackoverflow.com/users/358', 'pm_score': 0, 'selected': False, 'text': "<p>Using Test Driven Development certainly helps. You write a single component at a time and then enumerate all of the potential cases for inputs (via tests) before writing the code. This ensures that you've covered all bases and haven't written any <strong><em>cool</em></strong> code that no-one will use but might break.</p>\n\n<p>Although I don't do anything formal I generally spend some time looking at each class and ensuring that:</p>\n\n<ol>\n<li>if they are in a valid state that they stay in a valid state</li>\n<li>there is no way to construct them in an invalid state</li>\n<li>Under exceptional circumstances they will fail as gracefully as possible (frequently this is a cleanup and throw)</li>\n</ol>\n"}, {'answer_id': 7092, 'author': 'itj', 'author_id': 888, 'author_profile': 'https://Stackoverflow.com/users/888', 'pm_score': 0, 'selected': False, 'text': "<p>It depends.</p>\n\n<p>If I am genuinely hacking something up for my own use then I will write the best code that I don't have to think about.  Let the compiler be my friend for warnings etc. but I won't automatically create types for the hell of it.</p>\n\n<p>The more likely the code is to be used, even occasionally, I ramp up the level of checks.</p>\n\n<ul>\n<li>minimal magic numbers</li>\n<li>better variable names</li>\n<li>fully checked &amp; defined array/string lengths</li>\n<li>programming by contract assertions</li>\n<li>null value checks</li>\n<li>exceptions (depending upon context of the code)</li>\n<li>basic explanatory comments</li>\n<li>accessible usage documentation (if perl etc.)</li>\n</ul>\n"}, {'answer_id': 7097, 'author': 'C. K. Young', 'author_id': 13, 'author_profile': 'https://Stackoverflow.com/users/13', 'pm_score': 0, 'selected': False, 'text': '<p>I\'ll take a different definition of defensive programming, as the one that\'s advocated by <em><a href="http://java.sun.com/docs/books/effective/" rel="nofollow noreferrer">Effective Java</a></em> by Josh Bloch. In the book, he talks about how to handle mutable objects that callers pass to your code (e.g., in setters), and mutable objects that you pass to callers (e.g., in getters).</p>\n\n<ul>\n<li>For setters, make sure to clone any mutable objects, and store the clone. This way, callers cannot change the passed-in object after the fact to break your program\'s invariants.</li>\n<li>For getters, either return an immutable view of your internal data, if the interface allows it; or else return a clone of the internal data.</li>\n<li>When calling user-supplied callbacks with internal data, send in an immutable view or clone, as appropriate, unless you intend the callback to alter the data, in which case you have to validate it after the fact.</li>\n</ul>\n\n<p>The take-home message is to make sure no outside code can hold an alias to any mutable objects that you use internally, so that you can maintain your invariants.</p>\n'}, {'answer_id': 7130, 'author': 'epatel', 'author_id': 842, 'author_profile': 'https://Stackoverflow.com/users/842', 'pm_score': 1, 'selected': False, 'text': '<p>I\'d recommend being defensive for data that enter a "component" or framework. Within a "component" or framework one should think that the data is "correct".</p>\n\n<p>Thinking like this. It is up to the caller to supply correct parameters otherwise ALL functions and methods have to check every incomming parameter. But if the check is only done for the caller the check is only needed once. So, a parameter should be "correct" and thus can be passed through to lower levels.</p>\n\n<ol>\n<li>Always check data from external sources, users etc</li>\n<li>A "component" or framework should always check incomming calls.</li>\n</ol>\n\n<p>If there is a bug and a wrong value is used in a call. What is really the right thing todo? One only have an indication that the "data" the program is working on is wrong and some like ASSERTS but others want to use advanced error reporting and possible error recovery. In any case the data is found to be faulty and in few cases it\'s good to continue working on it. (note it\'s good if servers don\'t die at least)</p>\n\n<p>An image sent from a satellite might be a case to try advanced error recovery on...an image downloaded from the internet to put up an error icon for...</p>\n'}, {'answer_id': 7162, 'author': 'Zooba', 'author_id': 891, 'author_profile': 'https://Stackoverflow.com/users/891', 'pm_score': 0, 'selected': False, 'text': "<p>I am very much of the opinion that correct programming will protect against these risks. Things like avoiding deprecated functions, which (in the Microsoft C++ libraries at least) are commonly deprecated because of security vulnerabilities, and validating everything that crosses an external boundary.</p>\n\n<p>Functions that are only called from your code should not require excessive parameter validation because you control the caller, that is, no external boundary is crossed. Functions called by other people's code should assume that the incoming parameters will be invalid and/or malicious at some point.</p>\n\n<p>My approach to dealing with exposed functions is to simply crash out, with a helpful message if possible. If the caller can't get the parameters right then the problem is in their code and they should fix it, not you. (Obviously you have provided documentation for your function, since it is exposed.)</p>\n\n<p>Code injection is only an issue if your application is able to elevate the current user. If a process can inject code into your application then it could easily write the code to memory and execute it anyway. Without being able to gain full access to the system code injection attacks are pointless. (This is why applications used by administrators should not be writeable by lesser users.)</p>\n"}, {'answer_id': 10115, 'author': 'Nick', 'author_id': 1236, 'author_profile': 'https://Stackoverflow.com/users/1236', 'pm_score': 0, 'selected': False, 'text': "<p>In my experience, positively employing defensive programming does not necessarily mean that you end up improving the quality of your code. Don't get me wrong, you need to defensively program to catch the kinds of problems that users will come across - users don't like it when your program crashes on them - but this is unlikely to make the code any easier to maintain, test, etc.</p>\n\n<p>Several years ago, we made it policy to use assertions at all levels of our software and this - along with unit testing, code reviews, etc. plus our existing application test suites - had a significant, positive effect on the quality of our code.</p>\n"}, {'answer_id': 10150, 'author': 'Andrew Grant', 'author_id': 1043, 'author_profile': 'https://Stackoverflow.com/users/1043', 'pm_score': 1, 'selected': False, 'text': '<p>I recommend people write code that is fascist in the development environment and benevolent in production. </p>\n\n<p>During development you want to catch bad data/logic/code as early as possible to prevent problems either going unnoticed or resulting in later problems where the root cause is hard to track.</p>\n\n<p>In production handle problems as gracefully as possible. If something really is a non-recoverable error then handle it and present that information to the user. </p>\n\n<p>As an example here\'s our code to Normalize a vector. If you feed it bad data in development it will scream, in production it returns a safety value.</p>\n\n<pre><code>inline const Vector3 Normalize( Vector3arg vec )\n{\n    const float len = Length(vec);\n    ASSERTMSG(len &gt; 0.0f "Invalid Normalization");\n    return len == 0.0f ? vec : vec / len;\n}\n</code></pre>\n'}, {'answer_id': 45275, 'author': 'Tim Williscroft', 'author_id': 2789, 'author_profile': 'https://Stackoverflow.com/users/2789', 'pm_score': 0, 'selected': False, 'text': "<p>Java, Signed JARs and JAAS. </p>\n\n<p>Java to prevent buffer overflow and pointer/stack whacking exploits.</p>\n\n<p>Don't use JNI. ( Java Native Interface) it exposes you to DLL/Shared libraries.</p>\n\n<p>Signed JAR's to stop class loading being a security problem.</p>\n\n<p>JAAS can let your application not trust anyone, even itself.</p>\n\n<p>J2EE has (admittedly limited) built-in support for Role based security.</p>\n\n<p>There is some overhead for some of this but the security holes go away.</p>\n"}, {'answer_id': 1388907, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Simple answer: <strong>It depends</strong>.\nToo much defensive coding <strong>can</strong> cause major performance issues.</p>\n'}]
['https://Stackoverflow.com/questions/6847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/381/']