Java程序员的10条戒律

高分思路!挑战7天完成一篇网状meta DAY1-7 PASSION!继续析挑战,7天完成一篇网状meta分! 阅读详情

There are many standards and best practices for Java Developers out there. This article outlines ten most basic rules that every developer must adhere to and the disastrous outcomes that can follow if these rules are not followed.

1. Add comments to your code. – Everybody knows this, but somehow forgets to follow it. How many times have you "forgotten" to add comments? It is true that the comments do not literally contribute to the functionality of a program. But time and time again you return to the code that you wrote two weeks ago and, for the life of you, you cannot remember what it does! You are lucky if this uncommented code is actually yours. In those cases something may spark your memory. Unfortunately most of the time it is somebody else's, and many times the person is no longer with the company! There is a saying that goes "one hand washes the other." So let's be considerate to one another (and ourselves) and add comments to your code.

2. Do not complicate things. – I have done it before and I am sure all of you have. Developers tend to come up with complicated solutions for the simplest problems. We introduce EJBs into applications that have five users. We implement frameworks that an application just does not need. We add property files, object-oriented solutions, and threads to application that do not require such things. Why do we do it? Some of us just do not know any better, but some of us do it on purpose to learn something new, to make it interesting for ourselves. For those who do not know any better, I recommend reaching out to the more experienced programmers for advice. And to those of us that are willing to complicate the design of an application for personal gains, I suggest being more professional.

3. Keep in Mind – "Less is more" is not always better. – Code efficiency is a great thing, but in many situations writing less lines of code does not improve the efficiency of that code. Let me give you a "simple" example:

if(newStatusCode.equals("SD") && (sellOffDate == null || 
todayDate.compareTo(sellOffDate)<0 || (lastUsedDate != null && 
todayDate.compareTo(lastUsedDate)>0)) || 
(newStatusCode.equals("OBS") && (OBSDate == null || 
todayDate.compareTo(OBSDate)<0))){
		newStatusCode = "NYP";
}

How easy is it to figure out what this "if" condition is doing? Now imagine that whoever wrote this code, did not follow rule number 1 – Add comments to your code.

Wouldn't it be much easier if we could separate this condition into two separate if statements? Now, consider this revised code:

if(newStatusCode.equals("SD") && (sellOffDate == null || 
todayDate.compareTo(sellOffDate)<0 || (lastUsedDate != null && 
todayDate.compareTo(lastUsedDate)>0))){
		newStatusCode = "NYP";
}else 
if(newStatusCode.equals("OBS") && (OBSDate == null || 
todayDate.compareTo(OBSDate)<0))
{
		newStatusCode = "NYP";
}

Isn't it much more readable? Yes, we have repeating statements. Yes, we have one extra "IF" and two extra curly braces, but the code is much more readable and understandable!

4. No hard coding please. – Developers often forget or omit this rule on purpose because we are, as usual, crunched for time. But maybe if we had followed this rule, we would not have ended up in the situation that we are in. How long does it take to write one extra line of code that defines a static final variable?

Here is an example:

public class A {
	
		public static final String S_CONSTANT_ABC = "ABC";
	
		public boolean methodA(String sParam1){
			
			if (A.S_CONSTANT_ABC.equalsIgnoreCase(sParam1)){
				return true;
			}		
			return false;
		}
}

Now every time we need to compare literal "ABC" with some variable, we can reference A.S_CONSTANT_ABC instead of remembering what the actual code is. It is also much easier to modify this constant in one place rather then looking for it though out all of the code.

5. Do not invent your own frameworks. – There are literally thousands of frameworks out there and most of them are open-source. Many of these frameworks are superb solutions that have been used in thousands of applications. We need to keep up to date with the new frameworks, at least superficially. One of the best and most obvious examples of a superb widely used framework is Struts. This open source web framework is a perfect candidate to be used in web-based applications. Please do not come up with your own version of Struts, you will die trying. But you must remember rule number 3 – Do not complicate things. If the application that you are developing has 3 screens – please, do not use Struts, there isn't much "controlling" required for such an application.

