一致性和Use Right Tool For Right Job哪个重要?

本文讨论了一个具体的软件测试案例,涉及使用jMock和EasyMock框架进行单元测试,并探讨了一致性和选用合适工具之间的平衡。
这个争执发生在测试的时候。
背景是这样的:
一个接口有很多乱七八糟的业务相关的方法,其中有这么四个方法:
[code]
interface TaxLawBuckets {
double getRemaining401k();
double getRemaining403g();
void apply401k(double amount);
void apply403g(double amount);
}
[/code]
当然,这个设计有点不是很好。更好的也许是:
[code]
interface TaxLawBuckets {
TaxLawBucket get401k();
TaxLawBucket get403g();
}
interface TaxLawBucket {
double getRemaining();
void apply(double amount);
}
[/code]
不过,因为种种原因,无法采用这个设计(主要是这么一改,改动会比较大,这个系统里面有一个wsdl代码生成器,这个生成器对接口长的样子有变态的要求)。所以就凑合着把。


现在要制作一个PerAccountTaxLawBuckets类,这个类会对401k和403g有额外的逻辑处理:
[code]
interface TaxLawBuckets {
private double bucket_401k;
private double bucket_403g;
private TaxLawBuckets globalBuckets;

public double getRemaining401k(){
return Math.min(bucket_401k, globalBuckets.getRemaining401k());
}
public double getRemaining403g() {
return Math.min(bucket_403g, globalBuckets.getRemaining403g());
}
public void apply401k(double amount) {
bucket_401k -= amount;
if(bucket_401k<0) throw new SystemException(...);
globalBuckets.apply401k(amount);
}
public void apply403g(double amount) {
bucket_403g -= amount;
if(bucket_403g<0) throw new SystemException(...);
globalBuckets.apply403g(amount);
}
//所有其他的函数都直接委托给globalBuckets。
}
[/code]
恩。有些代码重复。主要还是因为这个接口设计的不好。好在重复不多,凑合吧。

下面要写测试代码了。先看怎么写针对401k的代码。pair用的是jmock。
[code]
public class PerAccountTaxLawBucketsTest extends MockObjectTestCase {
Mock bucketsMock = mock(TaxLawBuckets.class);
TaxLawBuckets globalBuckets = bucketMock.proxy();
PerAccountTaxLawBuckets perAccount = new PerAccountTaxLawBuckets(100, 100, globalBuckets);
public void testGetRemaining401kReturnsTheMinimal() {
bucketsMock.expects(once()).method("getRemaining401k").will(return(200));
assertEquals(100, perAccount.getRemaining401k());
}
...
}
[/code]
其它的测试也都是通过jmock设置expectation,然后从perAccount对象调用对应的函数。

下面注意到401k和403g的逻辑几乎一模一样,只有方法名不同。所以为了避免代码重复,我和pair决定用一个abstract class来抽出共性。然后用两个子类来代表不同之处。pair的代码是这样:

[code]
public abstract class AbstractPerAccountTaxLawBucketsTest extends MockObjectTestCase {
Mock bucketsMock = mock(TaxLawBuckets.class);
TaxLawBuckets globalBuckets = bucketMock.proxy();
PerAccountTaxLawBuckets perAccount = new PerAccountTaxLawBuckets(100, 100, globalBuckets);
public void testGetRemainingReturnsTheMinimal() {
bucketsMock.expects(once()).method(getRemainingName()).will(return(200));
assertEquals(100, getRemaining(perAccount));
}
...
abstract String getRemainingName();
abstract double getRemaining(TaxLawBuckets buckets);
abstract String getApplyName();
abstract void apply(TaxLawBuckets buckets, double amount);
...
}

public class PerAccount401kTestCase extends AbstractPerAccountTaxLawBucketsTest {
String getRemainingName() {
return "getRemaining401k";
}
double getRemaining(TaxLawBuckets buckets) {
return buckets.getRemaining401k();
}
String getApplyName() {
return "apply401k";
}
void apply(TaxLawBuckets buckets, double amount) {
buckets.apply401k(amount);
}
}

public class PerAccount403gTestCase extends AbstractPerAccountTaxLawBucketsTest {
String getRemainingName() {
return "getRemaining403g";
}
double getRemaining(TaxLawBuckets buckets) {
return buckets.getRemaining403g();
}
String getApplyName() {
return "apply403g";
}
void apply(TaxLawBuckets buckets, double amount) {
buckets.apply403g(amount);
}
}
[/code]
而我则不太喜欢getRemainingName()和getRemaining的重复。所以我建议用easymock这样写:
[code]

