- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Defensive R Programming
Defensive programming is a software development practice that involves designing and implementing code in a way that anticipates and prevents errors and vulnerabilities. In R programming, defensive programming involves using techniques and strategies to ensure that your R code is robust, reliable, and secure.
By the word “Defensive” in defensive programming, most of you might be confused about whether it means writing such a code that doesn’t fail at all. But the actual definition of “Defensive programming” is writing such a code that fails properly. By “failing properly”, we mean −
If the code fails, then it should be able to fail instantly if there are some operations and it’s quite expensive to work on them.
If the code fails, then it should be able to able to release all the resources and do-not write any files, etc.
If the code fails, then it should display an error message with a proper description.
If the code fails, then it should be handled properly. As a developer, you are required to debug it or get more insights into it.
Defensive R Programming Techniques
We will now discuss various techniques that falls under defensive R programming −
Diagnostic Messages
Syntax
R allows us message() function using which we can display diagnostic messages on the console. This function has the following syntax,
message(diagonostic_message)
Here diagnostic_message is the message that you want to display.
Example
Now let us consider a program given below −
# Defining myFunction() myFunction <- function() { # Diagnostic message message("You need to run system updates!") # Doing some work number1 = 10 number2 = 20 sum = number1 + number2 } # Calling function myFunction()
Output
You need to run system updates!
As you can see in the output, message has been displayed on the console.
Example
We can also define verbosity manually to make it a particular software or program feature rich as −
# Defining myFunction() myFunction <- function(verbose) { # Diagnostic message if(verbose) message("You need to run system updates!") # Doing some work number1 = 10 number2 = 20 sum = number1 + number2 } # Calling function myFunction(verbose = TRUE)
Output
You need to run system updates!
As you can see in the output, message has been displayed on the console.
Syntax
It is important note that sometimes we need to suppress annoying messages in a program. For this purpose, R provides us suppressMessages() function in R. This function has the following syntax −
suppressMessages(func())
Example
Here func() is the function in which messages are declared.
# Defining myFunction() myFunction <- function() { # Diagnostic message message("You need to run system updates!") # Doing some work number1 = 10 number2 = 20 sum = number1 + number2 # Display the sum print(sum) } # Suppress message suppressMessages(myFunction())
Output
[1] 30
As you can see in the output, message has been displayed on the console.
Warning Messages
Syntax
A warning message in a program is used to highlight potential problems. R provides us warning() function using which we can display warning messages on console for better defensive programming. This function has the following syntax,
warning(warning_message)
Here warning_message is the message to be displayed.
Example
Now let us consider a program below −
# Defining myFunction() myFunction <- function() { # Diagnostic message warning("Something wrong might happen in you code!") # Doing some work number1 = 10 number2 = 20 sum = number1 + number2 } # Calling function myFunction()
Output
Warning message: In myFunction() : Something wrong might happen in you code!
As you can see in the output, warning message has been displayed on the console.
Error Messages
Syntax
When our code fails and an error occurs in that case we should print error message to console. For this purpose, R provides us error() function. This function has the following syntax,
error(error_message)
Here error_message is error message to be displayed.
Example
Now consider the following program demonstrating the working of stop() function −
# Defining myFunction() myFunction <- function() { # Diagnostic message stop("Something wrong has happened in your code!") # Doing some work number1 = 10 number2 = 20 sum = number1 + number2 } # Calling function myFunction()
Output
Error in myFunction() : Something wrong has happened in your code!
As you can see in the output, error message has been displayed on the console.
Checking Conditions with stopifnot()
Example
We have discussed before in this article that we can use stop() function to create an error in R. Now let us consider a program below that check whether a vector hold values of character type or not.
# Creating a vector myVector <- 100 # Check whether the vector hold character value # If not print error to console # using stop() function if (!is.character(myVector)) { stop("Error found! myVector must be a character vector.") }
Output
Error: Error found! myVector must be a character vector.
As you can see in the output, error message has been displayed on the console.
The disadvantage of the above program is that if we have multiple conditions to evaluate then it might take many number of lines of code to check for all the conditions and therefore unnecessarily increase the code size of the program.
Syntax
R provides us stopifnot() function using which we can handle multiple conditions. This function has the following syntax,
stopifnot(condition)
This function accepts condition as a parameter and return a boolean value and corresponding error message (if there is some error in the passed condition.
Example
Let us consider an example demonstrating the working of this function −
# Creating a vector myVector <- 100 # Check whether vector hold character value # If not print error to console # using stop() function stopifnot(is.character(myVector))
Output
Error: is.character(myVector) is not TRUE
As you can see in the output since myVector contains integer value therefore error message is displayed on the console.
Writing Tests
In R, we have assertthat package that can be used for testing. If you have not installed this package yet the you may use the following command in R and install the package using CRAN −
install.packages("assertthat")
Syntax
The assertthat package provides us assert_that() function using which we can test any logical statement. This function has the following syntax −
assert_that(condition)
It accepts a logical condition as a parameter
Example
Consider a program below that demonstrates the working of this function −
# Importing library library(assertthat) # Defining two integer variables number1 = 100 number2 = 150 # Make sure that number1 is greater than number2 assert_that(number1 > number2)
Output
Error: number1 not greater than number2
As you can see in the output since number1 is less than number2 therefore error message is displayed on the console.
Syntax
The assert_that() function can also be applied to compare two vectors value but its syntax is slightly different from the above one −
assert_that(all(condition))
It accepts a logical condition as a parameter.
Example
Consider the following program that compares two vector values using this function −
# Importing library library(assertthat) # Defining two vectors of integer type vector1 <- c(10, 20, 30, 40) vector2 <- c(50, 60, 70, 80) # Make sure that all the elements # of vector1 are lesser than the # corresponding elements of vector2 assert_that(all(vector1 < vector2))
Output
[1] TRUE
Conclusion
In this tutorial, we discusses about various defensive programming techniques in R. I hope this has helped you to strengthen your knowledge in the field of data science.