简体   繁体   English

在Java中重构大型switch语句的最佳方法是什么?

[英]What's the best way to refactor a large switch statement in java?

I have a gross switch statement that I need to figure out how to refine. 我有一个总的切换语句,需要弄清楚如何改进。 I immediately think factory pattern, but I don't know if I want to actually use objects for these purposes. 我立即想到了工厂模式,但是我不知道是否要为这些目的实际使用对象。 How could you reduce the verbosity of this code? 您如何减少此代码的冗长性?

If I were to, I would 如果我愿意,我会

  • Define a Validator interface 定义Validator接口
  • Implement this interface for length, width, angle. 实现此接口的长度,宽度,角度。
  • Define a map of <Integer, Validator interface> with key as index and value as the corresponding Validator implementation 定义<Integer, Validator interface>的映射,键为索引,值为相应的Validator实现
  • In the for loop, based on the index, get the appropriate Validator implementation and run it. 在for循环中,基于索引,获取适当的Validator实现并运行它。

HTH. HTH。

Viktor has the preferred solution but if all you are trying to do is reduce the code, but keep the structure you could. Viktor有首选的解决方案,但是如果您要做的只是减少代码,但请保留结构。

change 更改

if (isValidBorrowAmount(amount) == false) {
    isValidValue = false;
    print("That value does not work here");
}

to

isValidValue = isValidBorrowAmount(amount);

and after the switch block put 并在开关块放置后

if(!isValidValue){
    print("That value does not work here");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java(静态类)中重构Utility类的最佳方法是什么 - What is the best way to refactor Utility class in java (static classes) 在Java中创建Statement和ResultSet的最佳方法是什么 - What is the best way to create Statement and ResultSet in java 在Google App Engine中使用Java,什么是存储和访问大型静态数据的最佳方法? - Using Java in Google App Engine, what's the best way to store and access large, static data? 重构 if else 分支的最佳方法是什么 - What is the best way to refactor an if else branch Java 8重构开关语句针对每种情况执行不同的操作 - Java 8 refactor switch statement that does different things for each case 切换AWSCredentialsProviders的最佳方法是什么? - What is the best way to switch AWSCredentialsProviders? 在非常大的树上执行DFS的最佳方法是什么? - What's the best way to perform DFS on a very large tree? 在java中编写和附加大文件的最佳方法是什么 - What is the best way to write and append a large file in java 重构详细的switch case语句 - Refactor a verbose switch case statement 最佳体系结构-收听Java中的原子供稿的最佳方法是什么? - Best Architecture - What's the best way to listen to an atom feed in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM