<p>Is it completely against the Java way to create struct like objects?</p>

<pre><code>class SomeData1 {
    public int x;
    public int y;
}
</code></pre>

<p>I can see a class with accessors and mutators being more Java like.</p>

<pre><code>class SomeData2 {
    int getX();
    void setX(int x);

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

    private int x;
    private int y;
}
</code></pre>

<p>The class from the first example is notationally convenient.</p>

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

<p>This is not as convenient.</p>

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

[{'answer_id': 36702, 'author': 'John Topley', 'author_id': 1450, 'author_profile': 'https://Stackoverflow.com/users/1450', 'pm_score': 1, 'selected': False, 'text': "<p>I don't see the harm if you know that it's always going to be a simple struct and that you're never going to want to attach behaviour to it.</p>\n"}, {'answer_id': 36718, 'author': 'brabster', 'author_id': 2362, 'author_profile': 'https://Stackoverflow.com/users/2362', 'pm_score': 2, 'selected': False, 'text': '<p>If the Java way is the OO way, then yes, creating a class with public fields breaks the principles around information hiding which say that an object should manage its own internal state. (So as I\'m not just spouting jargon at you, a benefit of information hiding is that the internal workings of a class are hidden behind an interface - say you wanted to change the mechanism by which your struct class saved one of its fields, you\'ll probably need to go back and change any classes that use the class...)</p>\n\n<p>You also can\'t take advantage of the support for JavaBean naming compliant classes, which will hurt if you decide to, say, use the class in a JavaServer Page which is written using Expression Language.</p>\n\n<p>The JavaWorld article <a href="http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html" rel="nofollow noreferrer">Why Getter and Setter  Methods are Evil</a> article also might be of interest to you in thinking about when not to implement accessor and mutator methods.</p>\n\n<p>If you\'re writing a small solution and want to minimise the amount of code involved, the Java way may not be the right way - I guess it always depends on you and the problem you\'re trying to solve.</p>\n'}, {'answer_id': 36734, 'author': 'Bartosz Bierkowski', 'author_id': 3666, 'author_profile': 'https://Stackoverflow.com/users/3666', 'pm_score': 7, 'selected': True, 'text': "<p>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.</p>\n\n<p>In practice, most fields have simple getters and setters. A possible solution would look like this: </p>\n\n<pre><code>public property String foo;   \na-&gt;Foo = b-&gt;Foo;\n</code></pre>\n\n<p><em>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</em></p>\n"}, {'answer_id': 36747, 'author': 'Jonathan', 'author_id': 1772, 'author_profile': 'https://Stackoverflow.com/users/1772', 'pm_score': 1, 'selected': False, 'text': "<p>This is a question on Object Oriented Design, not Java the language. It's generally good practice to hide data types within the class and expose only the methods that are part of the class API. If you expose internal data types, you can never change them in the future. If you hide them, your only obligation to the user is the method's return and argument types.</p>\n"}, {'answer_id': 36874, 'author': 'Spoike', 'author_id': 3713, 'author_profile': 'https://Stackoverflow.com/users/3713', 'pm_score': 3, 'selected': False, 'text': '<p>By the way, the structure you\'re giving as an example already exist in the Java base class library as <code>java.awt.Point</code>. It has x and y as public fields, <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Point.html" rel="noreferrer">check it out for yourself</a>.</p>\n\n<p>If you know what you\'re doing, and others in your team know about it, then it is okay to have public fields. But you shouldn\'t rely on it because they can cause headaches as in bugs related to developers using objects as if they were stack allocated structs (java objects are always sent to methods as references and not as copies).</p>\n'}, {'answer_id': 36891, 'author': 'izb', 'author_id': 974, 'author_profile': 'https://Stackoverflow.com/users/974', 'pm_score': 8, 'selected': False, 'text': "<p>Use common sense really. If you have something like:</p>\n\n<pre><code>public class ScreenCoord2D{\n    public int x;\n    public int y;\n}\n</code></pre>\n\n<p>Then there's little point in wrapping them up in getters and setters. You're never going to store an x, y coordinate in whole pixels any other way. Getters and setters will only slow you down.</p>\n\n<p>On the other hand, with:</p>\n\n<pre><code>public class BankAccount{\n    public int balance;\n}\n</code></pre>\n\n<p>You might want to change the way a balance is calculated at some point in the future. This should really use getters and setters.</p>\n\n<p>It's always preferable to know <em>why</em> you're applying good practice, so that you know when it's ok to bend the rules.</p>\n"}, {'answer_id': 36944, 'author': 'Mark Renouf', 'author_id': 758, 'author_profile': 'https://Stackoverflow.com/users/758', 'pm_score': 3, 'selected': False, 'text': '<p>Re: aku, izb, John Topley...</p>\n\n<p>Watch out for mutability issues...</p>\n\n<p>It may seem sensible to omit getters/setters. It actually may be ok in some cases. The real problem with the proposed pattern shown here is mutability.</p>\n\n<p>The problem is once you pass an object reference out containing non-final, public fields. Anything else with that reference is free to modify those fields. You no longer have any control over the state of that object. (Think what would happen if Strings were mutable.)</p>\n\n<p>It gets bad when that object is an important part of the internal state of another, you\'ve just exposed internal implementation. To prevent this, a copy of the object must be returned instead. This works, but can cause massive GC pressure from tons of single-use copies created.</p>\n\n<p>If you have public fields, consider making the class read-only. Add the fields as parameters to the constructor, and mark the fields final. Otherwise make sure you\'re not exposing internal state, and if you need to construct new instances for a return value, make sure it won\'t be called excessively.</p>\n\n<p>See: "<a href="http://java.sun.com/docs/books/effective/" rel="noreferrer">Effective Java</a>" by Joshua Bloch -- Item #13: Favor Immutability.</p>\n\n<p>PS: Also keep in mind, all JVMs these days will optimize away the getMethod if possible, resulting in just a single field-read instruction. </p>\n'}, {'answer_id': 38698, 'author': 'Brian', 'author_id': 700, 'author_profile': 'https://Stackoverflow.com/users/700', 'pm_score': 6, 'selected': False, 'text': '<p>To address mutability concerns you can declare x and y as final. For example:</p>\n\n<pre><code>class Data {\n  public final int x;\n  public final int y;\n  public Data( int x, int y){\n    this.x = x;\n    this.y = y;\n  }\n}\n</code></pre>\n\n<p>Calling code that attempts to write to these fields will get a compile time error of "field x is declared final; cannot be assigned".</p>\n\n<p>The client code can then have the \'short-hand\' convenience you described in your post</p>\n\n<pre><code>public class DataTest {\n    public DataTest() {\n        Data data1 = new Data(1, 5);\n        Data data2 = new Data(2, 4);\n        System.out.println(f(data1));\n        System.out.println(f(data2));\n    }\n\n    public int f(Data d) {\n        return (3 * d.x) / d.y;\n    }\n\n    public static void main(String[] args) {\n        DataTest dataTest = new DataTest();\n    }\n}\n</code></pre>\n'}, {'answer_id': 64376, 'author': 'Alex Miller', 'author_id': 7671, 'author_profile': 'https://Stackoverflow.com/users/7671', 'pm_score': 2, 'selected': False, 'text': "<p>The problem with using public field access is the same problem as using new instead of a factory method - if you change your mind later, all existing callers are broken.  So, from an API evolution point of view, it's usually a good idea to bite the bullet and use getters/setters.</p>\n\n<p>One place where I go the other way is when you strongly control access to the class, for example in an inner static class used as an internal data structure.  In this case, it might be much clearer to use field access.</p>\n\n<p>By the way, on e-bartek's assertion, it is highly unlikely IMO that property support will be added in Java 7.  </p>\n"}, {'answer_id': 203722, 'author': 'Kris Nuttycombe', 'author_id': 390636, 'author_profile': 'https://Stackoverflow.com/users/390636', 'pm_score': 2, 'selected': False, 'text': "<p>I frequently use this pattern when building private inner classes to simplify my code, but I would not recommend exposing such objects in a public API. In general, the more frequently you can make objects in your public API immutable the better, and it is not possible to construct your 'struct-like' object in an immutable fashion.</p>\n\n<p>As an aside, even if I were writing this object as a private inner class I would still provide a constructor to simplify the code to initialize the object. Having to have 3 lines of code to get a usable object when one will do is just messy.</p>\n"}, {'answer_id': 203730, 'author': 'cblades', 'author_id': 21305, 'author_profile': 'https://Stackoverflow.com/users/21305', 'pm_score': 0, 'selected': False, 'text': '<p>You can make a simple class with public fields and no methods in Java, but it is still a class and is still handled syntactically and in terms of memory allocation just like a class.  There is no way to genuinely reproduce structs in Java.</p>\n'}, {'answer_id': 312808, 'author': 'PhiLho', 'author_id': 15459, 'author_profile': 'https://Stackoverflow.com/users/15459', 'pm_score': 0, 'selected': False, 'text': '<p>Sometime I use such class, when I need to return multiple values from a method. Of course, such object is short lived and with very limited visibility, so it should be OK.</p>\n'}, {'answer_id': 332162, 'author': 'Steve B.', 'author_id': 19479, 'author_profile': 'https://Stackoverflow.com/users/19479', 'pm_score': 3, 'selected': False, 'text': "<p>I have tried this in a few projects, on the theory that getters and setters clutter up the code with semantically meaningless cruft, and that other languages seem to do just fine with convention-based data-hiding or partitioning of responsibilities (e.g. python). </p>\n\n<p>As others have noted above, there are 2 problems that you run into, and they're not really fixable:</p>\n\n<ul>\n<li>Just about any automated tool in the java world relies on the getter/setter convention. Ditto for, as noted by others, jsp tags, spring configuration, eclipse tools, etc. etc... \nFighting against what your tools expect to see is a recipe for long sessions trolling through google trying to find that non-standard way of initiating spring beans. Really not worth the trouble.</li>\n<li>Once you have your elegantly coded application with hundreds of public variables you will likely find at least one situation where they're insufficient- where you absolutely need immutability, or you need to trigger some event when the variable gets set, or you want to throw an exception on a variable change because it sets an object state to something unpleasant. You're then stuck with the unenviable choices between  cluttering up your code with some special method everywhere the variable is directly referenced, having some special access form for 3 out of the 1000 variables in your application. </li>\n</ul>\n\n<p>And this is in the best case scenario of working entirely in a self-contained private project. Once you export the whole thing to a publicly accessible library these problems will become even larger. </p>\n\n<p>Java is very verbose, and this is a tempting thing to do. Don't do it.</p>\n"}, {'answer_id': 2642464, 'author': 'luis.espinal', 'author_id': 201722, 'author_profile': 'https://Stackoverflow.com/users/201722', 'pm_score': 2, 'selected': False, 'text': "<p>There is nothing wrong with that type of code, provided that the author <strong><em>knows</em></strong> they are structs (or data shuttles) instead of objects. Lots of Java developers can't tell the difference between a well-formed object (not just a subclass of java.lang.Object, but a <em>true</em> object in a specific domain) and a pineapple. Ergo,they end up writing structs when they need objects and viceversa.</p>\n"}, {'answer_id': 2707127, 'author': 'Evvo', 'author_id': 973085, 'author_profile': 'https://Stackoverflow.com/users/973085', 'pm_score': 0, 'selected': False, 'text': "<p>As with most things, there's the general rule and then there are specific circumstances.\nIf you are doing a closed, captured application so that you know how a given object is going to be used, then you can exercise more freedom to favor visibility and/or efficiency.\nIf you're developing a class which is going to be used publicly by others beyond your control, then lean towards the getter/setter model.\nAs with all things, just use common sense.\nIt's often ok to do an initial round with publics and then change them to getter/setters later.</p>\n"}, {'answer_id': 8565711, 'author': 'developer.g', 'author_id': 906421, 'author_profile': 'https://Stackoverflow.com/users/906421', 'pm_score': 8, 'selected': False, 'text': '<p>It appears that many Java people are not familiar with the Sun Java Coding Guidelines\nwhich say it is quite appropriate to use public instance variable when the class is \nessentially a "Struct", if Java supported "struct" (when there is no behavior).</p>\n\n<p>People tend to think getters and setters are the Java way, \nas if they are at the heart of Java. This is not so. If you follow the Sun Java \nCoding Guidelines, using public instance variables in appropriate situations, \nyou are actually writing better code than cluttering it with needless getters and setters.</p>\n\n<p><strong>Java Code Conventions from 1999</strong> and still unchanged.</p>\n\n<p>10.1     Providing Access to Instance and Class Variables</p>\n\n<p>Don\'t make any instance or class variable public without good reason. Often, instance variables don\'t need to be explicitly set or gotten-often that happens as a side effect of method calls.</p>\n\n<p><strong>One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. <em>In other words, if you would have used a struct instead of a class (if Java supported struct), then it\'s appropriate to make the class\'s instance variables public</strong>.</em></p>\n\n<p><a href="http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177" rel="noreferrer">http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177</a></p>\n\n<p><a href="http://en.wikipedia.org/wiki/Plain_old_data_structure" rel="noreferrer">http://en.wikipedia.org/wiki/Plain_old_data_structure</a></p>\n\n<p><a href="http://docs.oracle.com/javase/1.3/docs/guide/collections/designfaq.html#28" rel="noreferrer">http://docs.oracle.com/javase/1.3/docs/guide/collections/designfaq.html#28</a></p>\n'}, {'answer_id': 8566099, 'author': 'necromancer', 'author_id': 621338, 'author_profile': 'https://Stackoverflow.com/users/621338', 'pm_score': 0, 'selected': False, 'text': "<p>Aspect-oriented programming lets you trap assignments or fetches and attach intercepting logic to them, which I propose is the right way to solve the problem.  (The issue of whether they should be public or protected or package-protected is orthogonal.)</p>\n\n<p>Thus you start out with unintercepted fields with the right access qualifier.  As your program requirements grow you attach logic to perhaps validate, make a copy of the object being returned, etc.</p>\n\n<p>The getter/setter philosophy imposes costs on a large number of simple cases where they are not needed.</p>\n\n<p>Whether aspect-style is cleaner or not is somewhat qualitative.  I would find it easy to see just the variables in a class and view the logic separately.  In fact, the raison d'etre for Apect-oriented programming is that many concerns are cross-cutting and compartmentalizing them in the class body itself is not ideal (logging being an example -- if you want to log all gets Java wants you to write a whole bunch of getters and keeping them in sync but AspectJ allows you a one-liner).</p>\n\n<p>The issue of IDE is a red-herring. It is not so much the typing as it is the reading and visual pollution that arises from get/sets.</p>\n\n<p>Annotations seem similar to aspect-oriented programming at first sight however they require you to exhaustively enumerate pointcuts by attaching annotations, as opposed to a concise wild-card-like pointcut specification in AspectJ.</p>\n\n<p>I hope awareness of AspectJ prevents people from prematurely settling on dynamic languages.</p>\n"}, {'answer_id': 14950725, 'author': 'Avik Kumar Goswami', 'author_id': 2085746, 'author_profile': 'https://Stackoverflow.com/users/2085746', 'pm_score': 1, 'selected': False, 'text': '<p>Here I create a program to input Name and Age of 5 different persons and perform a selection sort (age wise). I used an class which act as a structure (like C programming language) and a main class to perform the complete operation. Hereunder I\'m furnishing the code...</p>\n\n<pre><code>import java.io.*;\n\nclass NameList {\n    String name;\n    int age;\n}\n\nclass StructNameAge {\n    public static void main(String [] args) throws IOException {\n\n        NameList nl[]=new NameList[5]; // Create new radix of the structure NameList into \'nl\' object\n        NameList temp=new NameList(); // Create a temporary object of the structure\n\n        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\n        /* Enter data into each radix of \'nl\' object */\n\n        for(int i=0; i&lt;5; i++) {\n            nl[i]=new NameList(); // Assign the structure into each radix\n\n            System.out.print("Name: ");\n            nl[i].name=br.readLine();\n\n            System.out.print("Age: ");\n            nl[i].age=Integer.parseInt(br.readLine());\n\n            System.out.println();\n        }\n\n        /* Perform the sort (Selection Sort Method) */\n\n        for(int i=0; i&lt;4; i++) {\n            for(int j=i+1; j&lt;5; j++) {\n                if(nl[i].age&gt;nl[j].age) {\n                    temp=nl[i];\n                    nl[i]=nl[j];\n                    nl[j]=temp;\n                }\n            }\n        }\n\n        /* Print each radix stored in \'nl\' object */\n\n        for(int i=0; i&lt;5; i++)\n            System.out.println(nl[i].name+" ("+nl[i].age+")");\n    }\n}\n</code></pre>\n\n<p>The above code is Error Free and Tested... Just copy and paste it into your IDE and ... You know and what??? :)</p>\n'}, {'answer_id': 24680006, 'author': 'Lyubomyr Shaydariv', 'author_id': 166589, 'author_profile': 'https://Stackoverflow.com/users/166589', 'pm_score': 2, 'selected': False, 'text': '<p>A very-very old question, but let me make another short contribution. Java 8 introduced lambda expressions and method references. Lambda expressions can be simple method references and not declare a "true" body. But you cannot "convert" a field into a method reference. Thus</p>\n\n<pre class="lang-java prettyprint-override"><code>stream.mapToInt(SomeData1::x)\n</code></pre>\n\n<p>isn\'t legal, but</p>\n\n<pre class="lang-java prettyprint-override"><code>stream.mapToInt(SomeData2::getX)\n</code></pre>\n\n<p>is.</p>\n'}, {'answer_id': 26032324, 'author': 'sampathsris', 'author_id': 1461424, 'author_profile': 'https://Stackoverflow.com/users/1461424', 'pm_score': 4, 'selected': False, 'text': '<h2>Do not use <code>public</code> fields</h2>\n\n<p>Don\'t use <code>public</code> fields when you really want to wrap the internal behavior of a class. Take <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/BufferedReader.java" rel="nofollow noreferrer"><code>java.io.BufferedReader</code></a> for example. It has the following field:</p>\n\n<pre><code>private boolean skipLF = false; // If the next character is a line feed, skip it\n</code></pre>\n\n<p><code>skipLF</code> is read and written in all read methods. What if an external class running in a separate thread maliciously modified the state of <code>skipLF</code> in the middle of a read? <code>BufferedReader</code> will definitely go haywire.</p>\n\n<h2>Do use <code>public</code> fields</h2>\n\n<p>Take this <code>Point</code> class for example:</p>\n\n<pre><code>class Point {\n    private double x;\n    private double y;\n\n    public Point(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    public double getX() {\n        return this.x;\n    }\n\n    public double getY() {\n        return this.y;\n    }\n\n    public void setX(double x) {\n        this.x = x;\n    }\n\n    public void setY(double y) {\n        this.y = y;\n    }\n}\n</code></pre>\n\n<p>This would make calculating the distance between two points very painful to write.</p>\n\n<pre><code>Point a = new Point(5.0, 4.0);\nPoint b = new Point(4.0, 9.0);\ndouble distance = Math.sqrt(Math.pow(b.getX() - a.getX(), 2) + Math.pow(b.getY() - a.getY(), 2));\n</code></pre>\n\n<p>The class does not have any behavior other than plain getters and setters.  It is acceptable to use public fields when the class represents just a data structure, and does not have, <em>and</em> never will have behavior (thin getters and setters is <em>not</em> considered behavior here). It can be written better this way:</p>\n\n<pre><code>class Point {\n    public double x;\n    public double y;\n\n    public Point(double x, double y) {\n        this.x = x;\n        this.y = y;\n    }\n}\n\nPoint a = new Point(5.0, 4.0);\nPoint b = new Point(4.0, 9.0);\ndouble distance = Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));\n</code></pre>\n\n<p>Clean!</p>\n\n<p>But remember: Not only your class must be absent of behavior, but it should also have <em>no</em> reason to have behavior in the future as well.</p>\n\n<hr />\n\n<p>(This is exactly what <a href="https://stackoverflow.com/a/8565711/1461424">this answer</a> describes. To quote <a href="https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177" rel="nofollow noreferrer">"Code Conventions for the Java Programming Language: 10. Programming Practices"</a>:</p>\n\n<blockquote>\n  <p>One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a <code>struct</code> instead of a class (if Java supported <code>struct</code>), then it\'s appropriate to make the class\'s instance variables public.</p>\n</blockquote>\n\n<p>So the official documentation also accepts this practice.)</p>\n\n<hr />\n\n<p>Also, if you\'re extra sure that members of above <code>Point</code> class should be immutable, then you could add <code>final</code> keyword to enforce it:</p>\n\n<pre><code>public final double x;\npublic final double y;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/36701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3836/']