Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of java Code

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "java code case analysis". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this "java code case analysis" article can help you solve the problem.

1. A few directories that fool the code.

1. What are the pitfalls in this way of using StringBuffer?

2. How long is the longest line of code you have ever written?

3. Loop + conditional judgment, how many layers can you nest at most?

4. In order to optimize the query speed in the later stage, I have a lot of business sense!

5. How did you become an abnormal player after being played with an exception?

6, Stream play the most 6 code, people who have seen are stunned!

Second, cheating code | what are the pitfalls in using StringBuffer in this way?

Have you ever used Java's StringBuffer class in this way?

/ * * Create Time 2019-5-24 * StringBuffer adds * @ author cailong * * / public class Append {public static void main (String [] ares) {StringBuffer sb = new StringBuffer (); / / sb.append (""); for (int I = 0; I) can be understood here.

< 10; i++) { //为什么到这里就要这样写???既然都用StringBuffer了 (这里省略集合遍历用i代替 意思能懂就行) sb.append("" + ""+i+"" + ""+i+"" + ""+i+"" + ""+i+"" + ""+i+"" + "sjzs" + ""+i+"" + ""); } sb.append(""); System.out.println(sb.toString()); } } 三、坑爹代码 | 你写过的最长的一行代码有多长??? 你写过的最长的一行代码有多长吗?你为什么要写这么长?是看着帅呢,还是想减少代码行数? List purchaseInfoList = sheet.getPurchaseInfoList() .stream() .filter(purchaseInfo ->

PurchaseInfo.getExteriorOperation () .getExteriorPart () .getExteriorOperationList () .stream () .filter (exteriorOperation-> exteriorOperation .getProcessState () .equals (ExteriorOperation.ProcessState) .Processing) .count ()! = 0 / / other processes under the corresponding workpiece in the order details are in processing / / when it has been sent to the supplier and the supplier is not the current order supplier You need to judge & & (purchaseInfo.getExteriorOperation () .getExteriorPart ()) .getTeamwork () = = null | |! purchaseInfo.getExteriorOperation () .getExteriorPart (). GetTeamwork () .getExteriorPart (sheet.getTeamwork () .equals (Collectors.toList ()

Although the above code has been taken apart and displayed in multiple lines, it is essentially one line, an extremely complex assignment statement!

Is this kind of code to show your coding level so that others can't understand it?

The editor feels that Java Stream API and various functional programming methods, as well as various syntax candies, to some extent make this bad code more and more!

So let's criticize the code, or do you have any good solutions?

Fourth, cheating code | Loop + condition judgment, how many layers can you nest at most?

For loop and if conditional judgment statements are essential. But how many layers of nested loops and conditional judgments have you ever seen? Or, how many layers of nesting can you tolerate at most?

Let's first take a look at the extreme code:

/ / this * loop is nested and is only part of the total loop. I have fainted around if (recordList.size () > start) {for (int I = start; I) at Huangyuwan Interchange.

< end; i++) { Map map = recordList.get(i); Map field11 = (Map) map.get("field"); //name ->

Code Map record11 = (Map) map.get ("record"); / / code-> value String catagory1 = map.get ("categoryId"). ToString (); / / query * * other types corresponding to SalaryDataVo ss = JSON.parseObject (JSON.toJSONString (map), SalaryDataVo.class); Page page3 = salaryManagerService.getAllRecordsByCondition (ss) If (page3.getRecords (). Size () > 0) {List salaryDataVos = page3.getRecords (); salaryDataVos = this.reSetMap (salaryDataVos, null, null); for (Map map2: salaryDataVos) {Map field2 = (Map) map2.get ("field") Map record2 = (Map) map2.get ("record"); String catagory2 = map2.get ("categoryId"). ToString (); List groupList2 = salaryGroupService.getSalaryGroupsItems (this.getUserCorpId (), catagory2) For (SalaryGroupVO cc: groupList2) {cc.setCode (cc.getParentId () + cc.getCode ()) } / / calculate for (Map.Entry entity: field2.entrySet ()) {String keyName = entity.getKey () For (SalaryGroupVO S2: groupList2) {if ("bigDecimal" .equals (s2.getItemType ()) & & s2.getCode () .equals (field2.get (keyName) .toString ()) & ("Department"! = keyName) & & ("name"! = keyName) & & StringUtils.isNotEmpty (s2.getItemType () {if (field11.containsKey (keyName)) {if (field11.containsKey (keyName)) {String code1 = field11.get (keyName) .toString () Double newValue = 0; Double oldValue = 0. 0 If (! record11.get (code1) .toString () .matches ("^ [0-9] * $") {oldValue = Double.parseDouble (record11.get (code1) .toString ()) If (record2.containsKey (entity.getValue (). ToString ()) & (! record2.get (entity.getValue (). ToString ()). ToString (). Matches ("^ [0-9] * $")) {String value2 = record2.get (entity.getValue (). ToString ()) .toString () NewValue = Double.parseDouble (value2);} record11.remove (field11.get (keyName) .toString ()) } if (code1.startsWith (catagory1) | | code1.startsWith (catagory2)) {String co = code1.replace (catagory1, "hz") Field11.put (keyName, co); record11.put (co, oldValue + newValue) } else {String code = entity.getValue () .toString () String str = entity.getValue () .toString (); Object value2 = record2.get (entity.getValue () .toString ()) If (str.startsWith (catagory1) & & str.replace (catagory1, ") .startsWith (" hz ") {code = str.replace (catagory1,") } else if (str.startsWith (catagory2) & & str.replace (catagory2, ") .startsWith (" hz ") {code = str.replace (catagory2,") } field11.put (keyName, code); record11.put (code, value2) }} List sList = salaryGroupService.getSalaryGroupItemsByParentId (catagory1) For (SalaryGroupVO s: sList) {if (field11.containsKey (s.getName ()) & & s.getCode () .startsWith ("hz")) {String k = field11.get (s.getName ()) .toString (); field11.put (s.getName (), s.getCode ()) String value = null; if (record11.containsKey (k)) {value = record11.get (k). ToString ();} record11.put (s.getCode (), value) } resultList.add (map); pageInfo.setRecords (resultList);}}

Fifth, deceiving the code | in order to optimize the query speed in the later stage ~ quite business savvy!

What kind of programmer is a good programmer? When we are developing the system for our customers, we set aside some burial sites for later optimization.

Through the optimization of these burying points, customers can instantly feel that the system has a qualitative leap in running speed, so that the company can smoothly sign the second phase of the development contract and charge a huge development fee.

From the company's point of view, such a programmer is a good programmer.

For example:

Sixth, fool the code | how did you become an abnormal player after being fooled by an exception?

People who play Java will be abused at first, and null pointers should be the most common. After playing for two more years, I began to play with anomalies, and all kinds of strange and unusual games emerged one after another.

Do you think the definition of the following anomaly is correct?

/ * handle business exceptions * there are a bunch of static exceptions that can be thrown at any time. * the error code is the string * / public class CommandException extends BaseException {private static final long serialVersionUID =-6354513454371927970L; public static CommandException PARAM_NULL= new CommandException ("Command_assemble_01", "Parameter is Needed But Empty"); public static CommandException DEVID_NULL = new CommandException ("Command_assemble_02", "DevId Cannot Be Null"); public static CommandException MDCODE_NULL = new CommandException ("Command_assemble_03", "Model Code Cannot Be Empty") Public static CommandException ORDER_NULL = new CommandException ("Command_assemble_04", "Order Cannot Be Empty"); public static CommandException TYPE_NULL = new CommandException ("Command_assemble_05", "Upstream / Downstream Type Cannot Be Empty"); public static CommandException MENUID_NULL = new CommandException ("Command_assemble_06", "Menu Id Cannot Be Null"); public static CommandException CTRLTYPE_NOT_RANGE= new CommandException ("Command_assemble_07", "Ctrltype Cannot Be Recognized, Which is not in Range") Public static CommandException CMD_NULL = new CommandException ("Command_analyze_01", "CMD Cannot Be Null"); public static CommandException PAYLOAD_NULL = new CommandException ("Command_analyze_02", "Payload Cannot Be Null"); public static CommandException FRAMEWORK_FAILED= new CommandException ("Command_analyze_03", "Framework Failed to be Checked"); public static CommandException CHECK_FAILED= new CommandException ("Command_analyze_04", "Command Failed to be Checked") Public static CommandException CONFIGURE_NOT_EXIST = new CommandException ("Command_error_1001", "Configure is not Exist"); public static CommandException REDIS_ERROR = new CommandException ("Command_error_1002", "Cache Command in Redis Error", true); / / omit constructor, get/set method}

If not, what's the problem?

7. Fool the code | the code that plays the most 6 in Stream, everyone who has seen it is stunned!

As a highlight of Java 8, Stream is a completely different concept from InputStream and OutputStream in the java.io package. Stream in Java 8 is an enhancement to Collection objects, which focuses on a variety of very convenient and efficient aggregation operations (aggregate operation) or mass data operations (bulk data operation) on collection objects. With the help of the same new Lambda expression, Stream API greatly improves the programming efficiency and program readability.

The usage of Stream:

/ / final EventAction eventAction of 66 for Stream = redisObj (EventActionKey + distributionEventId, ()-> Optional .of (distributionEventId) .map (eventId-> {final EventActionExample example = new EventActionExample ()) Example.createCriteria () .andEventIdEqualTo (eventId) .andTriggerTypeEqualTo (EnumEventTriggerType.DISTRIBUTION_PURCHASE.getCode (). ByteValue ()); return example }) .map (eventActionMapper::selectByExample) .filter (StringUtil::isNotEmpty) .map (e-> e.get (0)) .orElseThrow (()-> ExceptionUtil.createParamException ("event trigger information does not exist"), EventAction.class) Final AwardConfig awardConfig = redisObj (EventConfigKey + eventAction.getId (), ()-> Optional.ofNullable (eventAction.getId ()) .map (actionId-> {final AwardConfigExample example = new AwardConfigExample (); example.createCriteria () .andActionIdEqualTo (actionId)) Return example ) .map (awardConfigMapper::selectByExample) .filter (StringUtil::isNotEmpty) .map (e-> e.get (0)) .orElseThrow (()-> ExceptionUtil.createParamException ("xxx")), AwardConfig.class) Optional.of (req) .map (e-> e.clueUid) .map (id-> {final ClueExample example = new ClueExample () Example.createCriteria () .andClueUidEqualTo (id) .andDeletedEqualTo (false) .andReceivedEqualTo (false) .andCreateTimeGreaterThan (now-cluetime); example.setOrderByClause ("create_time asc") Return example }) / / get the clues of all the unexpired and unclaimed clues of the invitee .map (clueMapper::selectByExample) .filter (StringUtil::isNotEmpty) .ifPresent (clues-> {final ClueResp clueResp = Optional.of (req)) .filter (c-> {c.count = clues.size ()) Return true;}) .map (this::awardValue) .orElseThrow (()-> ExceptionUtil.createParamException ("parameter error")) Final Integer specialId = req.getIsHead ()? Clues.get (0) .getId (): clues.get (clues.size ()-1) .getId () Clues.stream () .peek (clue-> {final AwardConfig awardConfigclone = Optional.of (awardConfig) .map (JSONUtil::obj2Json)) .map (json-> JSONUtil.json2Obj (json) AwardConfig.class) .orElseGet (AwardConfig::new) AwardConfigclone.setMoney (Optional.of (clue.getId ()). Filter (specialId::equals)) .map (e-> clueResp.specialReward.longValue ()) .orElse (clueResp.otherAverageReward.longValue () EventActionService.assembleAward (awardConfigclone, clue.getAdviserUid (), clue.getAdviserUid () Clue.getClueUid (), eventAction, new PasMessageParam (), clue.getId () AwardRelationType.Clud.code () ) .forEach (clue-> {clue.setOrderNo (req.orderNo); clue.setCommodityName (req.commodityName)) Clue.setOrderAmount (req.orderAmount); clue.setReceived (true); clue.setModifyTime (now); clueMapper.updateByPrimaryKeySelective (clue) This is the end of the introduction to "java Code instance Analysis". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report