public abstract class AbstractPerAccountTaxLawBucketsTest extends TestCase {
MockControl bucketsMock = MockControl.createControl(TaxLawBuckets.class);
TaxLawBuckets globalBuckets = bucketMock.getMock();
PerAccountTaxLawBuckets perAccount = new PerAccountTaxLawBuckets(100, 100, globalBuckets);
public void testGetRemainingReturnsTheMinimal() {
bucketsMock.expectsAndReturn(getRemaining(globalBuckets), 200);
bucketsMock.replay();
assertEquals(100, getRemaining(perAccount));
bucketsMock.verify();
}
...
abstract double getRemaining(TaxLawBuckets buckets);
abstract void apply(TaxLawBuckets buckets, double amount);
...
}

public class PerAccount401kTestCase extends AbstractPerAccountTaxLawBucketsTest {
double getRemaining(TaxLawBuckets buckets) {
return buckets.getRemaining401k();
}
void apply(TaxLawBuckets buckets, double amount) {
buckets.apply401k(amount);
}
}

public class PerAccount403gTestCase extends AbstractPerAccountTaxLawBucketsTest {
double getRemaining(TaxLawBuckets buckets) {
return buckets.getRemaining403g();
}
void apply(TaxLawBuckets buckets, double amount) {
buckets.apply403g(amount);
}
}
[/code]
这样,减少了重复,代码感觉更干净。

其实,这个例子简化了问题。实际的那个程序,除了getRemaining(), apply()之外,还有restore()和其他几个方法,也是401k和403g除了方法名字不同其他都一样。

但是,pair一听说用easymock直接就把这个方案枪毙了。pair的观点:
为了保持一致性,我们应该都用jmock。使用easymock会给公司里别的程序员带来理解上的困难。(我很心虚地想,我的几个test case都是用的easymock亚。)


对这个说法,我有点不知道如何说了。我一直以来的观点,都是use the right tool for the right job。
如果工具甲能够做功能1,2,3,4,工具乙能够做功能3,4,5,6。那么我不会为了保持一致性而强迫只用甲或者只用乙。而如果一个公司标准的ComplexTool能够做功能1,2,3,4,5,6,一个业界标准的SimpleTool(比如java.util.HashMap)能做功能1,而我又不需要功能2,3,4,5,6,那么我会选择SimpleTool。

何况,在一个比较强调技术的公司,担心大家不会用easymock或者jmock真的必要么?毕竟不管jmock还是easymock应该都是半个小时就能掌握的冬冬把?

其实,这种关于强调一致性的问题我已经和同事有若干次分歧了。另外一次是:公司里大多用一个内部做的MyPropertyFactory framework来读取class path里面的property文件内容。而我有一次独立开发的一个模块直接使用了ClassLoader.loadResourceAsInputStream()。于是,同事以一致性为理由要求我更改代码来使用MyPropertyFactory。具体细节在下一次disagree里面会解释。


