结构类似Java中的对象 [英] Struct like objects in Java

查看:148
本文介绍了结构类似Java中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class SomeData1 {
public int x ;
public int y;
}

我可以看到一个类与访问器和变异器比较像Java一样。 p>

  class SomeData2 {
int getX();
void setX(int x);

int getY();
void setY(int y);

private int x;
private int y;
}

第一个例子中的类是非常方便的。

  //一个类中的一个函数
public int f(SomeData1 d){
return(3 * dx)/ dy;
}

这不是那么方便。

  //一个类中的一个函数
public int f(SomeData2 d){
return(3 * d.getX())/ d。的getY();
}


解决方案

这是一个常见的话题。在对象中创建公共字段的缺点是您无法控制对其设置的值。在有许多程序员使用相同代码的组合项目中,重要的是避免副作用。此外,有时最好返回一个字段的对象的副本或以某种方式转换它。你可以在测试中模拟这些方法。如果您创建一个新类,您可能看不到所有可能的操作。这就像防御性编程 - 有一天,getters和setter可能是有帮助的,创建/使用它们并不花费很多。所以他们有时是有用的。



在实践中,大多数领域都有简单的getter和setter。一个可能的解决方案如下所示:

  public property String foo; 
a-> Foo = b-> Foo;

更新:在Java 7或可能永远不会添加属性支持。其他JVM语言,如Groovy,Scala等,现在支持这一功能。 - Alex Miller


Is it completely against the Java way to create struct like objects?

class SomeData1 {
    public int x;
    public int y;
}

I can see a class with accessors and mutators being more Java like.

class SomeData2 {
    int getX();
    void setX(int x);

    int getY();
    void setY(int y);

    private int x;
    private int y;
}

The class from the first example is notationally convenient.

// a function in a class
public int f(SomeData1 d) {
    return (3 * d.x) / d.y;
}

This is not as convenient.

// a function in a class
public int f(SomeData2 d) {
    return (3 * d.getX()) / d.getY();
}

解决方案

This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's object or transform it somehow etc. You can mock such methods in your tests. If you create a new class you might not see all possible actions. It's like defensive programming - someday getters and setters may be helpful, and it doesn't cost a lot to create/use them. So they are sometimes useful.

In practice, most fields have simple getters and setters. A possible solution would look like this:

public property String foo;   
a->Foo = b->Foo;

Update: It's highly unlikely that property support will be added in Java 7 or perhaps ever. Other JVM languages like Groovy, Scala, etc do support this feature now. - Alex Miller

这篇关于结构类似Java中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