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

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

问题描述

是否完全违背了 Java 的方式来创建类似对象的结构?

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

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

我可以看到一个带有访问器和修改器的类更像 Java.

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;
}

这样不太方便.

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

推荐答案

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

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.

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

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

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

更新:在 Java 7 或以后添加属性支持的可能性很小.其他 JVM 语言(如 Groovy、Scala 等)现在确实支持此功能.- 亚历克斯·米勒

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

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