ulfben icon

assert(), require(), expect()

ulfben | PRO | 09/05/21 08:31:09 PM UTC | 0 ⭐ | 12662 👁️ | Never ⏰ | []
Kotlin |

1.39 KB

|

None

|

0 👍

/

0 👎

/*
I habitually put assert()-statements in my code to check for programmer errors. When an assert() triggers it crashes the application immediately so the programmer error can be fixed. Problem is: assert() doesn't actually exist in the Android Java runtime (ART)! You can try it yourself - put assert(false) in your (Java) Game constructor and run it - nothing happens! Not in debug mode, not on the emulator nor on the physical device.
 
Kotlin *does* provide an Assert, but it doesn't make it easy to provide a helpful message. So I use two utility functions to provide assertion with messaging: require() and expect(). 
*/
 
import android.util.Log
fun expect(condition: Boolean, tag: String) {
    expect(condition, tag, "Expectation was broken.")
}
 
fun expect(condition: Boolean, tag: String, message: String) {
    if (!condition) {
        Log.e(tag, message)
    }
}
 
fun require(condition: Boolean) {
    require(condition, "Assertion failed!")
}
 
fun require(condition: Boolean, message: String) {
    if (!condition) {
        throw AssertionError(message)
    }
}
 
/*requires() will throw an AssertionError and thus be functionally equivalent to the original assert(). Your application will crash, and the debugger will give you a stack trace to show where the fault was. 
 
expects() logs the error but won't crash the app. This is good for documenting non-critical expectations.*/
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