[Add to favorites] The simplest anti-If code

Source: Internet
Author: User
Tags classe
Original article address: the simplest anti-If code

The basic problem is that ifs create
Dependencies, coupling between modules (methods, objects, components,
Etc.) and increases possible paths inside our code (which reduces
Legibility ).

An if seems like a quick and easy way to make changes, but
The reasons listed above, if after if, we create software full
Duplications that can't be modified.

Here's a simple example:

// Bond class double calculatevalue () {If (_ type = BTP) {return calculatebtpvalue ();} else if (_ type = BOT) {return calculatebotvalue ();} else {return calculateeubvalue ();}}

Every change in bond type, for example, a new bond to evaluate,
Leads to a modification in our piece of code. Imagine what it wocould take
To modify methods with built-in IFS and switches!

// Bond class double calculatevalue () {_ bondprofile. calculate ();} // abstractbondprofile class abstract double calculate (); // Classe btpbondprofile> abstractbondprofile double calculate (){...} // Classe botbondprofile> abstractbondprofile double calculate (){...} // Classe eubondprofile> abstractbondprofile double calculate (){...}


What do we gain by taking out ifs?

The advantage is that tomorrow, we can fulfill the request for
New type of bond by simply creating a new class, with the single
Required logic to calculate the value of that new bond.

The solution isn' t always to create a new abstract class or
Interface. But the solution will always make the software flexible,
Communicative, testable, ready for change.

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.