Questions tagged [defensive-programming]

Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software in spite of unforeseeable usage of said software. Defensive programming techniques are used especially when a piece of software could be misused mischievously or inadvertently to catastrophic effect.

defensive-programming
Filter by
Sorted by
Tagged with
341 votes
24 answers
51k views

What's the purpose of using braces (i.e. {}) for a single-line if or loop?

I'm reading some lecture notes of my C++ lecturer and he wrote the following: Use Indentation // OK Never rely on operator precedence - Always use parentheses // OK Always use a { } block -...
JAN's user avatar
  • 21.6k
266 votes
20 answers
77k views

When should I use Debug.Assert()?

I've been a professional software engineer for about a year now, having graduated with a CS degree. I've known about assertions for a while in C++ and C, but had no idea they existed in C# and .NET at ...
Nicholas Mancuso's user avatar
105 votes
14 answers
45k views

Techniques for obscuring sensitive strings in C++

I need to store sensitive information (a symmetric encryption key that I want to keep private) in my C++ application. The simple approach is to do this: std::string myKey = "...
Thomi's user avatar
  • 11.7k
75 votes
7 answers
16k views

Erlang's let-it-crash philosophy - applicable elsewhere?

Erlang's (or Joe Armstrong's?) advice NOT to use defensive programming and to let processes crash (rather than pollute your code with needless guards trying to keep track of the wreckage) makes so ...
Andrew Matthews's user avatar
48 votes
4 answers
63k views

Is it possible that Java String.split can return a null String[]

Is it possible for split to return a null String[]? I am curious as I want to try to be as defensive as possible in my code without having unnecessary checks. The code is as follows: String[] ...
Woot4Moo's user avatar
  • 24.2k
47 votes
1 answer
28k views

When to make constructor explicit in C++ [closed]

After reading the following blog : http://xania.org/200711/ambiguous-overloading I started asking myself "should I not always explicit define my constructors?" So I started reading more than found ...
oopsi's user avatar
  • 1,999
45 votes
12 answers
10k views

0xDEADBEEF equivalent for 64-bit development?

