scenario

If -else statements are written in daily development, right? When there are too many branches of logic, If-Elses can be layered on top of each other. Although the business function is realized, it seems really inelegant, especially for a program like me who is obsessive-compulsive to see so many If-Elses, the brain is buzzing, trying to unlock a new position: kill too many If-Elses!!

This paper will introduce the three axes:

  • If the condition is not met, the logic will interrupt and return in time.
  • Integration strategy model;
  • Strategy mode + factory + singleton mode, icing on the cake;

Next, I attach a business code I wrote a long time ago. The core logic is to give users corresponding rights and interests (VIP video membership days + lottery opportunities) according to the price package purchased by users in the payment callback.

Oh, my God, there’s so much if-else… (If you can’t see clearly, please click the picture to enlarge it.)



1. Prioritize the judgment conditions, and timely interruption is not satisfied

This is easy to understand. It means that in the business logic, we should filter out the ineligible ones first, instead of nested if-else judgments. See the code diagram:





2. Strategic mode transformation

To replace the logic mentioned at the beginning of the article, the logic of adding VIP days and sampling opportunities to users according to the price package (how much money they pay) after recharge is simplified into the action of “adding different VIP days of sports member videos to users according to the price package” :











On the surface, the code is elegant, but didn’t, and if – else say bye bye, thoroughly and recharge cost () method can be singled out, only need according to the different strategies of priceCode instantiation objects can be:



3. Strategy mode + factory + singleton mode, icing on the cake

Next, use the “factory class + singleton” to spice up the code:





Source: love1024.blog.csdn.net/article/details/104955363