Should I be using assert here?

Sorry if this is in the wrong category, I was thinking it might belong in code review but am unsure.

I have a monster class. When I instantiate that class, I run a method called “SetupConfiguration”. The idea is that each monster will have a configuration folder of value objects than will be run through and created as fields for the object.

Obviously, if there is no configuration folder when I try to instantiate the class, I want to throw an error, which of these is optimal?


It’s up to personal preference really, I’d recommend using the assert function since in my opinion it better conveys what the code’s trying to do for anyone else working or helping with it

@81MasterGamer There is one case where using assert is disadvantageous though, which is if you’re using string concatenation in the error message like in this example:

assert(exampleCondition, string.format("Error: %s", errorMessage))

string.format will be called even if the condition is truthy, which is an unnecessary function call since the error message only needs to show up if the condition is false. In a case like this, using the if statement method is preferred for performance

1 Like

I think they pretty much do the same thing, in my defence I don’t use OOP however I think that the first one will check if configurationFolder returns a value other than nil and the second one will check if it returns false.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.