抽象模型,严谨代码,开源分享

2024-04-01 21:58

本文主要是介绍抽象模型,严谨代码,开源分享,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言
    首先,感谢Eric对我代码上的建议,感谢Stone在FTP Lab环境部署上对我的指导。

    今年4月份的时候,做了一个小的项目,当时也没有去总结整理,现在想想总结整理是很有必要的,这也是一个很好的工作研究的习惯。

    关于项目,不论大小,其实做到极致也不是一件容易的事。只有做到极致,才算真正的项目经验;只有做到极致,才能让编程真正成为一门艺术;只有体会编程是一门有趣的艺术时,你的职业生涯才经久不衰,常青不老。

    当然,我现在也只是一个走在编程艺术道路上的小孩,不停探索,充满好奇,我也希望志同道合的同仁们给我指教与分享。

    我相信,只有开源了,才会有更多更大的进步,才会有活力,有创造力。我支持开源与自由,我唾弃陈旧死板的开发与管理!


项目简介
    略......

编程点滴

1. 同样一个文件能只打开一次搞定的,就只打开一次,避免频繁的I/O流操作。比如:读一个属性文件,文件中有很多属性项目,我们可以将属性项预定义在一个数组里,当打开属性文件时,遍历属性数组,将得到的属性键值对预存在一个哈希表里,这样之后在用到属性值时,只需从哈希表里获取就可以了。

    String[] propertyArray = new String[] { "templateDirectory", "sourceDirectory", "cm",  "filereadyfile", "xmlCMIRPVersion", "expireHour",  "meLimitCount", "fileNamePrefix", "subObjectLimitCount" };  Map<String, String> propertyMap = CommonTool.getPropertyMap(ConstantPool.CM_CONFIGRATION_FILE, propertyArray);  

    public static Map<String, String> getPropertyMap(String cmccCmConfigurationFile, String[] propertyArray) {  InputStream inputStream = null;  Map<String, String> propertyMap = new HashMap<String, String>();  int propertyArrayLength = propertyArray.length;  Properties properties = new Properties();  try {  inputStream = Files.newInputStream(Paths.get(cmccCmConfigurationFile));  properties.load(inputStream);  } catch (IOException ioe) {  LOG.error(ioe.getMessage());  ioe.printStackTrace();  } finally {  IOUtils.closeQuietly(inputStream);  }  for (int index = 0; index < propertyArrayLength; index++) {  String propertyName = propertyArray[index];  String propertyValue = properties.getProperty(propertyName);  if (StringUtils.trimToEmpty(propertyValue).equals("")) {  throw new NullPointerException("There is no property " + propertyName + " in the configuration file " + cmccCmConfigurationFile);  } else {  propertyValue = StringUtils.trim(propertyValue);  }  propertyMap.put(propertyName, propertyValue);  }  return propertyMap;  }  

2. 我们能计算一次搞定的,就只计算一次,比如:我们会经常遍历数组,往往会让数组长度的计算在循环中计算多次,这是低效的。

int propertyArrayLength = propertyArray.length;  for (int index = 0; index < propertyArrayLength; index++) {  ......  
} 

for (int index = 0; index < propertyArray.length; index++) {  ......  
} 

3. 我们处理属性文件时,一定要严谨,比如:有个属性项是表示数量的,当我们获取到该属性项时,我们要对其进行数字正则判断,要不然你得到一个非数字的属性,你怎么拿来运算?

public static boolean isDigit(String str) {  boolean isDigitFlag = false;  if (str.matches("(^[-|+]?)\\d+")) {  isDigitFlag = true;  }  return isDigitFlag;  
}

4. 我们经常会拼凑,传参等方式来定义文件名,所以在这种情况下,有必要对文件名合法性与否作出正则判断。

public static boolean isInvalidFileName(String fileName) {  boolean isInvalidFileNameFlag = false;  if (fileName.matches(".*[\\/:\\*\\?\"<>\\|].*")) {  isInvalidFileNameFlag = true;  }  return isInvalidFileNameFlag;  
} 

5. 我们对特殊字符的处理,也要严谨,考虑方方面面,比如:在文件中将'&'转换成'&amp;','<'转换成'&lt;','>'转换成'&gt;',在这种情况下,你就不能将'&amp;'和'&lt;',以及'&gt;'中的'&'再转换成'&amp;'了。

    public static String replaceReserveSymbel(String convertPartStr) {  if (convertPartStr != null) {  if (convertPartStr.contains("&")) {  StringBuffer sb = new StringBuffer("");  convertPartStr = replaceReserveSymbel(convertPartStr, sb);  }  convertPartStr = convertPartStr.replace("<", "<");  convertPartStr = convertPartStr.replace(">", ">");  convertPartStr = convertPartStr.replace("\\", "\\\\");  convertPartStr = convertPartStr.replace("{", "\\{");  convertPartStr = convertPartStr.replace("}", "\\}");  convertPartStr = convertPartStr.replace("(", "\\(");  convertPartStr = convertPartStr.replace(")", "\\)");  convertPartStr = convertPartStr.replace(",", "\\,");  }  return convertPartStr;  }  public static String replaceReserveSymbel(String convertPartStr, StringBuffer sb) {  int index = convertPartStr.indexOf("&");  String leftStr = "";  String rightStr = "";  if (index >= 0) {  leftStr = convertPartStr.substring(0, index + 1);  rightStr = convertPartStr.substring(index + 1);  sb.append(leftStr);  if (!rightStr.startsWith("amp;") && !rightStr.startsWith("lt;") && !rightStr.startsWith("gt;")) {  sb.append("amp;");  }  replaceReserveSymbel(rightStr, sb);  } else {  sb.append(convertPartStr);  }  return sb.toString();  }  