6. Say no to Print lines and String Concatenations. – I know that for debugging purposes, developers like to add System.out.println everywhere we see fit. And we say to ourselves that we will delete these later. But we often forget to delete these lines of code or we do not want to delete them. We use System.out.println to test, why would we be touching the code after we have tested it? We might remove a line of code that we actually need! Just so that you do not underestimate the damage of System.out.println, consider the following code:

public class BadCode {
	public static void calculationWithPrint(){
		double someValue = 0D;
		for (int i = 0; i < 10000; i++) {
			System.out.println(someValue = someValue + i);
		}	
	}
	public static void calculationWithOutPrint(){

			double someValue = 0D;
			for (int i = 0; i < 10000; i++) {
				someValue = someValue + i;
			}
		
	}
	public static void main(String [] n) {
		BadCode.calculationWithPrint();
		BadCode.calculationWithOutPrint();
	}
}

In the figure below, you can observe that method calculationWithOutPrint() takes 0.001204 seconds to run. In comparison, it takes a staggering 10.52 seconds to run the calculationWithPrint() method.

(If you would like to know how to produce a table like this, please read my article entitled "Java Profiling with WSAD" Java Profiling with WSAD )

The best way to avoid such CPU waste is to introduce a wrapper method that looks something like this:

public class BadCode {
	
		public static final int DEBUG_MODE = 1;
		public static final int PRODUCTION_MODE = 2;
	
	public static void calculationWithPrint(int logMode){	
		double someValue = 0D;
		for (int i = 0; i < 10000; i++) {
			someValue = someValue + i;
			myPrintMethod(logMode, someValue);
		}
	}
			
	public static void myPrintMethod(int logMode, double value) {
		if (logMode > BadCode.DEBUG_MODE) {	return; }
		System.out.println(value);	
	}
	public static void main(String [] n) {
		BadCode.calculationWithPrint(BadCode.PRODUCTION_MODE);
		}
}

String concatenation is another CPU waster. Consider example below:

public static void concatenateStrings(String startingString) {
		for (int i = 0; i < 20; i++) {
			startingString = startingString + startingString;
		}
	}
	
	public static void concatenateStringsUsingStringBuffer(
String startingString) {
		StringBuffer sb = new StringBuffer();
		sb.append(startingString);
			for (int i = 0; i < 20; i++) {
				sb.append(sb.toString());
			}
}

In the following figure you can see that the method that uses StringBuffer takes .01 seconds to execute where as the methods that use string concatenation takes .08 seconds to execute. The choice is obvious.

7. Pay attention to the GUI. – No matter how absurd it sounds; I repeatedly observe that GUI is as important to the business clients as functionality and performance. The GUI is an essential part of a successful application. Very often IT management tends to overlook the importance of GUI. Many organizations save money by not hiring web designers who have experience in design of "user-friendly" applications. Java developers have to rely on their own HTML skills and their limited knowledge in this area. I have seen too many applications that are "computer friendly" rather then "user friendly". Very rarely I have seen developers that are proficient in both software development and GUI development. If you are this unlucky Java developer who has been assigned to create an application interface, you should follow these three rules:

  1. Do not reinvent the wheel. Look for existing applications that have similar interface requirements.
  2. Create a prototype first. This is a very important step. The clients like to see what they are going to get. It is better for you also because you are going to get their input before you go all out and create an application interface that will leave the clients cold.
  3. Put the user's hat on. In other words, inspect the application requirements from the user's perspective. For example, a summary screen can be created with paging and without. As a software developer, it might be temping for you to omit paging from the application because it is so much less complicated. But, from the client's perspective, it might not be the best solution because the summary results can hold hundreds of rows of data.

8. Always Prepare Document Requirements. – Every business requirement must be documented. This could be true in some fairy tale, but it is far from that in the real world. No matter how time-pressed your development is, no matter how tight the deadlines, you must always make sure that every business requirement is documented.

9. Unit-test. Unit-test. Unit-test. – I am not going to go into any details as to what is the best way to unit-test your code. I am just going to say that that it must be done. This is the most basic rule of programming. This is one rule that, above all, cannot be omitted. It would be great if your fellow developer could create and execute a test plan for your code, but if that is not possible, you must do it yourself. When creating a unit test plan, follow these basic rules:

  1. Write the unit test before writing code for class it tests.
  2. Capture code comments in unit tests.
  3. Test all the public methods that perform an "interesting" function (that is, not getters and setters, unless they do their getting and setting in some unique way).

