Limits of Defensive Programming acknowledging that Exception Handling should be avoided

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
0
down vote

favorite












I've read Defensive Programming vs Exception Handling? and if/else statements or exceptions, but none contain something relevant to what I'm searching for.



Taking into account that exception handling is more computational expensive than just carefully designing your code and avoiding certain scenarios, I recently came to the following question: what is the computational complexity "threshold" over which Exception Handling should be preferred?



In my case, I am receiving data from an external middleware and some times fields are null. There are two cases I can handle this.



First



try 
catch (NullReferenceException e)

continue;



Second



if (!string.IsNullOrEmpty(user.departNameEn)
&& !string.IsNullOrEmpty(user.departNameFr)
&& !string.IsNullOrEmpty(user.departNameDe)
&& !string.IsNullOrEmpty(user.Id)
&& !string.IsNullOrEmpty(user.ShortName))


Intuitively, the first approach is much more clean and elegant than the second one but which of these is computationally less expensive? Where do the limits of defensive programming end?



Note to duplicate report: As I explained in the introduction, I've read the two main topics for Exception Handling vs Defensive Programming but what I'm actually asking is something different and very specific: when Defensive Programming becomes computationally more expensive than just simplifying your code and adding a single try-catch statement?










share|improve this question























  • Possible duplicate of Are exceptions as control flow considered a serious antipattern? If so, Why?
    – gnat
    2 hours ago










  • @gnat Please read my updated last paragraph. I am not asking (again) if Exception Handling is better than Defensive Programming; from the introduction, you can see that I am fully against exceptions to only when really necessary. What I am actually seeking advice for, is if Defensive Programming under certain cases, becomes computationally expensive.
    – Lefteris008
    2 hours ago
















up vote
0
down vote

favorite












I've read Defensive Programming vs Exception Handling? and if/else statements or exceptions, but none contain something relevant to what I'm searching for.



Taking into account that exception handling is more computational expensive than just carefully designing your code and avoiding certain scenarios, I recently came to the following question: what is the computational complexity "threshold" over which Exception Handling should be preferred?



In my case, I am receiving data from an external middleware and some times fields are null. There are two cases I can handle this.



First



try 
catch (NullReferenceException e)

continue;



Second



if (!string.IsNullOrEmpty(user.departNameEn)
&& !string.IsNullOrEmpty(user.departNameFr)
&& !string.IsNullOrEmpty(user.departNameDe)
&& !string.IsNullOrEmpty(user.Id)
&& !string.IsNullOrEmpty(user.ShortName))


Intuitively, the first approach is much more clean and elegant than the second one but which of these is computationally less expensive? Where do the limits of defensive programming end?



Note to duplicate report: As I explained in the introduction, I've read the two main topics for Exception Handling vs Defensive Programming but what I'm actually asking is something different and very specific: when Defensive Programming becomes computationally more expensive than just simplifying your code and adding a single try-catch statement?










share|improve this question























  • Possible duplicate of Are exceptions as control flow considered a serious antipattern? If so, Why?
    – gnat
    2 hours ago










  • @gnat Please read my updated last paragraph. I am not asking (again) if Exception Handling is better than Defensive Programming; from the introduction, you can see that I am fully against exceptions to only when really necessary. What I am actually seeking advice for, is if Defensive Programming under certain cases, becomes computationally expensive.
    – Lefteris008
    2 hours ago












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I've read Defensive Programming vs Exception Handling? and if/else statements or exceptions, but none contain something relevant to what I'm searching for.



Taking into account that exception handling is more computational expensive than just carefully designing your code and avoiding certain scenarios, I recently came to the following question: what is the computational complexity "threshold" over which Exception Handling should be preferred?



In my case, I am receiving data from an external middleware and some times fields are null. There are two cases I can handle this.



First



try 
catch (NullReferenceException e)

continue;



Second



if (!string.IsNullOrEmpty(user.departNameEn)
&& !string.IsNullOrEmpty(user.departNameFr)
&& !string.IsNullOrEmpty(user.departNameDe)
&& !string.IsNullOrEmpty(user.Id)
&& !string.IsNullOrEmpty(user.ShortName))


