Java 最喜欢的重构技术

发布于 2024-12-01 04:27:32 字数 119 浏览 0 评论 0原文

我在其他人的 Java 代码中发现了一些常见的代码模式,可以从一些简单的重构中受益。

您讨厌的代码模式及其修复方法是什么(以及原因(如果不明显的话))?

我冒昧地回答了一些我自己最讨厌的事情。

There are some common code patterns I find in other people's Java code that can benefit from some simple refactoring.

What are your pet code pattern hates and their fixes (and the reason if it isn't obvious)?

I have taken to liberty of answering with a couple of my own pet hates.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小兔几 2024-12-08 04:27:33

我最喜欢的重构之一是使用策略模式而不是长 if-else/switch 语句。
例如。

String chooser = ""//some sting

if(testCond1(chooser)){
doSomething1();
} else if(testCond2(chooser)){
doSomethingElse2();
} else if(testCond2(chooser)){
doSomethingElse3();
} else if(testCond4(chooser)){
doSomethingElse4();
} else if(testCond5(chooser)){
doSomethingElse5();
} else if(testCond6(chooser)){
doSomethingElse6();
}

可以改为:

    Map<String, Handler> handlers = new HashMap<String, Handler>();

handlers.get(chooser).handle();

然后我们定义一个Handler接口

interface Handler{
    handle();
}

,并且对于每个条件我们都有一个实现该处理程序的新类。

class CondOne implements Handler{
    handle(){
        //some code
    }
}

优点。面向对象的方法,代码更易于维护。在不更改代码重要部分的情况下添加新条件也很容易。

One of my favourite refactoring is using Strategy pattern instead of long if-else/switch statments.
Eg.

String chooser = ""//some sting

if(testCond1(chooser)){
doSomething1();
} else if(testCond2(chooser)){
doSomethingElse2();
} else if(testCond2(chooser)){
doSomethingElse3();
} else if(testCond4(chooser)){
doSomethingElse4();
} else if(testCond5(chooser)){
doSomethingElse5();
} else if(testCond6(chooser)){
doSomethingElse6();
}

Can be changed to:

    Map<String, Handler> handlers = new HashMap<String, Handler>();

handlers.get(chooser).handle();

then we define a Handler interface

interface Handler{
    handle();
}

And for each condition we have a new class that implements the handler.

class CondOne implements Handler{
    handle(){
        //some code
    }
}

Pros. Object oriented approch, code is easier to maintain. It is also easy to add new conditions without changing the important parts of the code.

一刻暧昧 2024-12-08 04:27:33
boolean someMethod() {
    if (<some test>) {
        return true;
    } else {
        return false;
    }
}

替换为

boolean someMethod() {
    return <some test>;
}

指导原则/模式:

  • 更少的代码是好的,
  • 冗余的代码是坏的
boolean someMethod() {
    if (<some test>) {
        return true;
    } else {
        return false;
    }
}

replace with

boolean someMethod() {
    return <some test>;
}

Guiding principles/patterns:

  • less code is good
  • redundant code is bad
转瞬即逝 2024-12-08 04:27:33
void someMethod(SomeClass param) {
    if (param != null) { // or some other test
        // Rest of method code
    }
}

替换为:

void someMethod(SomeClass param) {
    if (param == null) { // or some other test
        return; // or throw exception if test expected to "always" pass
    }
    // Rest of method code
}

指导原则/模式:

  • 缩进
  • 如果块很好,则
  • 越少越好,越短参数检查应该尽早完成并在出现问题时退出,而不是允许代码在传递时执行
void someMethod(SomeClass param) {
    if (param != null) { // or some other test
        // Rest of method code
    }
}

replace with:

void someMethod(SomeClass param) {
    if (param == null) { // or some other test
        return; // or throw exception if test expected to "always" pass
    }
    // Rest of method code
}

Guiding principles/patterns:

  • less indentation is good
  • shorter if blocks are good
  • parameter checking should be done early and exit on problem, rather than allowing code to execute on passing
听风念你 2024-12-08 04:27:33
if (<some test>) {
    return someObject;
} else {
    return someOtherObject;
}

替换为:

if (<some test>) {
    return someObject;
}

return someOtherObject;

或者为了更简洁,如果该行不太长(即您没有内联创建对象):

return <some test> ? someObject : someOtherObject;

指导原则/模式:

  • 更少的代码是好的,
  • 冗余的代码是坏的 - 当 if 返回时,不需要“其他”,
  • 缩进少一点就好
if (<some test>) {
    return someObject;
} else {
    return someOtherObject;
}

replace with:

if (<some test>) {
    return someObject;
}

return someOtherObject;

or for even more brevity and if the line isn't too long (ie you aren't creating the objects in-line):

return <some test> ? someObject : someOtherObject;

Guiding principles/patterns:

  • less code is good
  • redundant code is bad - when an if returns, there is no need for an "else"
  • less indentation is good
若无相欠,怎会相见 2024-12-08 04:27:33

我喜欢枚举并尝试通过大量字符串检查来重构代码。

if (str.equals("A") {...}
else if (str.equals("B") {...}
else if (str.equals("C") {...}

switch (str){
 case A: ... ; break;
 case B: ... ; break;
 case C: ... ; break;

}

I like enums and try to refactor code with a lot of string checks.

if (str.equals("A") {...}
else if (str.equals("B") {...}
else if (str.equals("C") {...}

to

switch (str){
 case A: ... ; break;
 case B: ... ; break;
 case C: ... ; break;

}

萌︼了一个春 2024-12-08 04:27:33

我经常看到这样的代码,但不应该比较引用,而是应该比较内容。

if (someObject == anotherObject) {
   doSomething();
}

所以我将其替换为(如果需要的话覆盖 equals() 和 hashCode()):

if (someObject.equals(anotherObject))  {
   doSomething();
}

Often I see code like this, when not references should be compared, but content.

if (someObject == anotherObject) {
   doSomething();
}

So I replace it with (and if necessary override equals() and hashCode()) :

if (someObject.equals(anotherObject))  {
   doSomething();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文