文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

java代码实例分析

2023-06-16 20:55

关注

这篇文章主要介绍“java代码实例分析”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“java代码实例分析”文章能帮助大家解决问题。

一、几个坑爹代码的目录

这样使用 StringBuffer 的方法有什么坑?

你写过的最长的一行代码有多长???

循环+条件判断,你最多能嵌套几层?

为了后期优化查询速度 ~ 颇有商业头脑!

你是如何被异常玩然后变成玩异常的?

Stream 玩得最 6 的代码,看过的人都惊呆了!

二、坑爹代码 | 这样使用 StringBuffer 的方法有什么坑?

你是否曾经这样使用过 Java 的 StringBuffer 类?

  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 < 10; i++) {              //为什么到这里就要这样写???既然都用StringBuffer了    (这里省略集合遍历用i代替 意思能懂就行)              sb.append("<NSRXX>" +                      "<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>" +                      "</NSRXX>");          }          sb.append("</ROOT>");          System.out.println(sb.toString());      }  }

三、坑爹代码 | 你写过的最长的一行代码有多长???

java代码实例分析

你写过的最长的一行代码有多长吗?你为什么要写这么长?是看着帅呢,还是想减少代码行数?

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());

上面这段代码虽然被拆开多行显示,但本质上是一行,一个极其复杂的赋值语句!

这种代码是不是为了让别人看不懂来彰显自己的编码水平呢?

小编觉得 Java Stream API 以及各种函数式编程方法,以及各种语法糖在某种程度让这种糟糕代码越来越多!

那么一起来批判一下这个代码,或者你有什么好的解决方案呢?

四、坑爹代码 | 循环+条件判断,你最多能嵌套几层?

for 循环和 if 条件判断语句,必不可少吧。但是你见过最多嵌套的循环和条件判断有几层呢?或者说,你最多能容忍多少层的嵌套呢?

java代码实例分析

我们还是先来看看极端的坑爹代码吧:

// 这个***循环嵌套,只是总循环的一部分。。。我已经绕晕在黄桷湾立交          if (recordList.size() > start) {              for (int i = start; i < end; i++) {                  Map<String, Object> map = recordList.get(i);                  Map<String, Object> field11 = (Map<String, Object>) map.get("field"); //name -> code                  Map<String, Object> record11 = (Map<String, Object>) 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<String, Object>> salaryDataVos = page3.getRecords();                      salaryDataVos = this.reSetMap(salaryDataVos, null, null);                      for (Map<String, Object> map2 : salaryDataVos) {                          Map<String, Object> field2 = (Map<String, Object>) map2.get("field");                          Map<String, Object> record2 = (Map<String, Object>) 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, Object> 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);              }          }

五、坑爹代码 | 为了后期优化查询速度 ~ 颇有商业头脑!

什么样的程序员是一个好程序员呢?当我们在给客户开发系统时候,为了后期的优化,预留一些埋点。

通过对这些埋点的优化,可以让客户瞬间感觉系统在运行速度上有质的飞跃,让公司顺利的签署二期开发合同,收取巨额开发费用。

从公司角度来看,这样的程序员就是一个好程序员。 

比如:

java代码实例分析

六、坑爹代码 | 你是如何被异常玩然后变成玩异常的?

玩 Java 的人,刚开始会被各种异常虐,空指针应该是最常见的。多玩两年就开始玩异常,各种奇葩异常玩法层出不穷。

你觉得下面这种异常的定义妥吗?

  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方法  }

如果不妥,有什么问题呢?

七、坑爹代码 | Stream 玩得最 6 的代码,看过的人都惊呆了!

Stream 作为 Java 8 的一大亮点,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念。Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),或者大批量数据操作 (bulk data operation)。Stream API 借助于同样新出现的 Lambda 表达式,极大的提高编程效率和程序可读性。

java代码实例分析

Stream 的用法:

//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);                                      });                          }                  );

关于“java代码实例分析”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网行业资讯频道,小编每天都会为大家更新不同的知识点。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