2

I'm writing a Java class representing some simple geometry.

At the top-most abstract class (which itself is package-private) I have declared attributes that I need be accessed from subclasses in the same package.

If I declare an attribute as final in the AbstractClass,

final int foo;

I'll able to access it in the package directly, without any fuss of a getter method. However. Doing according to "praxis" (or what I believe is the common style) would be:

private final int foo;

which would of course require a non-private getter. The subclasses would have to refer to foo (which is a very relevant and quintessential attribute) as if it were some external object:

this.getFoo();

It adds code and removes the direct way of accessing these members (i.e foo).

Are there any disadvantages of skipping the private modifier, since they're anyway final and I'm not worried of exposing these attributes internally in the package?

I'm aware of OO-advocates claiming that getters/setters is a very natural way for objects to access their own attributes - but when does this make any non-cosmetic, non-[insert any JavaBeans-style thing], difference?

Consider an inner class, Coordinate, which is so simple because it has two int attributes - leaving all usage for class OuterClass:

class OuterClass{
    final static class Coordinate{
        final int x, y;
        Coordinate(int x, int y){
            this.x = x;
            this.y = y;
        }
    }
    Coordinate coordinate;
}

For this inner class - why would I bother with the praxis of creating a getter? A getter would introduce more code and force any class in the same package to call coordinate.getX(); instead of simply coordinate.x;. Any overhead here? Notice the final modifier on the class Coordinate.