Intuitively, the first approach is much more clean and elegant than the second one but which of these is computationally less expensive? Where do the limits of defensive programming end?



Note to duplicate report: As I explained in the introduction, I've read the two main topics for Exception Handling vs Defensive Programming but what I'm actually asking is something different and very specific: when Defensive Programming becomes computationally more expensive than just simplifying your code and adding a single try-catch statement?










share|improve this question















I've read Defensive Programming vs Exception Handling? and if/else statements or exceptions, but none contain something relevant to what I'm searching for.



Taking into account that exception handling is more computational expensive than just carefully designing your code and avoiding certain scenarios, I recently came to the following question: what is the computational complexity "threshold" over which Exception Handling should be preferred?



In my case, I am receiving data from an external middleware and some times fields are null. There are two cases I can handle this.



First



try 
catch (NullReferenceException e)

continue;



Second



if (!string.IsNullOrEmpty(user.departNameEn)
&& !string.IsNullOrEmpty(user.departNameFr)
&& !string.IsNullOrEmpty(user.departNameDe)
&& !string.IsNullOrEmpty(user.Id)
&& !string.IsNullOrEmpty(user.ShortName))


Intuitively, the first approach is much more clean and elegant than the second one but which of these is computationally less expensive? Where do the limits of defensive programming end?



Note to duplicate report: As I explained in the introduction, I've read the two main topics for Exception Handling vs Defensive Programming but what I'm actually asking is something different and very specific: when Defensive Programming becomes computationally more expensive than just simplifying your code and adding a single try-catch statement?







c# .net exceptions defensive-programming






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 hours ago

























asked 2 hours ago









Lefteris008

1436




1436











  • Possible duplicate of Are exceptions as control flow considered a serious antipattern? If so, Why?
    – gnat
    2 hours ago










  • @gnat Please read my updated last paragraph. I am not asking (again) if Exception Handling is better than Defensive Programming; from the introduction, you can see that I am fully against exceptions to only when really necessary. What I am actually seeking advice for, is if Defensive Programming under certain cases, becomes computationally expensive.
    – Lefteris008
    2 hours ago
















  • Possible duplicate of Are exceptions as control flow considered a serious antipattern? If so, Why?
    – gnat
    2 hours ago










  • @gnat Please read my updated last paragraph. I am not asking (again) if Exception Handling is better than Defensive Programming; from the introduction, you can see that I am fully against exceptions to only when really necessary. What I am actually seeking advice for, is if Defensive Programming under certain cases, becomes computationally expensive.
    – Lefteris008
    2 hours ago















Possible duplicate of Are exceptions as control flow considered a serious antipattern? If so, Why?
– gnat
2 hours ago




Possible duplicate of Are exceptions as control flow considered a serious antipattern? If so, Why?
– gnat
2 hours ago












@gnat Please read my updated last paragraph. I am not asking (again) if Exception Handling is better than Defensive Programming; from the introduction, you can see that I am fully against exceptions to only when really necessary. What I am actually seeking advice for, is if Defensive Programming under certain cases, becomes computationally expensive.
– Lefteris008
2 hours ago




@gnat Please read my updated last paragraph. I am not asking (again) if Exception Handling is better than Defensive Programming; from the introduction, you can see that I am fully against exceptions to only when really necessary. What I am actually seeking advice for, is if Defensive Programming under certain cases, becomes computationally expensive.
– Lefteris008
2 hours ago










4 Answers
4






active

oldest

votes

















up vote
2
down vote













This depends on more information than you are giving us. What does it mean if some fields are null? Is that (1) totally admissible and should just be interpreted as a value of ""? (2) not supposed to happen but common in practice and susceptible to a workaround? (3) possible to deal with but only with user input? (4) a flaw that makes processing that record impossible? (5) a sign of such serious trouble that the entire import must be abandoned ("halt and catch fire")?



Exceptions are not just more expensive to process at runtime, they also structure control flow in a different way than standard control structures. You can build almost any possible logical flow with if statements, but once you throw an exception out of a block there is no reasonable way of getting back into it again, and nested catch clauses are almost impossible to write in an readable way. Also, programming a try...catch raises certain expectations in readers of the code; if these are not actually true, this makes the code much harder to understand. Those are at least three different aspects of choosing how to handle uncommon situations; others can apply depending on what exactly your code is processing.