6. 在多线程编程中,我们很多时候要实现接口Callable<?>, 而非实现接口Runnable,接口Callable<?>给我们带来的方便是不言而喻的,因为,可以重写它的方法call(),获得我们想要的返回值。

    /** * @author shengshu *  */  public class ConverterTask implements Callable<File> {  private static final Logger LOG = Logger.getLogger(ConverterTask.class);  private File templateFile = null;  private File fragmentFile = null;  private String exportDirectoryStr = null;  private String notificationDirectoryStr = null;  public String fileNamePrefix = null;  private static final Date date = new Date();  public ConverterTask(File fragmentFile, File templateFile, String destDirectoryStr, String notificationDirectoryStr, String fileNamePrefix) {  this.fragmentFile = fragmentFile;  this.templateFile = templateFile;  this.exportDirectoryStr = destDirectoryStr;  this.notificationDirectoryStr = notificationDirectoryStr;  this.fileNamePrefix = fileNamePrefix;  }  public File convertFile(File fragmentFile, File templateFile, String exportDirectoryStr, String notificationDirectoryStr, String fileNamePrefix) {  ......  return exportFile;  }  public void convertFile(File fragmentFile, File templateFile, File exportDirectory, File notificationDirectory, String fileNamePrefix) throws Throwable {  convertFile(fragmentFile, templateFile, exportDirectory.getAbsolutePath(), notificationDirectory.getAbsolutePath(), fileNamePrefix);  }  @Override  public File call() throws Exception {  File exportFile = convertFile(fragmentFile, templateFile, exportDirectoryStr, notificationDirectoryStr, fileNamePrefix);  return exportFile;  }  }  

    private static void initConverter() {  LOG.info("Converter thread pool size: " + threadPoolSize);  converterThreadPool = Executors.newFixedThreadPool(threadPoolSize);  converterFutureList = new ArrayList<Future<File>>();  if (sourceDirectory != null && sourceDirectory.isDirectory()) {  fragmentFileCollection = FileUtils.listFiles(sourceDirectory, new String[] { "xml", "XML" }, false);  } else {  LOG.warn("The directory " + sourceDirectoryStr + " doesn't exist or is invalid!");  }  if (templateDirectory != null && templateDirectory.isDirectory()) {  templateFileCollection = FileUtils.listFiles(templateDirectory, new String[] { "xsl", "XSL" }, false);  } else {  LOG.warn("The directory " + templateDirectoryStr + " doesn't exist or is invalid!");  }  }  public void converter() {  LOG.info("==================Converter Start==================");  startTime = System.currentTimeMillis();  initConverter();  if ((fragmentFileCollection != null && !fragmentFileCollection.isEmpty()) && (templateFileCollection != null && !templateFileCollection.isEmpty())) {  Iterator<File> fragmentFileIterator = fragmentFileCollection.iterator();  while (fragmentFileIterator.hasNext()) {  File fragmentFile = fragmentFileIterator.next();  LOG.info("Fragment file: " + fragmentFile);  Iterator<File> templateFileIterator = templateFileCollection.iterator();  while (templateFileIterator.hasNext()) {  File templateFile = templateFileIterator.next();  LOG.info("Template file: " + templateFile);  ConverterTask converterTask = new ConverterTask(fragmentFile, templateFile, exportDirectoryStr, notificationDirectoryStr, fileNamePrefix);  Future<File> converterFuture = converterThreadPool.submit(converterTask);  converterFutureList.add(converterFuture);  }  }  }  destroyConverter();  endTime = System.currentTimeMillis();  deltaTime = endTime - startTime;  LOG.info("Converter spend " + deltaTime / 1000 + " seconds");  LOG.info("==================Converter End==================");  }  private static void destroyConverter() {  LOG.info("===Start to destroy thread pool and delete files under source directory===");  for (Future<File> future : converterFutureList) {  try {  File exportFile = future.get();  if (exportFile.exists()) {  LOG.info("Invoke method call() and return : " + exportFile);  exportFileCollection.add(exportFile);  }  } catch (InterruptedException ie) {  ie.printStackTrace();  } catch (ExecutionException ee) {  ee.printStackTrace();  }  }  converterThreadPool.shutdown();  LOG.info("Thread pool is changed as status: SHUTDOWN");  while (!converterThreadPool.isTerminated())  ;  LOG.info("Thread pool is changed as status: STOP");  if (!CommonTool.deleteFileCollection(fragmentFileCollection)) {  LOG.error("Fail to delete fragment files under directory " + sourceDirectoryStr);  }  LOG.info("===End to destroy thread pool and delete files under source directory===");  }  

7. 我们会经常处理多线程,高并发的问题,往往会用到线程池,所以我们既要保证任务都能被执行,又能保证线程池正常终止。

subSpliterThreadPool.shutdown();  while (!subSpliterThreadPool.isTerminated())  ; 

8. 在处理XML文件时,对XSLT的应用将会大大简化我们的代码逻辑与数量,实现代码与文本处理的解耦。


待续...

这篇关于抽象模型,严谨代码,开源分享的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/868233

相关文章

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义