Is checking for null values bad practice?



  • I'm new to haxe, building a game in haxeflixel.
    There are times where I really want to check for null values in conditionals. However, I am worried this is bad practice, as I should be actively avoiding situations where my code could encounter a null value, or at least that fosters a more stable development.

    Any thoughts? Am I being paranoid?



  • You could initialize the variable first but in some cases a null check is still needed. For example, the player class is called before a monster class but at the player class a monster var is used. A null is needed then. It is good practice to use a null check but if you are sure that the code is executed first then it is not needed.



  • @galoyo
    How can I control, or at least view, the order in which classes are assembled? I am currently just using 'import' and helper functions which link/create references between instances of different classes.



  • The code I use at Reg.hx is public static var state:PlayState; then at PlayState, I have public var player:Player; then to check if that class exists, I use if (Reg.state.player != null) at playState

    The order in which a class exists is in reference to the map layer and its X and Y values. If you have a monster1 class at 0, 0 coordinate and monster2 class at 2, 10, then the one at 0, 0 will be called first.

    about how to see the order, I don't know.



  • You should only check for null when it's supposed to happen, for example in a function that takes an optional parameter.
    When in your code you're dealing with null when it shouldn't be there, you should let it crash so you see exactly where the problem occurs, else you will delay and hide the issue and make it harder to track the origin of your bug.
    If you're facing initialization order problems, try to initialize later or add methods that finalises init so you're sure everything's in memory, a good place would be in the manager that creates both of your objects.



  • Checking for null errors are important. The build error on neko, the invalid operation, come from uninitialized variables. To fix do var foo:int = 0. In this example, the 0 initializes that variable.


Log in to reply
 

Looks like your connection to HaxeFlixel was lost, please wait while we try to reconnect.