那么,一致性和use the right tool真的是矛盾的么?你怎么在两者之间取得平衡呢?
【EI复现】基于深度强化学习的微能源网能量管理与优化策略研究(Python代码实现)内容概要:本文围绕“基于深度强化学习的微能源网能量管理与优化策略”展开研究,重点利用深度Q网络(DQN)等深度强化学习算法对微能源网中的能量调度进行建模与优化,旨在应对可再生能源出力波动、负荷变化及运行成本等问题。文中结合Python代码实现,构建了包含光伏、储能、负荷等元素的微能源网模型,通过强化学习智能体动态决策能量分配策略,实现经济性、稳定性能效的多重优化目标,并可能与其他优化算法进行对比分析以验证有效性。研究属于电力系统与人工智能交叉领域,具有较强的工程应用背景学术参考价值。; 适合人群:具备一定Python编程基础机器学习基础知识,从事电力系统、能源互联网、智能优化等相关方向的研究生、科研人员及工程技术人员。; 使用场景及目标:①学习如何将深度强化学习应用于微能源网的能量管理;②掌握DQN等算法在实际能源系统调度中的建模与实现方法;③为相关课题研究或项目开发提供代码参考技术思路。; 阅读建议:建议读者结合提供的Python代码进行实践操作,理解环境建模、状态空间、动作空间及奖励函数的设计逻辑,同时可扩展学习其他强化学习算法在能源系统中的应用。
从hdfs到mysql报错Warning: /usr/local/sqoop/../hcatalog does not exist! HCatalog jobs will fail. Please set $HCAT_HOME to the root of your HCatalog installation. Warning: /usr/local/sqoop/../accumulo does not exist! Accumulo imports will fail. Please set $ACCUMULO_HOME to the root of your Accumulo installation. Warning: /usr/local/sqoop/../zookeeper does not exist! Accumulo imports will fail. Please set $ZOOKEEPER_HOME to the root of your Zookeeper installation. 错误: 找不到或无法加载主类 org.apache.hadoop.hbase.util.GetJavaProperty 2025-06-05 17:41:55,556 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6 2025-06-05 17:41:55,583 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead. 2025-06-05 17:41:55,664 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset. 2025-06-05 17:41:55,664 INFO tool.CodeGenTool: Using existing jar: /tmp/sqoop-hadoop/compile/8b77c7c2bee6c4dd7f3856618f5f8556/user_action.jar 2025-06-05 17:41:55,668 INFO mapreduce.ExportJobBase: Beginning export of user_action 2025-06-05 17:41:55,668 INFO Configuration.deprecation: mapred.job.tracker is deprecated. Instead, use mapreduce.jobtracker.address 2025-06-05 17:41:55,827 INFO Configuration.deprecation: mapred.jar is deprecated. Instead, use mapreduce.job.jar 2025-06-05 17:41:56,366 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false Thu Jun 05 17:41:56 CST 2025 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. 2025-06-05 17:41:56,900 INFO Configuration.deprecation: mapred.reduce.tasks.speculative.execution is deprecated. Instead, use mapreduce.reduce.speculative 2025-06-05 17:41:56,902 INFO Configuration.deprecation: mapred.map.tasks.speculative.execution is deprecated. Instead, use mapreduce.map.speculative 2025-06-05 17:41:56,904 INFO Configuration.deprecation: mapred.map.tasks is deprecated. Instead, use mapreduce.job.maps 2025-06-05 17:41:56,967 INFO impl.MetricsConfig: loaded properties from hadoop-metrics2.properties 2025-06-05 17:41:57,035 INFO impl.MetricsSystemImpl: Scheduled Metric snapshot period at 10 second(s). 2025-06-05 17:41:57,035 INFO impl.MetricsSystemImpl: JobTracker metrics system started 2025-06-05 17:41:57,104 INFO input.FileInputFormat: Total input files to process : 1 2025-06-05 17:41:57,111 INFO input.FileInputFormat: Total input files to process : 1 2025-06-05 17:41:57,139 INFO mapreduce.JobSubmitter: number of splits:4 2025-06-05 17:41:57,159 INFO Configuration.deprecation: mapred.map.tasks.speculative.execution is deprecated. Instead, use mapreduce.map.speculative 2025-06-05 17:41:57,236 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_local1705881514_0001 2025-06-05 17:41:57,236 INFO mapreduce.JobSubmitter: Executing with tokens: [] 2025-06-05 17:41:57,374 INFO mapred.LocalDistributedCacheManager: Creating symlink: /usr/local/hadoop/tmp/mapred/local/1749116517294/libjars <- /usr/local/sqoop/libjars/* 2025-06-05 17:41:57,376 INFO mapred.LocalDistributedCacheManager: Localized file:/tmp/hadoop/mapred/staging/hadoop1705881514/.staging/job_local1705881514_0001/libjars as file:/usr/local/hadoop/tmp/mapred/local/1749116517294/libjars 2025-06-05 17:41:57,408 INFO mapreduce.Job: The url to track the job: http://localhost:8080/ 2025-06-05 17:41:57,409 INFO mapreduce.Job: Running job: job_local1705881514_0001 2025-06-05 17:41:57,413 INFO mapred.LocalJobRunner: OutputCommitter set in config null 2025-06-05 17:41:57,416 INFO mapred.LocalJobRunner: OutputCommitter is org.apache.sqoop.mapreduce.NullOutputCommitter 2025-06-05 17:41:57,455 INFO mapred.LocalJobRunner: Waiting for map tasks 2025-06-05 17:41:57,456 INFO mapred.LocalJobRunner: Starting task: attempt_local1705881514_0001_m_000000_0 2025-06-05 17:41:57,492 INFO mapred.Task: Using ResourceCalculatorProcessTree : [ ] 2025-06-05 17:41:57,499 INFO mapred.MapTask: Processing split: Paths:/user/hive/warehouse/dblab.db/user_action/000000_0:11692413+1948736,/user/hive/warehouse/dblab.db/user_action/000000_0:13641149+1948737 2025-06-05 17:41:57,507 INFO Configuration.deprecation: map.input.file is deprecated. Instead, use mapreduce.map.input.file 2025-06-05 17:41:57,507 INFO Configuration.deprecation: map.input.start is deprecated. Instead, use mapreduce.map.input.start 2025-06-05 17:41:57,507 INFO Configuration.deprecation: map.input.length is deprecated. Instead, use mapreduce.map.input.length 2025-06-05 17:41:57,515 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false Thu Jun 05 17:41:57 CST 2025 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. 2025-06-05 17:41:57,543 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false 2025-06-05 17:41:57,548 INFO mapreduce.AutoProgressMapper: Auto-progress thread is finished. keepGoing=false 2025-06-05 17:41:57,551 INFO mapred.LocalJobRunner: Starting task: attempt_local1705881514_0001_m_000001_0 2025-06-05 17:41:57,552 INFO mapred.Task: Using ResourceCalculatorProcessTree : [ ] 2025-06-05 17:41:57,553 INFO mapred.MapTask: Processing split: Paths:/user/hive/warehouse/dblab.db/user_action/000000_0:0+3897471 2025-06-05 17:41:57,562 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false Thu Jun 05 17:41:57 CST 2025 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. 2025-06-05 17:41:57,574 INFO mapreduce.AutoProgressMapper: Auto-progress thread is finished. keepGoing=false 2025-06-05 17:41:57,577 INFO mapred.LocalJobRunner: Starting task: attempt_local1705881514_0001_m_000002_0 2025-06-05 17:41:57,578 INFO mapred.Task: Using ResourceCalculatorProcessTree : [ ] 2025-06-05 17:41:57,579 INFO mapred.MapTask: Processing split: Paths:/user/hive/warehouse/dblab.db/user_action/000000_0:3897471+3897471 2025-06-05 17:41:57,583 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false Thu Jun 05 17:41:57 CST 2025 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. 2025-06-05 17:41:57,603 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false 2025-06-05 17:41:57,607 INFO mapreduce.AutoProgressMapper: Auto-progress thread is finished. keepGoing=false 2025-06-05 17:41:57,614 INFO mapred.LocalJobRunner: Starting task: attempt_local1705881514_0001_m_000003_0 2025-06-05 17:41:57,616 INFO mapred.Task: Using ResourceCalculatorProcessTree : [ ] 2025-06-05 17:41:57,617 INFO mapred.MapTask: Processing split: Paths:/user/hive/warehouse/dblab.db/user_action/000000_0:7794942+3897471 2025-06-05 17:41:57,623 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false Thu Jun 05 17:41:57 CST 2025 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. 2025-06-05 17:41:57,638 INFO sasl.SaslDataTransferClient: SASL encryption trust check: localHostTrusted = false, remoteHostTrusted = false 2025-06-05 17:41:57,640 INFO mapreduce.AutoProgressMapper: Auto-progress thread is finished. keepGoing=false 2025-06-05 17:41:57,641 INFO mapred.LocalJobRunner: map task executor complete. 2025-06-05 17:41:57,642 WARN mapred.LocalJobRunner: job_local1705881514_0001 java.lang.Exception: java.io.IOException: java.lang.ClassNotFoundException: user_action at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:492) at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:552) Caused by: java.io.IOException: java.lang.ClassNotFoundException: user_action at org.apache.sqoop.mapreduce.TextExportMapper.setup(TextExportMapper.java:70) at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:143) at org.apache.sqoop.mapreduce.AutoProgressMapper.run(AutoProgressMapper.java:64) at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:799) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:347) at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:271) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.ClassNotFoundException: user_action at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:348) at org.apache.sqoop.mapreduce.TextExportMapper.setup(TextExportMapper.java:66) ... 10 more 2025-06-05 17:41:58,413 INFO mapreduce.Job: Job job_local1705881514_0001 running in uber mode : false 2025-06-05 17:41:58,414 INFO mapreduce.Job: map 0% reduce 0% 2025-06-05 17:41:58,416 INFO mapreduce.Job: Job job_local1705881514_0001 failed with state FAILED due to: NA 2025-06-05 17:41:58,422 INFO mapreduce.Job: Counters: 0 2025-06-05 17:41:58,432 WARN mapreduce.Counters: Group FileSystemCounters is deprecated. Use org.apache.hadoop.mapreduce.FileSystemCounter instead 2025-06-05 17:41:58,434 INFO mapreduce.ExportJobBase: Transferred 0 bytes in 1.5124 seconds (0 bytes/sec) 2025-06-05 17:41:58,436 WARN mapreduce.Counters: Group org.apache.hadoop.mapred.Task$Counter is deprecated. Use org.apache.hadoop.mapreduce.TaskCounter instead 2025-06-05 17:41:58,436 INFO mapreduce.ExportJobBase: Exported 0 records. 2025-06-05 17:41:58,437 ERROR tool.ExportTool: Error during export: Export job failed!
06-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值