# Defensive programming & assert

**URL:** https://discourse.julialang.org/t/defensive-programming-assert/8383
**Category:** General Usage
**Created:** [January 15, 2018, 1:49pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383 "2018-01-15T13:49:05Z")
**Posts on this page:** 14
**Page:** 1

<div class="post-metadata">

### Author: ![Vincent\_Picaud](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vincent_picaud/32/3108_2.png) [@Vincent\_Picaud](https://discourse.julialang.org/u/Vincent_Picaud)
#### Post date: [January 15, 2018, 1:49pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/1 "2018-01-15T13:49:05Z")

</div>

I come from the C++ world and I would like to use Julia more often. I generally use a lot of asserts in my code (a “defensive” programming approach), for instance imagine a function reading the first N records of a file. In pseudo C++ code you have something like:

```
 // read N first records
 //
 void read_file_N(std::istream& file_in,const int N) 
 {
      assert(N>=0); // logical error: coder/caller responsibility is involved

      for(i=0;i<N;i++) {
   
           file >> data;

           // coder/caller responsibility is _not_ involved (I/O error)
           //
           if(!data.well_formed()) { 
                throw error("Error in file, data is not well formed"); 
           }
      ...
   }
}

```

There are (at least) **two kind of errors**. Logical ones, **involving coder responsibility** and errors (like corrupted I/O etc.) where **coder is not responsible**. For the first ones I use a lot of **asserts** , for the second one I use **exceptions**. In C/C++ I can easily remove the assert thanks to a compiler flag (-DNDEBUG) thus there is no run-time penalty in production code. However, when I code in Julia (I am quite new with this language) I have the feeling that these two notions are mixed and that we can not take the same approach: AFAIK Julia @assert/assert is close to my C++ exception usage, but there is no Julia equivalent to C++ assert. This is a real problem for me and the way I code.

Do I miss something?  
What can I do to have **a C/C++ equivalent to assert in Julia** (with the constraint that we can remove them in production code)?

---

<div class="post-metadata">

### Author: ![sdanisch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sdanisch/32/1406_2.png) [@sdanisch](https://discourse.julialang.org/u/sdanisch)
#### Post date: [January 15, 2018, 2:00pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/2 "2018-01-15T14:00:26Z")

</div>

you can use something like:

```nohighlight
module MyModule
const DNDEBUG = true
macro c_assert(boolean)
    if DNDEBUG
        :($boolean || error("Assertion $($a) == $($b) failed"))
    end
end
end

julia> using MyModule
julia> @c_assert 1 == 2
ERROR: Assertion 1 == 2 failed

```

With DNDEBUG = false

```nohighlight
julia> test() = @c_assert 1 == 2
test (generic function with 1 method)
julia> test()
julia> @code_llvm test()
define void @julia_test_69494() #0 !dbg !5 {
top:
  ret void
}

```

Note, that this will recompile the optimized version as well, when you change the flag in the source.

---

<div class="post-metadata">

### Author: ![Vincent\_Picaud](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vincent_picaud/32/3108_2.png) [@Vincent\_Picaud](https://discourse.julialang.org/u/Vincent_Picaud)
#### Post date: [January 15, 2018, 2:29pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/3 "2018-01-15T14:29:46Z")

</div>

Thanks for the feedback (and sorry for my first post bad formatting).  
I was thinking to something similar but I thought that maybe there was a special/intergrated Julia way for it.

I think that there is a typo, the macro should be something like

:($boolean || error(“Assertion $boolean failed”))

but this only print “false”, how to print it in its unevaluted form?

---

<div class="post-metadata">

### Author: ![sdanisch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sdanisch/32/1406_2.png) [@sdanisch](https://discourse.julialang.org/u/sdanisch)
#### Post date: [January 15, 2018, 2:37pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/4 "2018-01-15T14:37:14Z")

</div>

Ah yeah, I first had another version.  
Try:

```nohighlight
julia> macro c_assert(boolean)
           if DNDEBUG
               :($(esc(boolean)) || error("Assertion $($(QuoteNode(boolean))) failed"))
           end
       end

```

---

<div class="post-metadata">

### Author: ![Vincent\_Picaud](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vincent_picaud/32/3108_2.png) [@Vincent\_Picaud](https://discourse.julialang.org/u/Vincent_Picaud)
#### Post date: [January 15, 2018, 2:38pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/5 "2018-01-15T14:38:49Z")

</div>

Works great, thanks!

---

<div class="post-metadata">

### Author: ![sdanisch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sdanisch/32/1406_2.png) [@sdanisch](https://discourse.julialang.org/u/sdanisch)
#### Post date: [January 15, 2018, 2:39pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/6 "2018-01-15T14:39:59Z")