10. Remember – quality, not quantity. - Do not stay late (when you do not have to). I understand that sometimes production problems, urgent deadlines, and unexpected events might prevent us from leaving work on time. But, managers do not appreciate and reward their employees because they stay late on regular basis, they appreciate them because they do quality work. If you follow the rules that I outline above, you will find yourself producing less buggy and more maintainable code. That is the most important part of your job.

 

相关推荐

Paho Asynchronous MQTT C Client Library--MQTTAsync API

异步MQTT 客户端库for C

yoyo勰的博客 1264

My Ten Commandments for Good Teaching

Know the material Want to teach Genuinely respectyour students and show it Set the bar high; students will measure up Emphasize understanding; de-emphasize memorization ...

weixin_34401479的博客 229

20道SpringSecurity常见面试题汇总(超详细回答 !!!)

本文中,我们将探讨一些与 Spring Security 相关的面试问题。Spring Security 是一款流行的 Java 应用程序安全框架,它提供了一套全面且易于使用的安全解决方案。

小斜同学的博客 3076

Java程序员应该遵循的10条戒律

http://soft.chinabyte.com/database/459/12317459.shtml   Java程序员有许多应遵循的守则或最佳实践方式。本文概述了每个开发者最应该遵循的10条守则或戒律,如果不遵循它们,将会导致灾难性后果。   1. 为代码添加注释(Add comments to your code)。 – 每个人都知道这一点,但不是每个人都会这么做。你有多少次“忘记...

weixin_34018202的博客 145

<工控><PLC>汇川Easy521系列PLC与汇川SV630N伺服进行EtherCat通讯的相关配置及指令编写

本系列是关于PLC相关的博文,包括PLC编程、PLC与上位机通讯、PLC与下位驱动、仪器仪表等通讯、PLC指令解析等相关内容。PLC品牌包括但不限于西门子、三菱等国外品牌,汇川、信捷等国内品牌。除了PLC为主要内容外,PLC相关元器件如触摸屏(HMI)、交换机等工控产品,如果有值得记录的内容,也会添加进来。

用沸腾的热血,支付我们的人生吧! 2万+

LLM - windows下的Dify离线部署:从镜像打包到无网环境部署(亲测,包含插件部署)

LLM - windows下的Dify离线部署:从镜像打包到无网环境部署(亲测,包含插件部署)

ocean00008899的博客 1285

Java程序员应该遵循的十条戒律

Java程序员应该遵循的十条戒律 Java程序员有许多应遵循的守则或最佳实践方式。本文概述了每个开发者最应该遵循的10条守则或戒律,如果不遵循它们,将会导致灾难性后果。   1:为代码添加注释。每个人都知道这一点,但不是每个人都会这么做。你有多少次“忘记”添加注释了?确实,注释不会为你的程序增加任何函数功能。但是,有多少次,看到2周前写的代码,你都记不起它是干...

weixin_33834628的博客 192

mongoDB 数据莫名其妙的没了

问题 之前没有接触过mongoDB,然后接手一个项目使用的是MongoDB,我就跟着网上的教程搭建一个MongoDB的服务,并运行起来。 一开始没有啥问题,成功的把服务与MongoDB都启动以来,运行也没有问题。但是过了几天,我再次打开时发现,以前的数据神奇的消失了。我还在想,是有什么定时清除的么,还是什么原因导致崩了然后数据就被清理了。 查找原因 第一次遇到我没有在意,重启了一下MongoDB,...

技术熊的博客小窝 1万+

给Java开发者的10条戒律

1.给你的代码加注解—每个人都知道这一点,但是总会有人忘记遵守。你有多少次“忘记”加注解了?的却不加文字注解有助于程序的功能性。但是一次又一你返回两星期前写的代码,结果你想不起来那是什么了!如果这个未注解的代码确实是你写的那你就是幸运的了。因为在那些代码中可以唤起你的记忆。不幸的是,大多数的时候代码是别人写的,而且他已将离开了公司!有句谚语是这样说的“自己的事情自己做”。所以为了别人或是我们自己考