share|improve this answer




















  • (1/2) From the examples I've provided, you can see that I am parsing five fields that come externally from a middleware call (code not available for that). Middleware is not handled by me, so it is possible that each one of them could be null. Trying to perform an equality check with a null on C#, throws an exception. So, either I create a much more complex if-else statement that removes this possibility, or I simplify it and encase it in a try-catch statement. My question is more general: where if-else performance advantage ends over a try-catch?
    – Lefteris008
    2 hours ago











  • (2/2) Can I create an if-else condition that has 15 members to validate and still be more efficient than a more shorter version with three members and encased into a try-catch?
    – Lefteris008
    2 hours ago

















up vote
2
down vote














I am receiving data from an external middleware




File.Exists


So let's look at the bigger picture. You have data. That data was serialized. Then send over a wire. Then deserialized. And in the end, you even access the file system based on that data.



Looking at how you handle this from a perspective of performance is completely unnecessary, because computation power is really not the bottleneck by far in your scenario. It's like wondering whether the diver of an 18-wheeler should be put on a diet to save on overall weight.



As for the 18 wheeler: the best solution is to let the driver do whatever makes him happy and motivated to drive their truck. A pound or two in either direction really do not matter. So do what is best for the programmer. Whatever is the more readable, easier to understand code by your standards is the best solution here.




On an unrelated note:



user.departNameEn.Equals(selectedUser)


is there a reason you call Equals or is that maybe just a bad Java habit?



user?.departNameEn == selectedUser


This line does the same and will not throw on one side being null. The only "disadvantage" would be that if selectedUser is null it's considered equal too, instead of throwing as in your line.






share|improve this answer




















  • For your last comment: 1. It's a "bad" habit from Java, yes, but Equals() at least to me reminds me that I compare object and not primitive types (string is not a primitive). 2. I am aware of the null safe operator but the project I am working runs on an older version of .NET that does not support it. 3. My question is whether there is an overall limit to Defensive Programming and not to find a specific workaround to "cover" the problem.
    – Lefteris008
    1 hour ago






  • 1




    string is not a value-type, that's true, but why care? == is fine with null on one side. The null-safe operator is optional, just leave it out. Your solution assumes user is never null anyway. And as for your question: yes, the limit on defensive programming is when it does not give you any perceivable advantage (as in this case). Then you should ignore it and go for things that do give you an advantage, for example more readable code.
    – nvoigt
    1 hour ago

















up vote
1
down vote













The two code examples are not logically equivalent.



In the first case just one needs to be filled and satisfy the condition. In the second case, all three need to be non-empty.



This in my opinion is the big thing why you should go for the first version. You made the code more complex and ended up with something else then intended. Use the code the expresses the best what you want to do in the easiest to understand way.