</div>

A little less magical:

```nohighlight
macro c_assert(boolean)
      if DNDEBUG
           message = string("Assertion: ", boolean, " failed")
           :($(esc(boolean)) || error($message))
      end
end

```

---

<div class="post-metadata">

### Author: ![NaOH](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/naoh/32/5632_2.png) [@NaOH](https://discourse.julialang.org/u/NaOH)
#### Post date: [January 15, 2018, 2:51pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/7 "2018-01-15T14:51:25Z")

</div>

Reference: [omit assert under `--optimize`; introduce`@check` macro?](https://github.com/JuliaLang/julia/issues/10614)

---

<div class="post-metadata">

### Author: ![Vincent\_Picaud](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vincent_picaud/32/3108_2.png) [@Vincent\_Picaud](https://discourse.julialang.org/u/Vincent_Picaud)
#### Post date: [January 15, 2018, 2:56pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/8 "2018-01-15T14:56:58Z")

</div>

Yes, I have seen that however on my Julia V0.6, @check macro is not found.

---

<div class="post-metadata">

### Author: ![NaOH](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/naoh/32/5632_2.png) [@NaOH](https://discourse.julialang.org/u/NaOH)
#### Post date: [January 15, 2018, 3:20pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/9 "2018-01-15T15:20:49Z")

</div>

Indeed it hasn’t been implemented yet, but it is a popular wanted feature, I’d love built-in support too, just wanted people reading this know.

---

<div class="post-metadata">

### Author: ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)
#### Post date: [January 15, 2018, 9:15pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/10 "2018-01-15T21:15:00Z")

</div>

This is my take on this thread / issue: [https://github.com/JuliaLang/julia/pull/25576](https://github.com/JuliaLang/julia/pull/25576)

---

<div class="post-metadata">

### Author: ![c42f](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/c42f/32/52842_2.png) [@c42f](https://discourse.julialang.org/u/c42f)
#### Post date: [January 15, 2018, 9:29pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/11 "2018-01-15T21:29:57Z")

</div>

Here’s a way this can be done for modules without breaking precompilation.

```julia
module DebugAsserts

export debug_asserts, @dassert

function debug_asserts(m::Module, dodebug::Bool)
    m.eval(:(_debug_enabled() = $dodebug))
    nothing
end

# Like @assert, but only active in debug mode
macro dassert(exs...)
    if !isdefined( __module__ , :_debug_enabled)
        eval( __module__ , :(_debug_enabled() = false))
    end
    quote
        if $ __module__._debug_enabled()
            @assert $(map(esc,exs)...)
        end
    end
end

end

```

---

<div class="post-metadata">

### Author: ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)
#### Post date: [January 15, 2018, 9:37pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/12 "2018-01-15T21:37:34Z")

</div>

> [@c42f](#):
>
> Here’s a way this can be done for modules without breaking precompilation.

AFAIU, The way this works is exploiting that #265 (reliable redefinition of methods) is fixed, this automatically recompiles all dependent functions that use `@dassert` every time `debug_asserts` is called. Depending on how many functions uses `@dassert` (or how many functions are in the call graph of any function that uses it) this will have to recompile a different number of functions but, in the worst case, using `debug_asserts` will cause a full recompilation of the whole package.

---

<div class="post-metadata">

### Author: ![c42f](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/c42f/32/52842_2.png) [@c42f](https://discourse.julialang.org/u/c42f)
#### Post date: [January 15, 2018, 9:48pm UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/13 "2018-01-15T21:48:26Z")

</div>

That’s right, this relies on the compiler to recompile all methods which use `@dassert` when the associated `_debug_enabled` is redefined via #265. You can use this `@dassert` in your own package exactly the same way as `@assert`, but the expression should be completely optimized away unless you call `debug_asserts(MyModule, true)`.

---

<div class="post-metadata">

### Author: ![jameson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jameson/32/23_2.png) [@jameson](https://discourse.julialang.org/u/jameson)
#### Post date: [January 16, 2018, 4:18am UTC](https://discourse.julialang.org/t/defensive-programming-assert/8383/14 "2018-01-16T04:18:59Z")

</div>

> [@kristoffer.carlsson](#):
>
> The way this works is exploiting that #265

Ah, clever. And since we don’t print the method replacement warning anymore, seems like this should be fairly seamless even too. I’m not sure we would want to put a trick like that in Base (to avoid potential confusion over when world-age changes become visible), but on-the-other-hand, it’s such a simple mechanism (and world-age visibility constraints usually aren’t too noticeable), so perhaps, why not!
