Refactoring day 18th replaces exceptions with conditional statements (replace exception with conditional)

Source: Internet
Author: User

Understanding : The "use of conditional judgment instead of exception" in this article refers to the need to use the exception to judge the conditions as far as possible to change the conditions of judgment.

Detailed :

Refactoring Pre-code:

1   Public classMicrowave2     {3         PrivateImicrowavemotor Motor {Get;Set; }4 5          Public BOOLStart (ObjectFood )6         {7             BOOLfoodcooked =false;8             Try9             {Ten Motor.cook (food); Onefoodcooked =true; A             } -             Catch(inuseexception) -             { thefoodcooked =false; -             } -  -             returnfoodcooked; +         } -}

The refactored code looks like this,TryCatchThe statement that made the conditional judgment was changed toIf return , which in many ways unifies the writing of the Code and also improves performance.

1  Public classMicrowave2     {3         PrivateImicrowavemotor Motor {Get;Set; }4 5          Public BOOLStart (ObjectFood )6         {7             if(Motor.isinuse)8                 return false;9 Ten Motor.cook (food); One  A             return true; -         } -}

This refactoring is also often used in project code because it is difficult for a part of the programmer to grasp when to useTryCatch, where should I use it?Try catch . Remember that you've talked about this before, such as how to use it well and which component should be placed in medium and large projects.

Refactoring day 18th replaces exceptions with conditional statements (replace exception with conditional)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.