share|improve this answer



























    up vote
    0
    down vote













    I am the kind of programmer that use defensive programming a lot. However if I would have to handle some communication with a 3rd party that give me possibly null value and such stuff, I would rather fill it with default empty strings, etc.



    However in your specific case it is not necessary : just switch the side of your test : selectedUser.equals(...) because you are probably sure at this point that selectedUser is neither null nor empty.






    share|improve this answer




















    • The user object that I am validating, is generating in a for-each loop from items that come directly from the middleware (auto-generated WSDL code). I can anytime change this code, but I don't want to. Plus, my question, yet again, is about the advantage limit of Defensive Programming over Exception Handling and not to overcome this problem.
      – Lefteris008
      46 mins ago










    Your Answer







    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "131"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f378544%2flimits-of-defensive-programming-acknowledging-that-exception-handling-should-be%23new-answer', 'question_page');

    );

    Post as a guest






























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote













    This depends on more information than you are giving us. What does it mean if some fields are null? Is that (1) totally admissible and should just be interpreted as a value of ""? (2) not supposed to happen but common in practice and susceptible to a workaround? (3) possible to deal with but only with user input? (4) a flaw that makes processing that record impossible? (5) a sign of such serious trouble that the entire import must be abandoned ("halt and catch fire")?



    Exceptions are not just more expensive to process at runtime, they also structure control flow in a different way than standard control structures. You can build almost any possible logical flow with if statements, but once you throw an exception out of a block there is no reasonable way of getting back into it again, and nested catch clauses are almost impossible to write in an readable way. Also, programming a try...catch raises certain expectations in readers of the code; if these are not actually true, this makes the code much harder to understand. Those are at least three different aspects of choosing how to handle uncommon situations; others can apply depending on what exactly your code is processing.






    share|improve this answer




















    • (1/2) From the examples I've provided, you can see that I am parsing five fields that come externally from a middleware call (code not available for that). Middleware is not handled by me, so it is possible that each one of them could be null. Trying to perform an equality check with a null on C#, throws an exception. So, either I create a much more complex if-else statement that removes this possibility, or I simplify it and encase it in a try-catch statement. My question is more general: where if-else performance advantage ends over a try-catch?
      – Lefteris008
      2 hours ago











    • (2/2) Can I create an if-else condition that has 15 members to validate and still be more efficient than a more shorter version with three members and encased into a try-catch?
      – Lefteris008
      2 hours ago














    up vote
    2
    down vote













    This depends on more information than you are giving us. What does it mean if some fields are null? Is that (1) totally admissible and should just be interpreted as a value of ""? (2) not supposed to happen but common in practice and susceptible to a workaround? (3) possible to deal with but only with user input? (4) a flaw that makes processing that record impossible? (5) a sign of such serious trouble that the entire import must be abandoned ("halt and catch fire")?



    Exceptions are not just more expensive to process at runtime, they also structure control flow in a different way than standard control structures. You can build almost any possible logical flow with if statements, but once you throw an exception out of a block there is no reasonable way of getting back into it again, and nested catch clauses are almost impossible to write in an readable way. Also, programming a try...catch raises certain expectations in readers of the code; if these are not actually true, this makes the code much harder to understand. Those are at least three different aspects of choosing how to handle uncommon situations; others can apply depending on what exactly your code is processing.






    share|improve this answer




















    • (1/2) From the examples I've provided, you can see that I am parsing five fields that come externally from a middleware call (code not available for that). Middleware is not handled by me, so it is possible that each one of them could be null. Trying to perform an equality check with a null on C#, throws an exception. So, either I create a much more complex if-else statement that removes this possibility, or I simplify it and encase it in a try-catch statement. My question is more general: where if-else performance advantage ends over a try-catch?
      – Lefteris008
      2 hours ago











    • (2/2) Can I create an if-else condition that has 15 members to validate and still be more efficient than a more shorter version with three members and encased into a try-catch?
      – Lefteris008
      2 hours ago












    up vote
    2
    down vote










    up vote
    2
    down vote









    This depends on more information than you are giving us. What does it mean if some fields are null? Is that (1) totally admissible and should just be interpreted as a value of ""? (2) not supposed to happen but common in practice and susceptible to a workaround? (3) possible to deal with but only with user input? (4) a flaw that makes processing that record impossible? (5) a sign of such serious trouble that the entire import must be abandoned ("halt and catch fire")?



    Exceptions are not just more expensive to process at runtime, they also structure control flow in a different way than standard control structures. You can build almost any possible logical flow with if statements, but once you throw an exception out of a block there is no reasonable way of getting back into it again, and nested catch clauses are almost impossible to write in an readable way. Also, programming a try...catch raises certain expectations in readers of the code; if these are not actually true, this makes the code much harder to understand. Those are at least three different aspects of choosing how to handle uncommon situations; others can apply depending on what exactly your code is processing.






    share|improve this answer












    This depends on more information than you are giving us. What does it mean if some fields are null? Is that (1) totally admissible and should just be interpreted as a value of ""? (2) not supposed to happen but common in practice and susceptible to a workaround? (3) possible to deal with but only with user input? (4) a flaw that makes processing that record impossible? (5) a sign of such serious trouble that the entire import must be abandoned ("halt and catch fire")?



    Exceptions are not just more expensive to process at runtime, they also structure control flow in a different way than standard control structures. You can build almost any possible logical flow with if statements, but once you throw an exception out of a block there is no reasonable way of getting back into it again, and nested catch clauses are almost impossible to write in an readable way. Also, programming a try...catch raises certain expectations in readers of the code; if these are not actually true, this makes the code much harder to understand. Those are at least three different aspects of choosing how to handle uncommon situations; others can apply depending on what exactly your code is processing.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 2 hours ago









    Kilian Foth

    84.7k31227256




    84.7k31227256











    • (1/2) From the examples I've provided, you can see that I am parsing five fields that come externally from a middleware call (code not available for that). Middleware is not handled by me, so it is possible that each one of them could be null. Trying to perform an equality check with a null on C#, throws an exception. So, either I create a much more complex if-else statement that removes this possibility, or I simplify it and encase it in a try-catch statement. My question is more general: where if-else performance advantage ends over a try-catch?
      – Lefteris008
      2 hours ago











    • (2/2) Can I create an if-else condition that has 15 members to validate and still be more efficient than a more shorter version with three members and encased into a try-catch?
      – Lefteris008
      2 hours ago
















    • (1/2) From the examples I've provided, you can see that I am parsing five fields that come externally from a middleware call (code not available for that). Middleware is not handled by me, so it is possible that each one of them could be null. Trying to perform an equality check with a null on C#, throws an exception. So, either I create a much more complex if-else statement that removes this possibility, or I simplify it and encase it in a try-catch statement. My question is more general: where if-else performance advantage ends over a try-catch?
      – Lefteris008
      2 hours ago











    • (2/2) Can I create an if-else condition that has 15 members to validate and still be more efficient than a more shorter version with three members and encased into a try-catch?
      – Lefteris008
      2 hours ago















    (1/2) From the examples I've provided, you can see that I am parsing five fields that come externally from a middleware call (code not available for that). Middleware is not handled by me, so it is possible that each one of them could be null. Trying to perform an equality check with a null on C#, throws an exception. So, either I create a much more complex if-else statement that removes this possibility, or I simplify it and encase it in a try-catch statement. My question is more general: where if-else performance advantage ends over a try-catch?
    – Lefteris008
    2 hours ago





    (1/2) From the examples I've provided, you can see that I am parsing five fields that come externally from a middleware call (code not available for that). Middleware is not handled by me, so it is possible that each one of them could be null. Trying to perform an equality check with a null on C#, throws an exception. So, either I create a much more complex if-else statement that removes this possibility, or I simplify it and encase it in a try-catch statement. My question is more general: where if-else performance advantage ends over a try-catch?
    – Lefteris008
    2 hours ago













    (2/2) Can I create an if-else condition that has 15 members to validate and still be more efficient than a more shorter version with three members and encased into a try-catch?
    – Lefteris008
    2 hours ago




    (2/2) Can I create an if-else condition that has 15 members to validate and still be more efficient than a more shorter version with three members and encased into a try-catch?
    – Lefteris008
    2 hours ago












    up vote
    2
    down vote














    I am receiving data from an external middleware




    File.Exists


    So let's look at the bigger picture. You have data. That data was serialized. Then send over a wire. Then deserialized. And in the end, you even access the file system based on that data.



    Looking at how you handle this from a perspective of performance is completely unnecessary, because computation power is really not the bottleneck by far in your scenario. It's like wondering whether the diver of an 18-wheeler should be put on a diet to save on overall weight.



    As for the 18 wheeler: the best solution is to let the driver do whatever makes him happy and motivated to drive their truck. A pound or two in either direction really do not matter. So do what is best for the programmer. Whatever is the more readable, easier to understand code by your standards is the best solution here.




    On an unrelated note:



    user.departNameEn.Equals(selectedUser)


    is there a reason you call Equals or is that maybe just a bad Java habit?



    user?.departNameEn == selectedUser


    This line does the same and will not throw on one side being null. The only "disadvantage" would be that if selectedUser is null it's considered equal too, instead of throwing as in your line.






    share|improve this answer




















    • For your last comment: 1. It's a "bad" habit from Java, yes, but Equals() at least to me reminds me that I compare object and not primitive types (string is not a primitive). 2. I am aware of the null safe operator but the project I am working runs on an older version of .NET that does not support it. 3. My question is whether there is an overall limit to Defensive Programming and not to find a specific workaround to "cover" the problem.
      – Lefteris008
      1 hour ago






    • 1




      string is not a value-type, that's true, but why care? == is fine with null on one side. The null-safe operator is optional, just leave it out. Your solution assumes user is never null anyway. And as for your question: yes, the limit on defensive programming is when it does not give you any perceivable advantage (as in this case). Then you should ignore it and go for things that do give you an advantage, for example more readable code.
      – nvoigt
      1 hour ago














    up vote
    2
    down vote














    I am receiving data from an external middleware




    File.Exists


    So let's look at the bigger picture. You have data. That data was serialized. Then send over a wire. Then deserialized. And in the end, you even access the file system based on that data.



    Looking at how you handle this from a perspective of performance is completely unnecessary, because computation power is really not the bottleneck by far in your scenario. It's like wondering whether the diver of an 18-wheeler should be put on a diet to save on overall weight.



    As for the 18 wheeler: the best solution is to let the driver do whatever makes him happy and motivated to drive their truck. A pound or two in either direction really do not matter. So do what is best for the programmer. Whatever is the more readable, easier to understand code by your standards is the best solution here.




    On an unrelated note:



    user.departNameEn.Equals(selectedUser)


    is there a reason you call Equals or is that maybe just a bad Java habit?



    user?.departNameEn == selectedUser


    This line does the same and will not throw on one side being null. The only "disadvantage" would be that if selectedUser is null it's considered equal too, instead of throwing as in your line.






    share|improve this answer




















    • For your last comment: 1. It's a "bad" habit from Java, yes, but Equals() at least to me reminds me that I compare object and not primitive types (string is not a primitive). 2. I am aware of the null safe operator but the project I am working runs on an older version of .NET that does not support it. 3. My question is whether there is an overall limit to Defensive Programming and not to find a specific workaround to "cover" the problem.
      – Lefteris008
      1 hour ago






    • 1




      string is not a value-type, that's true, but why care? == is fine with null on one side. The null-safe operator is optional, just leave it out. Your solution assumes user is never null anyway. And as for your question: yes, the limit on defensive programming is when it does not give you any perceivable advantage (as in this case). Then you should ignore it and go for things that do give you an advantage, for example more readable code.
      – nvoigt
      1 hour ago












    up vote
    2
    down vote










    up vote
    2
    down vote










    I am receiving data from an external middleware




    File.Exists


    So let's look at the bigger picture. You have data. That data was serialized. Then send over a wire. Then deserialized. And in the end, you even access the file system based on that data.



    Looking at how you handle this from a perspective of performance is completely unnecessary, because computation power is really not the bottleneck by far in your scenario. It's like wondering whether the diver of an 18-wheeler should be put on a diet to save on overall weight.



    As for the 18 wheeler: the best solution is to let the driver do whatever makes him happy and motivated to drive their truck. A pound or two in either direction really do not matter. So do what is best for the programmer. Whatever is the more readable, easier to understand code by your standards is the best solution here.




    On an unrelated note:



    user.departNameEn.Equals(selectedUser)


    is there a reason you call Equals or is that maybe just a bad Java habit?



    user?.departNameEn == selectedUser


    This line does the same and will not throw on one side being null. The only "disadvantage" would be that if selectedUser is null it's considered equal too, instead of throwing as in your line.






    share|improve this answer













    I am receiving data from an external middleware




    File.Exists


    So let's look at the bigger picture. You have data. That data was serialized. Then send over a wire. Then deserialized. And in the end, you even access the file system based on that data.



    Looking at how you handle this from a perspective of performance is completely unnecessary, because computation power is really not the bottleneck by far in your scenario. It's like wondering whether the diver of an 18-wheeler should be put on a diet to save on overall weight.



    As for the 18 wheeler: the best solution is to let the driver do whatever makes him happy and motivated to drive their truck. A pound or two in either direction really do not matter. So do what is best for the programmer. Whatever is the more readable, easier to understand code by your standards is the best solution here.




    On an unrelated note:



    user.departNameEn.Equals(selectedUser)


    is there a reason you call Equals or is that maybe just a bad Java habit?



    user?.departNameEn == selectedUser


    This line does the same and will not throw on one side being null. The only "disadvantage" would be that if selectedUser is null it's considered equal too, instead of throwing as in your line.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 2 hours ago









    nvoigt

    3,97811118




    3,97811118











    • For your last comment: 1. It's a "bad" habit from Java, yes, but Equals() at least to me reminds me that I compare object and not primitive types (string is not a primitive). 2. I am aware of the null safe operator but the project I am working runs on an older version of .NET that does not support it. 3. My question is whether there is an overall limit to Defensive Programming and not to find a specific workaround to "cover" the problem.
      – Lefteris008
      1 hour ago






    • 1




      string is not a value-type, that's true, but why care? == is fine with null on one side. The null-safe operator is optional, just leave it out. Your solution assumes user is never null anyway. And as for your question: yes, the limit on defensive programming is when it does not give you any perceivable advantage (as in this case). Then you should ignore it and go for things that do give you an advantage, for example more readable code.
      – nvoigt
      1 hour ago
















    • For your last comment: 1. It's a "bad" habit from Java, yes, but Equals() at least to me reminds me that I compare object and not primitive types (string is not a primitive). 2. I am aware of the null safe operator but the project I am working runs on an older version of .NET that does not support it. 3. My question is whether there is an overall limit to Defensive Programming and not to find a specific workaround to "cover" the problem.
      – Lefteris008
      1 hour ago






    • 1




      string is not a value-type, that's true, but why care? == is fine with null on one side. The null-safe operator is optional, just leave it out. Your solution assumes user is never null anyway. And as for your question: yes, the limit on defensive programming is when it does not give you any perceivable advantage (as in this case). Then you should ignore it and go for things that do give you an advantage, for example more readable code.
      – nvoigt
      1 hour ago















    For your last comment: 1. It's a "bad" habit from Java, yes, but Equals() at least to me reminds me that I compare object and not primitive types (string is not a primitive). 2. I am aware of the null safe operator but the project I am working runs on an older version of .NET that does not support it. 3. My question is whether there is an overall limit to Defensive Programming and not to find a specific workaround to "cover" the problem.
    – Lefteris008
    1 hour ago




    For your last comment: 1. It's a "bad" habit from Java, yes, but Equals() at least to me reminds me that I compare object and not primitive types (string is not a primitive). 2. I am aware of the null safe operator but the project I am working runs on an older version of .NET that does not support it. 3. My question is whether there is an overall limit to Defensive Programming and not to find a specific workaround to "cover" the problem.
    – Lefteris008
    1 hour ago




    1




    1




    string is not a value-type, that's true, but why care? == is fine with null on one side. The null-safe operator is optional, just leave it out. Your solution assumes user is never null anyway. And as for your question: yes, the limit on defensive programming is when it does not give you any perceivable advantage (as in this case). Then you should ignore it and go for things that do give you an advantage, for example more readable code.
    – nvoigt
    1 hour ago




    string is not a value-type, that's true, but why care? == is fine with null on one side. The null-safe operator is optional, just leave it out. Your solution assumes user is never null anyway. And as for your question: yes, the limit on defensive programming is when it does not give you any perceivable advantage (as in this case). Then you should ignore it and go for things that do give you an advantage, for example more readable code.
    – nvoigt
    1 hour ago










    up vote
    1
    down vote













    The two code examples are not logically equivalent.



    In the first case just one needs to be filled and satisfy the condition. In the second case, all three need to be non-empty.



    This in my opinion is the big thing why you should go for the first version. You made the code more complex and ended up with something else then intended. Use the code the expresses the best what you want to do in the easiest to understand way.






    share|improve this answer
























      up vote
      1
      down vote













      The two code examples are not logically equivalent.



      In the first case just one needs to be filled and satisfy the condition. In the second case, all three need to be non-empty.



      This in my opinion is the big thing why you should go for the first version. You made the code more complex and ended up with something else then intended. Use the code the expresses the best what you want to do in the easiest to understand way.






      share|improve this answer






















        up vote
        1
        down vote










        up vote
        1
        down vote









        The two code examples are not logically equivalent.



        In the first case just one needs to be filled and satisfy the condition. In the second case, all three need to be non-empty.



        This in my opinion is the big thing why you should go for the first version. You made the code more complex and ended up with something else then intended. Use the code the expresses the best what you want to do in the easiest to understand way.






        share|improve this answer












        The two code examples are not logically equivalent.



        In the first case just one needs to be filled and satisfy the condition. In the second case, all three need to be non-empty.



        This in my opinion is the big thing why you should go for the first version. You made the code more complex and ended up with something else then intended. Use the code the expresses the best what you want to do in the easiest to understand way.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 1 hour ago









        Pieter B

        10.3k12560




        10.3k12560




















            up vote
            0
            down vote













            I am the kind of programmer that use defensive programming a lot. However if I would have to handle some communication with a 3rd party that give me possibly null value and such stuff, I would rather fill it with default empty strings, etc.



            However in your specific case it is not necessary : just switch the side of your test : selectedUser.equals(...) because you are probably sure at this point that selectedUser is neither null nor empty.






            share|improve this answer




















            • The user object that I am validating, is generating in a for-each loop from items that come directly from the middleware (auto-generated WSDL code). I can anytime change this code, but I don't want to. Plus, my question, yet again, is about the advantage limit of Defensive Programming over Exception Handling and not to overcome this problem.
              – Lefteris008
              46 mins ago














            up vote
            0
            down vote













            I am the kind of programmer that use defensive programming a lot. However if I would have to handle some communication with a 3rd party that give me possibly null value and such stuff, I would rather fill it with default empty strings, etc.



            However in your specific case it is not necessary : just switch the side of your test : selectedUser.equals(...) because you are probably sure at this point that selectedUser is neither null nor empty.






            share|improve this answer




















            • The user object that I am validating, is generating in a for-each loop from items that come directly from the middleware (auto-generated WSDL code). I can anytime change this code, but I don't want to. Plus, my question, yet again, is about the advantage limit of Defensive Programming over Exception Handling and not to overcome this problem.
              – Lefteris008
              46 mins ago












            up vote
            0
            down vote










            up vote
            0
            down vote









            I am the kind of programmer that use defensive programming a lot. However if I would have to handle some communication with a 3rd party that give me possibly null value and such stuff, I would rather fill it with default empty strings, etc.



            However in your specific case it is not necessary : just switch the side of your test : selectedUser.equals(...) because you are probably sure at this point that selectedUser is neither null nor empty.






            share|improve this answer












            I am the kind of programmer that use defensive programming a lot. However if I would have to handle some communication with a 3rd party that give me possibly null value and such stuff, I would rather fill it with default empty strings, etc.



            However in your specific case it is not necessary : just switch the side of your test : selectedUser.equals(...) because you are probably sure at this point that selectedUser is neither null nor empty.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 1 hour ago









            Walfrat

            3,013724




            3,013724











            • The user object that I am validating, is generating in a for-each loop from items that come directly from the middleware (auto-generated WSDL code). I can anytime change this code, but I don't want to. Plus, my question, yet again, is about the advantage limit of Defensive Programming over Exception Handling and not to overcome this problem.
              – Lefteris008
              46 mins ago
















            • The user object that I am validating, is generating in a for-each loop from items that come directly from the middleware (auto-generated WSDL code). I can anytime change this code, but I don't want to. Plus, my question, yet again, is about the advantage limit of Defensive Programming over Exception Handling and not to overcome this problem.
              – Lefteris008
              46 mins ago















            The user object that I am validating, is generating in a for-each loop from items that come directly from the middleware (auto-generated WSDL code). I can anytime change this code, but I don't want to. Plus, my question, yet again, is about the advantage limit of Defensive Programming over Exception Handling and not to overcome this problem.
            – Lefteris008
            46 mins ago




            The user object that I am validating, is generating in a for-each loop from items that come directly from the middleware (auto-generated WSDL code). I can anytime change this code, but I don't want to. Plus, my question, yet again, is about the advantage limit of Defensive Programming over Exception Handling and not to overcome this problem.
            – Lefteris008
            46 mins ago

















             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f378544%2flimits-of-defensive-programming-acknowledging-that-exception-handling-should-be%23new-answer', 'question_page');

            );

            Post as a guest













































































            Comments

            Popular posts from this blog

            What does second last employer means? [closed]

            List of Gilmore Girls characters

            Confectionery