Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert vs If in Controller

What is the best way to check for a value that was passed in the controller?

Is it assert or if?

if this is the sample url....

http://example.com/read/1/2

I would like to check if 1 and 2 is number and if it's null. Like if the user changed the url to http://example.com/read/1asdf/2asdfqwer

We are using assert in our company. And I'm just thinking that what will happen if it's already in production mode and assert is disabled.

Somebody give me an insight with this.

like image 594
Mnick Avatar asked Sep 03 '25 07:09

Mnick


2 Answers

assert is intended as a debugging tool for checking conditions under you control. If it fires, it indicates a bug in your code. Checking user supplied input does not fall into this category, instead it is a feature of correct programs. Thus you should use if statements for checking user input.

like image 75
Drunix Avatar answered Sep 04 '25 19:09

Drunix


Asserts are mainly used to check preconditions.

Its like if given preconditions are not mate throw AssertionError. Checking preconditions this way is actually good practice in testing environments. Where we can make sure all preconditions are mate and satisfied.

In production environment if debug mode is not yet activated then it will surely will not harm. this statement will work as if it is commented.

In your case if you merely want to check which value is accepted at controller level use if's.

but If you want to check that as precondition and then you want throw error if these preconditions are not met and ideally in debug mode. (AssertionError.) then you can use asserts.

like image 44
Pramod S. Nikam Avatar answered Sep 04 '25 21:09

Pramod S. Nikam