Home > Java > javaTutorial > Java code example analysis

Java code example analysis

PHPz
Release: 2023-05-10 11:58:06
forward
1750 people have browsed it

1. Directory of several cheating codes

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

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

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

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

5. How did you get played by an anomaly and then become an anomaly?

6. Stream is the most played code, everyone who has seen it is shocked!

2. Cheat code | What are the pitfalls of using StringBuffer in this way?

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

/**   * Create Time 2019/5/24   * StringBuffer追加 如痴如醉的写法   * @author cailong   **/  public class Append {      public static void main(String[] ares){          StringBuffer sb = new StringBuffer();          //这里都能理解          sb.append("<?xml  version=\"1.0\" encoding=\"UTF-8\"?><root>");          for (int i = 0; i " +                      "<nsrsbh>"+i+"</nsrsbh>" +                      "<nsrmc>"+i+"</nsrmc>" +                      "<djxh>"+i+"</djxh>" +                      "<zgswj_dm>"+i+"</zgswj_dm>" +                      "<zgswj_mc>"+i+"</zgswj_mc>" +                      "<sjly>sjzs</sjly>" +                      "<ywsx_dm>"+i+"</ywsx_dm>" +                      "");          }          sb.append("</root>");          System.out.println(sb.toString());      }  }
Copy after login

3. Cheating code | How long is the longest line of code you have ever written? ? ?

Java code example analysis

#What is the longest line of code you have ever written? Why did you write so long? Does it look cool, or do you want to reduce the number of lines of code?

List<operationpurchaseinfo> purchaseInfoList                  = sheet.getPurchaseInfoList()                  .stream()                  .filter(purchaseInfo -> purchaseInfo.getExteriorOperation()                          .getExteriorPart()                          .getExteriorOperationList()                          .stream()                          .filter(exteriorOperation -> exteriorOperation                                  .getProcessState()                                  .equals(ExteriorOperation.ProcessState.PROCESSING))                          .count() != 0                          // 订单明细中工序对应的工件下的其他工序存在加工中,                          // 且已发给供应商且供应商不是当前订单供应商时,需要判断                          && (purchaseInfo.getExteriorOperation()                          .getExteriorPart()                          .getTeamwork() == null || !purchaseInfo.getExteriorOperation()                          .getExteriorPart().getTeamwork().equals(sheet.getTeamwork()))                  ).collect(Collectors.toList());</operationpurchaseinfo>
Copy after login

Although the above code is split into multiple lines and displayed, it is essentially one line, an extremely complex assignment statement!

Is this kind of code meant to be incomprehensible to others to show off your coding skills?

The editor feels that the Java Stream API and various functional programming methods, as well as various syntactic sugars, have made this kind of bad code more and more common to some extent!

So let’s criticize this code together, or do you have any good solutions?

4. Cheating code | Loop conditional judgment, how many levels can you nest at most?

For loops and if conditional judgment statements are essential. But how many levels of nested loops and conditional judgments have you seen? In other words, how many levels of nesting can you tolerate at most?

Java code example analysis

Let’s take a look at the extreme cheating code first:

// 这个***循环嵌套,只是总循环的一部分。。。我已经绕晕在黄桷湾立交          if (recordList.size() > start) {              for (int i = start; i  map = recordList.get(i);                  Map<string> field11 = (Map<string>) map.get("field"); //name -> code                  Map<string> record11 = (Map<string>) map.get("record"); // code -> value                  String catagory1 = map.get("categoryId").toString();                  //  查询***种类型对应的其他类型                  SalaryDataVo ss = JSON.parseObject(JSON.toJSONString(map), SalaryDataVo.class);                  Page page3 = salaryManagerService.getAllRecordsByCondition(ss);                  if (page3.getRecords().size() > 0) {                      List<map>> salaryDataVos = page3.getRecords();                      salaryDataVos = this.reSetMap(salaryDataVos, null, null);                      for (Map<string> map2 : salaryDataVos) {                          Map<string> field2 = (Map<string>) map2.get("field");                          Map<string> record2 = (Map<string>) map2.get("record");                          String catagory2 = map2.get("categoryId").toString();                          List<salarygroupvo> groupList2 = salaryGroupService.getSalaryGroupsItems(this.getUserCorpId(), catagory2);                          for (SalaryGroupVO cc : groupList2) {                              cc.setCode(cc.getParentId() + cc.getCode());                          }                          //计算                          for (Map.Entry<string> entity : field2.entrySet()) {                              String keyName = entity.getKey();                              for (SalaryGroupVO s2 : groupList2) {                                  if ("bigDecimal".equals(s2.getItemType()) && s2.getCode().equals(field2.get(keyName).toString()) && ("部门" != keyName) && ("姓名" != keyName) && StringUtils.isNotEmpty(s2.getItemType())) {                                      if (field11.containsKey(keyName)) {                                          if (field11.containsKey(keyName)) {                                              String code1 = field11.get(keyName).toString();                                              Double newValue = 0.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<salarygroupvo> 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);              }          }</salarygroupvo></string></salarygroupvo></string></string></string></string></string></map></string></string></string></string>
Copy after login

5. The cheating code | In order to optimize the query speed in the later stage~ quite a lot Business acumen!

What kind of programmer is a good programmer? When we develop systems for customers, we reserve some hidden points for later optimization.

Through the optimization of these buried points, customers can instantly feel that the system has made a qualitative leap in running speed, allowing the company to successfully sign the second-phase development contract and collect huge development fees.

From the company's perspective, such a programmer is a good programmer.

For example:

Java code example analysis

6. Cheating code | How did you get played by an anomaly and then become an anomaly?

People who play Java will be abused by various exceptions at the beginning, and null pointers should be the most common one. After playing for two more years, I started to play abnormally, and all kinds of weird and abnormal gameplay emerged in an endless stream.

Do you think the following definition of anomaly is appropriate?

/**   * 处理业务的异常   * 居然有一堆静态异常,准备好了随时可以抛??   * 错误码是字符串   */  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);    //省略构造函数、get/set方法  }
Copy after login

If it’s not appropriate, what’s the problem?

7. Cheating code | Stream is the most played code, everyone who has seen it is shocked!

Stream, as a highlight of Java 8, is a completely different concept from InputStream and OutputStream in the java.io package. Stream in Java 8 is an enhancement to the functionality of Collection objects. It focuses on performing various very convenient and efficient aggregation operations (aggregate operations) or bulk data operations (bulk data operations) on collection objects. The Stream API greatly improves programming efficiency and program readability with the help of the newly emerged Lambda expression.

Java code example analysis

Stream usage:

//Stream 用的66的  final EventAction eventAction = 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("事件触发信息不存在"))                  , 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;                  })  // 获取该被邀请人所有未过期且未被领取的线索的线索                  .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("参数错误"));                              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);                                      });                          }                  );
Copy after login

The above is the detailed content of Java code example analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template