tortal
  • 713
  • 1
  • 5
  • 17
  • 3
    There are some people who get all hot and bothered if you allow ANY access to an object's fields from outside the object. To these people it makes a difference. To everyone else, no. – Hot Licks Nov 26 '12 at 01:12
  • @HotLicks : this is my biggest concern actually :) atm for my implementation it certainly doesn't make sense. But I'm also eager to code accordingly to all great coders praxis. I mean, since it's FINAL, then having access (package-private however) to just at LOOKING at the variable, rather than using getter - how can this be wrong? espectially when looking directly produce less ugly paranthesis. – tortal Nov 26 '12 at 01:21
  • There is the concern that if the internals of the class change over time it might be desired to remove the direct access and use an accessor method instead. This is a realistic concern in certain cases (eg, major public interfaces for a widely-used application), but of very little concern for most cases. And the simplicity (and hence fewer errors) of the direct approach may easily outweigh that concern. – Hot Licks Nov 26 '12 at 01:33
  • How would internals change? I'm not knowledgeble enough to understand how it's possible. My idea is that this AbstractClass is bundled with specifications through in interface and therefore has its package-private system (which i define) and its public interaction (which others can use). Therefore, no one else than the package-maintaner will be affected by this - and its helpful since it makes extending the abstract class simpler (in the sense that i can call it by simply "foo" in subclasses rather than getFoo() (that makes little sense to me since the subclass should feel as if foo is "his") – tortal Nov 26 '12 at 02:21
  • Internals might change, eg, if the class were changed to operate on a remote database rather than a local one, or the application were generalized to where the number (a weight, perhaps) is delivered in your preferred units (pounds vs kg) while still being kept in kg internally. But in "real life" the odds of such a change without also needing to redesign the interface for other reasons is quite low. – Hot Licks Nov 26 '12 at 03:01

3 Answers3

6

The advantage of getters is decoupling interface from implementation. Today your getFoo might do nothing but return foo, but in the future you might want, for example, to remote the foo member and return a computed result instead. A getter will allow you to do that without requiring a change at each call site.

Alexey Feldgendler
  • 1,792
  • 9
  • 17
  • 1
    Thing is that the ecosystem for these variables are contained in an isolation of final methods and final variables - making any changes different from what's now useless. So, if there is no further need to in any way modify how that var is computed, then there is no reason? (In a way, if you ask for getX, and you know X is final, there is not much to expect than X itself... or?) – tortal Nov 26 '12 at 01:18
  • The point of encapsulation is not so much preventing unauthorized change (which indeed can be achived by marking the members final) as decoupling impementation details from the interface. If you're not concerned about that, there is no other reason. – Alexey Feldgendler Nov 26 '12 at 01:22
  • Especially if this is a learning exercise, you should embrace the encapsulation paradigm and make sure you fully understand why you use techniques like getters and setters — instead of cutting corners because it's a “real simple” project. A learning exercise is designed to model real-world problems that aren't as simple as what you can solve in a class, but can be approached using the same methodologies. – Alexey Feldgendler Nov 26 '12 at 01:47
  • Problem is that I'm not sure if I should be concerned or not. We're supposed to implement a framework for Geometrical forms, real simple in a sense but the point of the assignment is to "learn how to code in bigger coding environments". To be more specific: I declared for example final Location (which is a class describing a location on 2D plane). All of the methods placing, moving, and changing this variable are ALL final. Making the life of this variable TOTALLY internal to the Abstract class. I just want simple (native-feel-like) access for it from subclasses (that's why dumping getters). – tortal Nov 26 '12 at 01:49
  • Why does direct access to properties feel native to you? Are you coming from a programming language with active properties, like Python? – Alexey Feldgendler Nov 26 '12 at 01:51
  • Also want to add that this is a continuation course in java and getters/setters were enforced to us already in previous lectures. I'm trying to see if it's possible, now when I feel responsible enough :) to skip those getters/setter at specific situations I can't see any reason to have them!! – tortal Nov 26 '12 at 01:52
  • I did some PHP prior to PHP5. other than that i've just quickly played around with various. And yes.. the OO-paradigm of getters/setters bother me sometime, especially when i see direct access as being far more simplified (in situations there is no obvious reason for encapsulation) – tortal Nov 26 '12 at 01:53
  • I really advise you for the future to get used to getters and setters. The thing is that you can't predict all the changes that the code will have in te future. Especially if this is a profesional software rather than hobby project. So you have two options- think really hard about every field that you make whenever it can be made public (and if you are wrong and it changes- you pay dearly with a lot of code to change) or simply automaticaly generate getters and setters. – bjedrzejewski Nov 26 '12 at 01:56
  • I don't remember PHP having active properties either, but PHP is in general a mess (read more: http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/). If you're doing programming in Java, you should teach yourself to perceive access to properties through getters and setters as normal, and direct access as something that only happens within the class itself and maybe within very tightly coupled neighbor clases from the same package. – Alexey Feldgendler Nov 26 '12 at 01:57
  • Thanks a lot for all the input. It just feels as if in this case it really isn't needed, but it must because i have old habits of wanting to access vars directly rather than through unnecessary layers of abstractions. Since getX will also be final where is the room for modifications that can be made for other implementations? thx anyway – tortal Nov 26 '12 at 02:05
2

If you are ever going to access this value from JSF Page, it will expect getFoo rather than just foo (even if you write object.foo).

Apart from that- today this field is final, long time from now it can change (I guess). Even if the chance is very close to 0, I believe that there is no overkill in following good practices. Vast majority of the time you are making changes than writing code from scratch, so it is much better to safeguard yourself whenever possible (if all it takes is writing private and in case of eclipse about 4 clicks to generate the getter and setter automaticaly).

bjedrzejewski
  • 2,378
  • 2
  • 25
  • 46
  • thx for the input and good mentioning interoperability concerns, haven't thought at all about that really. – tortal Nov 26 '12 at 02:24
  • I never thought about them either before I started working with JSF and Java EE. It is just really hard to predict how the code that you write (if it is more than a hobby project) will be used. Also- if you are colaborating with other programmers, they may expect the practices to be followed. Some of them with start writing get... in their IDE looking for variables that po up. If your public variable is not there it can be overlooked. Writing code that is friendly to everyone colaborating with you is also important. – bjedrzejewski Nov 26 '12 at 02:30
  • Problem is, it's more code, and more code means more chance for error. Particularly with "minor" attributes the odds of doing a "dupe error" are quite high, and could be expensive to debug. – Hot Licks Nov 26 '12 at 17:00
0

To extend Feldgendler's answer (with information which may be useful for someone needing the answer of this question --- I believe this is relevant because it is really a question about encapsulation):

In effect of using private modifiers you will have to create the "getter" (e.g. int getX(){ ... }) to sustain access. Which can be declared in an implemented interface. A Java interface does not allow declaration of instance variables, such as the example of final int x; --- or of any other variable lacking the static modifier. The interface will act as a declaration of the behavior any implementing class will have.

If implemented like:

Coordinate implements ICoordinate { ... }

it could be useful in many scenarios:

The use of an interface

  • Self-documentation of an API.
    • Easy to read, document and manage.
    • Hence, allowing several implementations to be readily used and swapped.
    • In component-based design and more: provide explicit means to provide or require described behavior without actually having any implementation code ready.
      • Example: One could then create a database component that provides an interface. John Doe wants to write a program that will in the future use a database. For now however it is sufficient to use some other simpler form of storage. In order not to re-code what is already working code when the day comes John could implement an interface (maybe given the name interface IDatabase) with the methods void insert( ... ); Object get( ... ); and perhaps a few more -- then implement his temporary solution. The day comes and he now has a database implementing the same interface IDatabase. To swap to the new database he might only need to change *one line of code* (e.g. the constructor call)!
  • An example for the sake of it: http://pastebin.com/vvV2Nck8

Using private modifier

  • It Clarifies the intent of the class! Much like the interface, it has the nature of being self-documenting. (It has no value in security)
    • private modifier would imply that it is NOT to be accessed out of scope. Or equivalently -- only to be accessed within a certain scope. Same of course applies to public, "package-private" (no modifier implies package-private) and protected.
    • Accessing an attribute will not explicitly tell the caller what kind of variable it is. Having a getter but no setter says something else however...
    • NOTE: For constants (e.g. static final double LIGHT_SPEED) there is reasonable reason to omit a getter and have it public instead. This being just convention as it will be clear to what is a constant and what is an object with its own members.
    • NOTE2: Read about final keyword and its impact on optimization if interested. They can be used in methods as well as attributes. (Does use of final keyword in Java improve the performance? is an example)
tortal
  • 713
  • 1
  • 5
  • 17