For C++ development for 32-bit systems (be it Linux, Mac OS or Windows, PowerPC or x86) I have initialised pointers that would otherwise be undefined (e.g. they can not immediately get a proper ...
Peter Mortensen's user avatar
38 votes
12 answers
18k views

Does wrapping everything in try/catch blocks constitute defensive programming?

I have been programming for the last 3 years. When I program, I use to handle all known exceptions and alert the user gracefully. I have seen some code recently which has almost all methods wrapped ...
user avatar
38 votes
14 answers
3k views

How defensively should I program? [closed]

i was working with a small routine that is used to create a database connection: Before public DbConnection GetConnection(String connectionName) { ConnectionStringSettings cs= ...
Ian Boyd's user avatar
  • 251k
36 votes
9 answers
34k views

How to hide strings in a exe or a dll?

I discovered that it is possible to extract the hard-coded strings from a binary. For example the properties view of Process Explorer displays all the string with more than 3 characters. Here is the ...
Winz's user avatar
  • 506
31 votes
5 answers
10k views

Is this code defensive programming, or bad practice? [closed]

I have this debate with my colleague about this piece of code: var y = null; if (x.parent != null) y = x.parent.somefield; My point of view is that in the place where the code is, x.parent ...
Allen Zhang's user avatar
  • 2,512
23 votes
5 answers
19k views

Copy constructors and defensive copying

What is a copy constructor? Can someone share a small example that can be helpful to understand along with defensive copying principle?
user2094103's user avatar
21 votes
2 answers
1k views

How to combine defensive programming techniques together?

The question I want to ask you is quite wide but in the same time it's very concrete. First, I have to say, that I mostly interested in answers which are applicable in the .net environment. Well, I ...
Igor Soloydenko's user avatar
17 votes
9 answers
2k views

Checklist for Web Site Programming Vulnerabilities

Watching SO come online has been quite an education for me. I'd like to make a checklist of various vunerabilities and exploits used against web sites, and what programming techniques can be used to ...
Mark Harrison's user avatar
15 votes
3 answers
6k views

What's the most defensive way to loop through lines in a file with Perl?

I usually loop through lines in a file using the following code: open my $fh, '<', $file or die "Could not open file $file for reading: $!\n"; while ( my $line = <$fh> ) { ... } However, ...
CanSpice's user avatar
  • 35.3k
14 votes
15 answers
2k views

How "defensive" should my code be?

I was having a discussion with one of my colleagues about how defensive your code should be. I am all pro defensive programming but you have to know where to stop. We are working on a project that ...
user avatar
14 votes
3 answers
2k views

Getting meaningful error messages from fstream's in C++

What is the best way to get meaningful file access error messages, in a portable way from std::fstreams ? The primitiveness of badbits and failbits is getting to be bit annoying. I have written my own ...
Hassan Syed's user avatar
  • 20.3k
13 votes
2 answers
18k views

How to use the Either type in C#?

Zoran Horvat proposed the usage of the Either type to avoid null checks and to not forget to handle problems during the execution of an operation. Either is common in functional programming. To ...
SuperJMN's user avatar
  • 13.7k
12 votes
9 answers
2k views

Test Cases AND assertion statements

The code in this question made me think assert(value>0); //Precondition if (value>0) { //Doit } I never write the if-statement. Asserting is enough/all you can do. "Crash early, crash often" ...
jan's user avatar
  • 1,601
11 votes
3 answers
4k views

Logging with Vala

I am new to Vala programming and have experiences with Java and .NET yet I haven't been able to find anything useful on how to log with Vala. Is there any useful logging facility like log4j or log4net ...
Martin Macak's user avatar
  • 3,661
11 votes
14 answers
3k views

Defensive programming [closed]

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 ...
David's user avatar
  • 14.1k
11 votes
1 answer
492 views

Avoiding accidental capture in structural pattern matching

This example is being discussed as likely "gotcha" when using pattern matching: NOT_FOUND = 400 retcode = 200 match retcode: case NOT_FOUND: print('not found') print(f'...
Raymond Hettinger's user avatar
11 votes
7 answers
286 views

How can I declare derived "shell" classes that do nothing but act as renames?

I have two different kinds of strings I'm passing around and using in my code, and the two are closely related, but should not be confused for one another. I thought I could help myself avoid errors ...
Atario's user avatar
  • 1,380
11 votes
2 answers
4k views

Defensive programming and exception handling

A couple days ago, I have following theoretical questions on the exam: (a) Explain what is meant by defensive programming when dealing with exceptional circumstances that may occur during the ...
kuper006's user avatar
  • 111
10 votes
2 answers
2k views

JavaScript anti-silent techniques to indicate failure

What would be a good way to report errors in JavaScript instead of relying on nulls, and undefineds when errors do occur and a function is unable to proceed forward. I can think of three approaches: ...
Anurag's user avatar
  • 141k
9 votes
5 answers
2k views

Test Cases VS ASSERTION statement

In my most C++ project I heavily used ASSERTION statement as following: int doWonderfulThings(const int* fantasticData) { ASSERT(fantasticData); if(!fantasticData) return -1; // ,,...
popopome's user avatar
  • 12.3k
8 votes
10 answers
6k views

Defensive Programming: Guidelines in Java

I’m from a .NET background and now dabbling in Java. Currently, I’m having big problems designing an API defensively against faulty input. Let’s say I’ve got the following code (close enough): ...
Konrad Rudolph's user avatar
8 votes
8 answers
6k views

Is clone() really ever used? What about defensive copying in getters/setters?

Do people practically ever use defensive getters/setters? To me, 99% of the time you intend for the object you set in another object to be a copy of the same object reference, and you intend for ...
GreenieMeanie's user avatar
8 votes
2 answers
1k views

Why defensive copying with clone represents a security issue?

These days I am reading the second edition of Effective Java by Joshua Bloch. In the item 39 he mentions that it is a good idea to make defensive copies of mutable objects passed as arguments, say in ...
Efraim J Lopez's user avatar
8 votes
2 answers
842 views

Editor templates for defensive programming

Recently I worked on FindBugs warnings about exposing internal state, i.e. when a reference to an array was returned instead of returning a copy of the array. I created some templates to make ...
Daniel Hiller's user avatar
7 votes
14 answers
2k views

How defensive should you be? [duplicate]

Possible Duplicate: Defensive programming We had a great discussion this morning about the subject of defensive programming. We had a code review where a pointer was passed in and was not ...
TERACytE's user avatar
  • 7,673
7 votes
8 answers
836 views

How to avoid key-loggers when authenticating access

As per the title really, just what can be done to defeat key/keystroke logging when authenticating access? I have just posted a related question (how-to-store-and-verify-digits-chosen-at-random-from-...
andora's user avatar
  • 1,336
7 votes
9 answers
2k views

Should I leave an unreachable break in a case where I throw an exception?

Is it silly of me to leave unreachable break statements in a case that just throws an Exception anyway? The defensive part of me wants to leave it there in the event that the logic changes. Another ...
Tim Lehner's user avatar
  • 15.1k
7 votes
3 answers
2k views

Why are fail fast style programs shorter than defensive style programs?

I have read about how the fail-fast style of programming in languages like Erlang end up with much shorter programs than the defensive style found in most other languages. Is this correct for all ...
6 votes
6 answers
2k views

Does defensive programming violate the DRY principle?

Disclaimer: I am a layperson currently learning to program. Never been part of a project, nor written anything longer than ~500 lines. My question is: does defensive programming violate the Don't ...
jkeys's user avatar
  • 3,893
6 votes
7 answers
583 views

web application attacks and must have defence methods

What is your must have defence methods to common web attacks like XSS, Sql Injection, Denial of Service, etc. ? Edit : I collected your responses under descriptions from Wikipedia. And I add some ...
Canavar's user avatar
  • 47.9k
6 votes
2 answers
278 views

How well are Cocoa UI and general framework elements protected against malicious attacks?

So far I had little concern about overall security considerations, because I have been developing only promotional and uncritical iPhone apps. Currently, however, I'm working on a Mac application ...
Toastor's user avatar
  • 8,990
5 votes
9 answers
1k views

How can I program defensively in Ruby?

Here's a perfect example of the problem: Classifier gem breaks Rails. ** Original question: ** One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's ...
James A. Rosen's user avatar
5 votes
5 answers
930 views

C# anonymous backing fields with non-auto properties

I want to make a private member variable that is private even to the class that owns it, and can ONLY be accessed by its getters and setters. I know you can do this with auto-properties like private ...
Bryan Hart's user avatar
5 votes
2 answers
2k views

How to detect QObject::moveToThread() failure in Qt5?

The documentation on QObject::moveToThread() for Qt5.3 explains that the moveToThread() method can fail if the object has a parent. How would I detect this failure in my code? I realize that simply ...
Mr. Developerdude's user avatar
5 votes
3 answers
1k views

TDD vs Defensive Programming

Uncle Bob says: "Defensive programming, in non-public APIs, is a smell, and a symptom, of teams that don't do TDD." I am wondering how TDD can avoid an (internal) function to be used in an ...
offline's user avatar
  • 211
5 votes
3 answers
4k views

XmlSerializer - How can I set a default when deserializing an enum?

I have a class that looks like this (heavily simplified): public class Foo { public enum Value { ValueOne, ValueTwo } [XmlAttribute] public Value Bar { get; set; }...
NeilD's user avatar
  • 2,288
5 votes
2 answers
580 views

Adding *copies* of entries from Java Map<String, Object> propertyMap

I would like to add copies of a propertyMap to my propertyMap: public void addProperties(Map<String, Object> propertyMap) { for (Map.Entry<String, Object> propertyEntry : ...
Robottinosino's user avatar
5 votes
2 answers
439 views

How do you manage external dependencies for your application?

There are many types of external dependencies. Interfacing with external applications, components or services (e.g. Outlook to send emails, TWAIN or WIA for scanning, ActiveX objects and Web services ...
Ola Eldøy's user avatar
  • 5,838
5 votes
2 answers
931 views

Inefficiency of defensive copy in Java [closed]

I'm a longtime C/C++ programmer who's learning Java. I've read about the problem of breaking encapsulation by having an accessor method that returns a reference to a private field. The standard Java ...
Dave Beal's user avatar
4 votes
7 answers
240 views

C Syntax Question

Is it considered bad coding to put a break in the default part of a switch statement? A book I was reading said that it was optional but the teacher counted off for using it.
shinjuo's user avatar
  • 20.8k
4 votes
2 answers
359 views

Will the macro `assert` be removed in C++20?

According to cppreference, assert will be used as a C++ attribute. However, there already exist tons of projects heavily dependent on the macro assert, is there any bad effect?
xmllmx's user avatar
  • 40.9k
4 votes
2 answers
276 views

How to avoid defensive if conditions in python?

I am writing a code which tries to dig deep into the input object and find out a value lying inside that object. Here is a sample code: def GetThatValue(inObj): if inObj: level1 = inObj....
Sadanand Upase's user avatar
4 votes
2 answers
232 views

Objective-C defensive copying in accessor methods

Coming from a Java background, I'm having trouble figuring out ways to program defensively in Objective-C. Assuming SomeClass is mutable and provides a copy method, this is a typical piece of code I'd ...
Dmitry's user avatar
  • 161
4 votes
0 answers
635 views

Nullable reference types and null-oblivious libraries

Recently we started to use C# nullable reference types in our projects. Of course in our project, we use nuget libraries that don't support nullable reference types. What is the best practice of using ...
Astemir Almov's user avatar