您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java 项目工程实例代码分析

2025/11/6 20:04:16发布21次查看
衡量代码好环的原则1 评判代码指标实际上,咱们平时嘴中常说的“好”和“烂”,是对代码质量的一种描述。“好”笼统地表示代码质量高,“烂”笼统地表示代码质量低。对于代码质量的描述,除了“好”“烂”这样比较简单粗暴的描述方式之外,我们也经常会听到很多其他的描述方式。这些描述方法语义更丰富、更专业、更细化。我搜集整理了一下,罗列在了下面,一般有几下几标准,分别是可读性、可维护性、可扩展性、可复用性 、灵活性、可测试性等等
可读性 readability
软件设计大师 martin fowler 曾经说过:“any fool can write code that a computer can understand. good programmers write code that humans can understand.”翻译成中文就是:“任何傻瓜都会编写计算机能理解的代码。好的程序员能够编写人能够理解的代码。”google 内部甚至专门有个认证就叫作 readability。只有拿到这个认证的工程师,才有资格在 code review 的时候,批准别人提交代码。可见代码的可读性有多重要,毕竟,代码被阅读的次数远远超过被编写和执行的次数。
我个人认为,代码的可读性应该是评价代码质量最重要的指标之一。我们在编写代码的时候,时刻要考虑到代码是否易读、易理解。除此之外,代码的可读性在非常大程度上会影响代码的可维护性。毕竟,不管是修改 bug,还是修改添加功能代码,我们首先要做的事情就是读懂代码。代码读不大懂,就很有可能因为考虑不周全,而引入新的 bug。
既然可读性如此重要,那我们又该如何评价一段代码的可读性呢?我们需要看代码是否符合编码规范、命名是否达意、注释是否详尽、函数是否长短合适、模块划分是否清晰、是否符合高内聚低耦合等等。你应该也能感觉到,从正面上,我们很难给出一个覆盖所有评价指标的列表。这也是我们无法量化可读性的原因。
实际上,code review 是一个很好的测验代码可读性的手段。如果你的同事可以轻松地读懂你写的代码,那说明你的代码可读性很好;如果同事在读你的代码时,有很多疑问,那就说明你的代码可读性有待提高了
可维护性 maintainability
一般指的是在不破坏原代码设计的前提下,快速修改bug或增加代码,不会带来新bug,表明该代码的维护性比较好。落实到编码开发,所谓的“维护”无外乎就是修改 bug、修改老的代码、添加新的代码之类的工作。所谓“代码易维护”就是指,在不破坏原有代码设计、不引入新的 bug 的情况下,能够快速地修改或者添加代码。所谓“代码不易维护”就是指,修改或者添加代码需要冒着极大的引入新 bug 的风险,并且需要花费很长的时间才能完成。
可扩展性 extensibility
代码面对未来新需求的变化能力,一般来说,开发新需求的时候,不修改原代码或很少修改,即可达到需求开发的能力,通常会预留一些功能扩展点。
可复用性 reusability
尽量避免重复造轮子,即能够沉淀出一些通用的代码逻辑,保持与上层业务代码的解耦
灵活性 flexibility
这个词比较宽泛。通常与可维护性、可扩展性以及可复用性类似
可测试性
主要反映在写单测的时候。从两个方面体现:
1.单元测试是否容易编写;
2.写单元测试的时候,不能依赖环境,远程调用其他服务的借口,尽可能进行mock数据,保持服务之间的解耦。虽然要团队每人都按这个规范走很难,但我们团队有一个强制要求,就是每个功能函数不能超过50行代码,而且要求代码越短越好。
这几个维度是评判代码维度比较重要的几个指标。
2 指导理论高内聚低耦合几乎是每个程序员员都会挂在嘴边的,但这个词太过于宽泛,太过于正确,所以聪明的编程人员们提出了若干面向对象设计原则来衡量代码的优劣:
开闭原则 ocp (the open-close principle)
单一职责原则 srp (single responsibility principle)
依赖倒置原则 dip (dependence inversion principle)
最少知识原则 lkp (least knowledge principle)) / 迪米特法则 (law of demeter)
里氏替换原则 lsp (liskov substitution principle)
接口隔离原则 isp (interface segregation principle)
组合/聚合复用原则 carp (composite/aggregate reuse principle)
这些理论想必大家都很熟悉了,是我们编写代码时的指导方针,按照这些原则开发的代码具有高内聚低耦合的特性,换句话说,我们可以用这些原则来衡量代码的优劣。
代码实现技巧我相信每个工程师都想写出高质量的代码,不想一直写没有成长、被人吐槽的烂代码。那如何才能写出高质量的代码呢?针对什么是高质量的代码,我们刚刚讲到了七个最常用、最重要的评价指标。所以,问如何写出高质量的代码,也就等同于在问,如何写出易维护、易读、易扩展、灵活、简洁、可复用、可测试的代码,但要写好代码,也不是一蹴而就,需要非常多的实践与积累,下面简举例说明:
1 抽像能力抽象思维是我们工程师最重要的思维能力,因为软件技术本质上就是一门抽象的艺术。我们工程师每天都要动用抽象思维,对问题域进行分析、归纳、综合、判断、推理,从而抽象出各种概念,挖掘概念和概念之间的关系,然后通过编程语言实现业务功能,所以,我们大部分的时间并不是在写代码,而是在梳理需求,理清概念,对需求有一个全局的认知。而抽像能力让我及团队切身感受到,它给我们在编码和设计上带来的质的变化。
案例一:异步excel导出
其实导出excel功能在我们工程里随处可见,特别是咱们的运营希望一次性导出越多数据越好,为了不给我们系统带来太大压力,对于大数据量的导出一般异步进行,针对于这样一个简单的功能,那么应该如何抽像呢?
普通的写法:
public string exportxxx(参数) throws exception { //业务实现}public string exportxxx2(参数) throws exception { //业务实现}
抽像写法:
我们其实可以把每个异步导出看作是一个异步任务,而每个任务可导出的内容是不一样的,因此完全可以把导出抽像一个方法,由每个具体实现类去实现导出不同的内容,具体如下:
// export excel public interface iexcelexporttask { string export(bizcommonexporttask exporttask) throws exception;}//样例实现类xxxxexporttask implements iexcelexporttask { string export(bizcommonexporttask exporttask) throws exception{ public string export(bizcommonexporttask exporttask) throws exception { //组织数据筛选条件 testreq queryreq = gsonutils.toobject(exporttask.getinputparams(),testreq.class); string filename = string.format("%s%s%s", exporttask.getuploadfilename(),system.currenttimemillis(),".xlsx"); string downurl = excelservice.uploadexcel(filename, null, new fetcher<preoccupymodel>(preoccupymodel.class) { //循环获取数据 @override public list<testmodel> fetch(int pageno, int pagesize) throws ospexception{ testqueryresp resp = testfethchlogic.fetchrecord(queryreq); return pageno > resp.getpagenum() ? collections.emptylist() :toexcelmodel(resp); } }); return downurl; }}public class xxxxexporttask1 implements iexcelexporttask { @override public string export(bizcommonexporttask exporttask) throws ospexception { testquery query = gsonutils.toobject(exporttask.getinputparams(), testquery .class); string filename = string.format("%s%s%s", exporttask.getuploadfilename(), system.currenttimemillis(), ".xlsx"); return excelservice.uploadexcel(filename, null, new fetcher<exportitemmodel>(testmodel.class) { @override public list<testmodel> fetch(int pageno, int pagesize) throws ospexception { return xxxxlogic.queryexportitem(query, pageno, pagesize); } }); }}//导出任务分发器public class exceltaskdispacther extends applicationobjectsupport { public boolean dispacthtask(long taskid) throws ospexception { updatetaskstatus(exporttask,commonexportstatus.creating,transferexportstatus.creating,stringutils.empty); try { string beanname = getbeanname(); exporttaskhandler exporttaskhandler = getapplicationcontext().getbean(beanname , iexcelexporttask .class); if(exporttaskhandler == null) { log.warn(string.format("任务id[%s]写入配置错误!", taskid)); return false; } updatetaskstatus(exporttask,commonexportstatus.create_success,transferexportstatus.create_success,stringutils.empty); log.info(string.format("任务id[%s]rfid为[%s]处理成功", exporttask.getid(),rfid)); return true; } catch(busiexception ex) { log.info("任务id[{}]失败,原因:{}", exporttask.getid(),ex.getmessage(),ex); updatetaskresult(); } catch(exception ex) { log.info("任务id[{}]失败,原因:{}", exporttask.getid(),ex.getmessage(),ex); updatetaskresult(); } return false; }}
案例二:系统通知
在微服务化流行的今天,为了提升系统吞吐量,系统职责越来越细,各系统模块需要频繁交互数据,那么对于复杂的数据交互场景,比如我们调拨单,调拨单在扭转的过程中需要与很多系统交互,跟门店、仓库、库存模块有非常多的交互,我们又该如何抽像呢,以下是调拨与各系统交互的代码示例
//接口定义public interface biznotificationhandler { /** * 抛异常会当失败处理 * 是否需要重试由biznotificationstatus返回状态来决定 * @param biznotification * @return * @throws ospexception */ biznotificationstatus handlenotification(biznotification biznotification) throws ospexception;}//推送调拨差异数据给库存系统public class syncdifftosimsandbackquotahandler implements biznotificationhandler { @override public biznotificationstatus handlenotification(biznotification biznotification) throws ospexception { //业务逻辑实现 return biznotificationstatus.process_success; }}//占用库存public class transferoccupyinventoryhandler implements biznotificationhandler { @override public biznotificationstatus handlenotification(biznotification biznotification) throws ospexception { //业务实现 }}//在gpdc生成新条码public class gpdcgeneratenewbarcodehandler implements biznotificationhandler { @override public biznotificationstatus handlenotification(biznotification biznotification) throws ospexception { //业务代码实现 }}
其实我们在与其它系统交互的时候,我们可以把每一个交互动作抽像成一个通知事件,每次交互的时候,写一个事件通知事件即可。
2 组合/聚合复用原则&emsp;&emsp;关于组合/聚合复用原则,其实我们在项目过程会经常遇到,比如项目里会经常管理各种单据,像采购单、调拨单、收货单等,而对于每种单据都会有各种各样的较验,我们先来看一段建调拨单代码,具体如何下:
//接口定义public interface transfervalidator { boolean validator(createtransferctx ctx) throws ospexception;}//接口实现1public class w2scrosspoqtyvalidator implements transfervalidator { @override public boolean validator(createtransferctx ctx) throws ospexception { //较验器代码实现 }//接口实现2public class w2sstorebarcodesalelimitvalidator implements transfervalidator { @override public boolean validator(createtransferctx ctx) throws ospexception { //较验器代码实现 }}//较验器组装public class transfervalidators { public validatorchain newchain() { return new validatorchain(); } public class validatorchain { private final list<transfervalidator> validators = new arraylist<>(); public validatorchain qtyvalidator() { validators.add(qtyvalidator); return this; } public validatorchain transferroutecfgvalidator() { validators.add(transferroutecfgvalidator); return this; } public validatorchain prodvalidator() { validators.add(prodvalidator); return this; } public validatorchain w2swarehousestorevalidator() { validators.add(w2swarehousestorevalidator); return this; } public validatorchain w2sstorebarcodesalelimitvalidator() { validators.add(w2sstorebarcodesalelimitvalidator); return this; } public validatorchain w2sassignpovalidator() { validators.add(w2sassignpovalidator); return this; } public validatorchain w2scrosspovalidator() { validators.add(w2scrosspovalidator); return this; } public validatorchain w2scrosspoqtyvalidator() { validators.add(w2scrosspoqtyvalidator); return this; } public validatorchain w2scross4xupvalidator() { validators.add(w2scross4xupvalidator); return this; } public validatorchain repeatlinevalidator() { validators.add(repeatlinevalidator); return this; } public validatorchain sstradebarcodevalidator() { validators.add(sstradebarcodevalidator); return this; } public validatorchain s2wwarehousestorevalidator() { validators.add(s2wwarehousestorevalidator); return this; } public boolean validator(createtransferctx ctx) throws ospexception { for (transfervalidator validator : validators) { if (!validator.validator(ctx)) { return false; } } return true; } }}//业务代码使用public interface transfercreator { boolean createorder(createtransferctx ctx) throws ospexception;}public abstract class defaulttransfercreator implements transfercreator { @override public boolean createorder(createtransferctx ctx) throws ospexception { validator(ctx) //实现业务逻辑 } protected abstract boolean validator(createtransferctx ctx) throws ospexception; }//店仓调拨单 public class s2wrefundcreator extends defaulttransfercreator { //较验器自由组装 @override protected boolean validator(createtransferctx ctx) throws ospexception { return transfervalidators.newchain() .qtyvalidator() .transferroutecfgvalidator() .prodvalidator() .validator(ctx); }}
以上就是java 项目工程实例代码分析的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product