有没有一种方法来重构这些 if 语句?

huangapple go评论65阅读模式
英文:

Is there a way to refactor these if statements?

问题

只是想知道是否有一种方法重构下面的代码?我对Java还不太熟悉,正在尝试编写DRY(不重复原则)的代码 - 下面是我写的代码,但似乎有很多条件需要检查。

void printDirection() {
  if (yDirection > 0) {
    if (xDirection < 0) {
      println("Travelling South-West");
    } else {
      println("Travelling South-East");
    }
  } else if (yDirection < 0) {
    if (xDirection < 0) {
      println("Travelling North-West");
    } else {
      println("Travelling North-East");
    }
  }
}

提前感谢任何帮助!

英文:

just wondering if there's a way to refactor the below code? I'm new to Java and trying to have DRY code - the below I've written but seems like a lot of conditionals to check

void printDirection() {
  if (yDirection &gt; 0) {
    if (xDirection &lt; 0) {
      println(&quot;Travelling South-West&quot;);
    } else {
      println(&quot;Travelling South-East&quot;);
    }
  } else if (yDirection &lt; 0) {
    if (xDirection &lt;0) {
      println(&quot;Travelling North-West&quot;);
    } else {
      println(&quot;Travelling North-East&quot;);
    }
  }
}

Thanks in advance for any help!

答案1

得分: 8

你可以分别评估北/南和东/西的条件,然后将这些方向组合成你的消息。

System.out.printf("旅行 %s-%s%n", (yDirection < 0 ? "北" : "南"),
                  (xDirection < 0 ? "西" : "东"));

我从你问题中的代码推断出你只关心这四个互补的方向(而不是正北、正东、静止等)。

英文:

You can evaluate the north/south and the east/west conditions individually, and glue the directions into your message.

System.out.printf(&quot;Travelling %s-%s%n&quot;, (yDirection &lt; 0 ? &quot;North&quot; : &quot;South&quot;),
                  (xDirection &lt; 0 ? &quot;West&quot; : &quot;East&quot;));

I assume from the code in your question that you're only concerned about those four complementary directions (not due north, due east, stationary etc.).

答案2

得分: 1

如果您真的想使其更加DRY,可以使用运算符?来实现,但这既不容易阅读也不推荐。它在编程竞赛中被用于尽可能快地进行操作。

它遵循以下模式:
(条件?条件为真时发生的情况:条件为假时发生的情况);
您可以在赋值中使用它:

int i = (a>0)?a:0;

在这种情况下,如果a>0,则i=a,否则a=0。

在您的情况下,我会这样做:

void printDirection() {
    System.out.println("Travelling " + (yDirection > 0 ? "South" : "North") + "-" + (xDirection > 0 ? "East" : "West"));
}
英文:

If you really want to make it DRY, it can be done using the operator ? but It's neither easy to read nor recommanded. It's used in programming contest where the goal is to go as fast as possible.

It follows the scheme :
(Condition?WhatHappenIfConditionIsTrue:WhatHappenIfConditionIsFalse);
You can use it in assignment :

int i = (a&gt;0)?a:0;

in that case, if a>0 then i=a, else a=0

In your case, I would do it like that

void printDirection()
{
	System.out.println(&quot;Travelling &quot; + (yDirection &gt; 0?&quot;South&quot;:&quot;North&quot;) + &quot;-&quot; + (xDirection&gt;0?&quot;East&quot;:&quot;West&quot;));
}

答案3

得分: 0

public class Status {

    public enum Direction {
        SOUTH_WEST((x, y) -> y > 0 && x < 0, "Travelling South-West"),
        SOUTH_EAST((x, y) -> y > 0 && x > 0, "Travelling South-East"),
        NORTH_EAST((x, y) -> x > 0 && y < 0, "Travelling North-East"),
        NORTH_WEST((x, y) -> x < 0 && y < 0, "Travelling North-West"),
        CENTER((x, y) -> x == 0 && y == 0, "");

        BiPredicate<Integer, Integer> bp;
        String desc;

        private Direction(BiPredicate<Integer, Integer> bp, String desc) {
            this.bp = bp;
            this.desc = desc;
        }

        public static Direction getDirection(int x, int y) {
            for (Direction direction : Direction.values()) {
                if (direction.bp.test(x, y)) {
                    return direction;
                }
            }
            return null;
        }
    }

    public static void main(String[] args) {
        Direction d = Direction.getDirection(3, 4);
        System.out.println(d.desc);
        /*if (d == Direction.SOUTH_WEST) {
            System.out.println("do some thing");
        } else if (d == Direction.SOUTH_EAST) {
            System.out.println("do some thing");
        } else if (d == Direction.NORTH_EAST) {
            System.out.println("do some thing");
        } else if (d == Direction.NORTH_WEST) {
            System.out.println("do some thing");
        }*/
    }
}
英文:

Some suggestiones:

  1. Due to x,y combination; there are five states; you can use enum type to define these status;
  2. If you want to reduce if...else statementes in your code, please refer to Status Machine Design Pattern; but i think, under your case, the status is so simple, do not need to make it too complicated
public class Status {
public enum Direction {
SOUTH_WEST((x, y) -&gt; y &gt; 0 &amp;&amp; x &lt; 0, &quot;Travelling South-West&quot;)
, SOUTH_EAST((x, y) -&gt; y &gt;0 &amp;&amp; x &gt; 0, &quot;Travelling South-East&quot;)
, NORTH_EAST((x, y) -&gt; x &gt; 0 &amp;&amp; y &lt; 0, &quot;Travelling North-East&quot;)
, NORTH_WEST((x,y) -&gt; x &lt; 0 &amp;&amp; y &lt; 0, &quot;Travelling North-West&quot;), CENTER((x,y) -&gt; x == 0 &amp;&amp; y == 0, &quot;&quot;);
BiPredicate&lt;Integer, Integer&gt; bp;
String desc;
public BiPredicate&lt;Integer, Integer&gt; getBp() {
return bp;
}
public void setBp(BiPredicate&lt;Integer, Integer&gt; bp) {
this.bp = bp;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
private Direction(BiPredicate&lt;Integer, Integer&gt; bp, String desc) {
this.bp = bp;
this.desc = desc;
}
public static Direction getDirection(int x, int y) {
for (Direction direction : Direction.values()) {
if(direction.getBp().test(x, y)) {
return direction;
}
}
return null;
}
}
public static void main(String[] args) {
Direction d =  Direction.getDirection(3, 4);
System.out.println(d.getDesc());
/*		if(d == Direction.SOUTH_WEST){
System.out.println(&quot;do some thing&quot;);
} else if(d == Direction.SOUTH_EAST){
System.out.println(&quot;do some thing&quot;);
} else if(d == Direction.NORTH_EAST){
System.out.println(&quot;do some thing&quot;);
} else if(d == Direction.NORTH_WEST){
System.out.println(&quot;do some thing&quot;);
}*/
}
}

huangapple
  • 本文由 发表于 2020年3月15日 20:43:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/60693002.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定