Is there a good reason for choosing assert() over an if condition with an error?

27 ビュー (過去 30 日間)
I want to make sure a condition is valid, so I write a quick test for it with a boolean output. Does it matter whether I put the test in an if/error block or an assertion? Is easier reading/fewer lines the only goal?
  12 件のコメント
dpb 2022 年 5 月 5 日
But in the particular case they are equivalent -- while the if...end COULD could include more code, in this case it doesn't.
I don't argue that it would make computing a metric much more difficult, but imo one should recognize that one can have the same effective metric and the code is just as robust despite what the present metric may indicate as the one being higher than the other.
For a simple, short routine with only one or two exits, the numerical difference probably wouldn't show up much; a more involved routine with lots of error checking could really show up as a loser when, in fact, it really isn't.



Stephen23 2022 年 5 月 4 日
編集済み: Stephen23 2022 年 5 月 4 日
"Is easier reading/fewer lines the only goal?"
Why call two operators when you can call just one?
It certainly can make the intent clearer: ASSERT makes it clear that no other actions are intended/possible. In my quick internet search just now (not MATLAB specific), the general consensus seems to be that ASSERT should be used (much like its name implies) at particular points in code where certain condition/s must be met for the code to work. In contrast, an IF certainly implies that some other action might be performed at the programmers discretion.
My observation: ASSERT tends to be underused in MATLAB.
My recommendation: use whichever one makes your code look best and easier to read.
  1 件のコメント
dpb 2022 年 5 月 4 日
Mayhaps it's just me and being an old dog, but I find I almost always have it backwards the first time for some almost always have to spend extra time debugging/fixing my logic when I try using it.
For legibility, I'll often use something like
if errortest(), error('Error msg'), end
instead of the full-blown indented if...end structure so it doesn't break up the code linear flow when scanning.


その他の回答 (0 件)


Find more on Performance and Memory in Help Center and File Exchange



Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by