wangdabin_1216的专栏 596

Debian 12 安装nodejs(包括node、npm、npx、yarn、pnpm、cnpm、bun)

【代码】Debian 12 安装nodejs。

mirana的专栏 8004

AI原生应用中的数据治理:从采集到应用的完整方案

当AI从"辅助工具"进化为"应用核心"(如ChatGPT、智能驾驶系统),传统数据管理方式已无法满足需求:模型需要更精准的训练数据、业务需要更实时的决策支持、法规需要更严格的隐私保护。本文聚焦AI原生应用的数据全生命周期治理(从采集→清洗→标注→存储→应用→归档的完整链路),覆盖技术方案、工具选择和实践要点。本文将按"场景引入→核心概念→技术方案→实战案例→未来趋势"的逻辑展开,重点通过"奶茶店原料管理"类比,解释数据治理的关键环节;结合Python代码演示核心技术(如异常值检测、主动学习标注);

SuperAGI2025 882

成为优秀Java程序员的10大技巧

一个最成功的、也是被广泛使用的例子是Struts框架,这个开源的web框架是建立web系统的极佳选择,不要试图构造你自己的Struts版本,会累死的。如果你要开发的系统只有3个界面,就不要用Struts. 对于这样一个系统,没有足够的需要被“控制”的东西(译注:Struts将界面做MVC划分,C即controller,所以作者说there isn’t much “controlling” required)。你很幸运,那些未注释的代码是你自己写的,你脑海中还会有残存的印象。仅仅知道是不够的,还要遵循它们。

2301_78145669的博客 338

华为OD技术面真题 - Python开发 - 2

汇总华为OD技术面八股Python八股,高频技术真题并提供详细解答。

qq_45776114的博客 910

Java程序员的十条戒律

10 Commandments for Java Developers

lylhelin的专栏 145

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

java程序员应该遵循的10条守则

Java程序员有许多应遵循的守则或最佳实践方式。本文概述了每个开发者最应该遵循的10条守则或戒律,如果不遵循它们,将会导致灾难性后果。 1. 为代码添加注释(Add comments to your code). – 每个人都知道这一点,但不是每个人都会这么做。你有多少次“忘记”添加注释了?确实,注释不会为你的程序增加任何函数功能。但是,有多少次,看到2周前写的代码,你都记...

weixin_34356138的博客 148

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

如何成为优秀Java程序员的10大技巧

Java程序员有许多应遵循的守则或最佳实践方式。本文概述了每个开发者最应该遵循的10条守则或戒律,如果不遵循它们,将会导致灾难性后果。 01 为代码添加注释 为代码添加注释,每个人都知道这一点,但不是每个人都会这么做。你有多少次“忘记”添加注释了?确实,注释不会为你的程序增加任何函数功能。但是,有多少次,看到2周前写的代码,你都记不起它是干什么的?你很幸运,那些未注释的代码是你自己写的,你脑...

weixin_45442745的博客 251

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

程序员的禅修之路

做一名禅修程序员意味着什么?那意味着,你要持守我从禅宗 习得的10条戒律,它们与计算机程序员的现代世界息息相关。 早晨,外面下着雨,我发觉自己正坐在办公桌上琢磨有关高效率工作(efficient working)的问题。在我成为自由职业者之前的那些日子,尽管做了许多工作,然而回首往昔,不过是一片狼藉罢了。 回想2006年我开始禅修之际,当时有好一阵子,这种念头清晰地浮现在我的脑海里:几百年

just do IT 1390

禅修程序员十诫

做一名禅修程序员意味着什么?那意味着,你要持守我从禅宗 习得的10条戒律,它们与计算机程序员的现代世界息息相关。 早晨,外面下着雨,我发觉自己正坐在办公桌上琢磨有关高效率工作(efficient working)的问题。在我成为自由职业者之前的那些日子,尽管做了许多工作,然而回首往昔,不过是一片狼藉罢了。 回想2006年我开始禅修之际,当时有好一阵子,这种念头清晰地浮现在我的脑海里

446
上一篇: JSP知识点小结
下一篇: 提高应用程序安全性应该考虑的10个方面
andyjava2006
博客等级 码龄20年 1粉丝 9原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值