Using getter / setter inside a class - good or bad practice? [closed] - java

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Using a getter/setter in the internal code of a class instead of accessing the instance variable directly, is it good or bad practice? At least for setters one could add additional code validating the value, but for the getters it's just overhead? How intelligent is the Java compiler, if my getters/setters just set/get the value directly, will Java optimize my code and replace the getters/setters by direct access to the instance variables, so there's no method calling overhead?

It is more common to access the field directly. The value of a setFieldName method is more obvious for programmers using your code in other classes. With the implementation details hidden, they might not realize what ranges of values are acceptable, so keeping fields private and forcing other developers to go through a setter makes sense. But inside your own class, the case for using a setter is much weaker. If you look at the source for the java API you'll find that getter / setter methods are generally not used within a class.

There is no need to do that inside a class, unless want to perform additional operations in those getters / setters.
The access to the class members can be direct to the class internally, as:
The reason for hiding is mainly to hide the implementation (and there's no need to hide the implementation from the class itself)
The getters and setters access the members directly, so to call them just to avoid access the members directly is somewhat, umm... redundant.
Regarding performance - I honestly think that in most cases, you shouldn't think about it, you should decide whether to call a method or access directly in terms of readability, scalability and maintenance, not in terms of whether it will take another nano second or not. This approach pays off in the long run. There are places for optimizations, and you should be efficient, but keeping your code clear and maintainable is much more important once the code base is over 20 lines.

Accessing directly is a good thing. However, no one can say getter/setter access is bad, inside the same class. If you are developing a Java bean, you will definitely understand what I am saying. Think you are trying to get the user input of a JTextField as a String. In this case, the getter methods will allow you to do lot of things including String truncating, trim, uppercase, lowercase, etc. If you are trying to do this all just by accessing the direct variable (eg: String s = textField.getText()), you will find it quite difficult to do it. So, what I think is, the good or bad depends on the situation and what you are developing

Related

Best practices with class visibility [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Is it best practice to have all the classes public in a Java project? I have noticed that in all Java projects I have worked with, there have only been public classes.
It isn't a guideline, no.
The information hiding principle tells us to only exposed what is required, and nothing more, to minimize coupling.
So, for example, if a class lets you handle logic in a separate class easier, and is only used by that class, there's no reason to have it public, nor should you make it public.
The simple answer to your question is "no!"
The slightly more complicated one is that you should only make a class public if it needs to be used by other classes outside it's own package. But if, like me, you break you project up into many packages for readability, then then if will often be the case that your classes will need to be public to be usable.
While your question is simple to ask, it is far from simple in its nature. Much will depend upon the kind of code your writing. It you're writing a library then use externally is probably high on your agenda. In an application less so.
I have found that I prefer the public approach. I try and design for reuse because it keeps my options open, causes me to think more carefully about my implementation because of the reuse issues, and that leads to better code. But it really is horses for courses, you are the biggest variable in this equation.
It depends, For top level class's, If you want other class's in a different package to view your class you should mark it public. If you only want class's in the same package to view you class mark it default(no-modifier).
So, your question is really, should all top level classes be public? I think it boils down to the usage of the package access that you do in your project. This question was relevant to that, some time ago.
Usually most classes are indeed public but there are cases when you might want to use default or private scope as well.
A class using the default scope is only accessible to other classes in the same package. In case of helper classes for example it's often a good practice to limit their use this way as your code becomes more encapsulated. The private scope can often be used for inner classes for the same reason.
No it is not. There are lot of classes with other access specifiers or even anonymous. For an example, you can write private or anonymous classes that can be registered to listeners like
'ActionListener' and 'ItemListener'. Just like that, for various purposes, we do write lot of classes with no public specifier. It really helps to separate your work into pieces.
However, in Java, normally every source file contains a public class. That is because if your source file's name is 'Reader.java', you cannot have a private or other access specifier for the class 'Reader' inside that source file. It must be public or default. Apart from that, no other class can have the access specifier 'public' instead of 'Reader' class.
Other thing is, private, protected and other types (except default) of classes cannot be written in a source file as "Independent classes". For an example, following is an error
Check.java
private class Check
{
}
It definitely is not best practice. You are seeing it because most programmers don't know that a top-level class doesn't have to be public.
Ideally, a package isn't just a way to organize classes into groups. There is no minimum or maximum number of classes that belong in a single package; rather, subpackages should be created only when there is a need for package-level classes and/or members. Java APIs do this a lot, and since the javadoc distributed from Sun/Oracle is generated for protected-level classes and members, some packages may appear to be sparse, even to the point of appearing nonsensically so.
For instance, the javax.swing.colorchooser package appears to have only four classes, but it actually has 17 (actual number may vary depending on the version of Java). Four are public; the rest are only for use with JColorChooser internals.
I've found that an inner class that is becoming too big to be easily maintained as an inner class is usually a good candidate for being a non-public top-level class.

Standard for programming 'beautiful' code in Java? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm reading some books about coding standard in Java.
I always loved beautiful and clean code.
But there are some things that bother me. For example, a method name should start with a lowercase word, and if it has a second word, it should be start with a uppercase character. But the standard for variables is the same thing. I think this is a little confusing.
So I'm asking you guys, what's your coding standard in Java?
Like:
How do you name objects, methods, classes, etc.
If you have more than one object from same class, how do you name the second one?
If you have one object in the argument of a method and you have another object from the same class inside this method, how you do name both of them?
What is the best trade-off for performance/code beauty, a lot of small methods, or some longer methods?
Feel free to say something more. =)
Mostly following the Java code convention.
I try to not make it matter what kind of class an object is. If I for instance have five different strings, the name of each variable should describe what information/content the variable represents, and not that is is a string.
I find it often silly to try coming up with variations of a variable just because it exists both as a method argument and a class variable. I mostly use the same name with this syntax this.theVariable = theVariable
A method should be as short as possible: as few lines as possible, and as few nested levels as possible (i.e. max one if-statement, and not ifs inside ifs etc.)
Robert Martin's Clean Code is highly recommended!
Just to address one specific point, because it's one I commonly see people doing horrific things with:
If you have more than one object from same class, how do you name the second one?
By their purpose, surely. If you have two different objects of the same class, you must be using them for different purposes, so name it after that purpose. I think all of these examples would be pretty self-explanatory to most readers:
public void copyAddresses(Customer source, Customer destination) {
public void sendMessage(Mailbox sender, Mailbox recipient) {
public void changeContactCompany(User contact, Company from, Company to) {
public void eatWatermelon(Bowl servingBowl, Bowl bowlForSeedSpitting) {
or whatever... you get the idea.
You should start with the official Java Code Conventions.
They will explain why code conventions are needed, different conventions and, what your question seems to be about, naming conventions. They add various examples too.
What is the best trade-off for
performance/code beauty, a lot of
small methods, or some longer methods?
"Premature optimization is the root of all evil" - Donald Knuth
Remember:
Make it work.
Make it right.
Make it fast.
You should only worry about performance if it is warranted; if the current code is too slow to meet requirements.
In that case you should find the 'hot-spots' and optimize those. Check if performance is good enough. If not, repeat.
Well since most of these are easily googled I will add my own standard Java naming practices:
I usually suffix the name of classes of what they extend or implement.
In other words Spring MVC controllers are suffixed with "Controller". This makes it easy in Eclipse to do a Crtl-Shift-R *Controller.
Second if I find I need to aggregate a whole bunch of static methods in a class I usually suffix that class with "Utils". I got this from Apache Commons and has just stuck.
Finally derived methods that do special expensive stuff and are transient I avoid calling them getXXX. The reason is to avoid problems with serializers.
Look here at the official guide

Why would one mark local variables and method parameters as "final" in Java? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
In Java, you can qualify local variables and method parameters with the final keyword.
public static void foo(final int x) {
final String qwerty = "bar";
}
Doing so results in not being able to reassign x and qwerty in the body of the method.
This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?
You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors. Static analysis tools such as PMD and the built-in SA of Eclipse flag these sorts of cases for this reason.
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.
I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.
But, of course, it's all personal preference ;-)
Making a parameter final guarantees that the value used at any location in the method refers to the value passed. Otherwise you have to parse mentally all the code above a given location to know what value the parameter has at that point.
Hence, not using final makes your code less readable, and maintainable, all by itself :)
Final local variables depend on intent, and is less important in my point of view. Depends on what goes on.
In the case of local variables, I tend to avoid this. It causes visual clutter, and is generally unnecessary - a function should be short enough or focus on a single impact to let you quickly see that you are modify something that shouldn't be.
In the case of magic numbers, I would put them as a constant private field anyway rather than in the code.
I only use final in situations where it is necessary (e.g., passing values to anonymous classes).
Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.
Finalizing local var's seems somewhat overkill IMO.
Yes do it.
It's about readability. It's easier to reason about the possible states of the program when you know that variables are assigned once and only once.
A decent alternative is to turn on the IDE warning when a parameter is assigned, or when a variable (other than a loop variable) is assigned more than once.
final has three good reasons:
instance variables set by constructor only become immutable
methods not to be overridden become final, use this with real reasons, not by default
local variables or parameters to be used in anonimous classes inside a method need to be final
Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.
Although it creates a little clutter, it is worth putting final. Ides e.g eclipse can automatically put the final if you configure it to do so.
Making local variables and method parameters final is essential if you want to pass those parameters into anonymous classes - like you instantiate an anonymous Thread and want to access those params in the body of the run() method.
Apart from that I am not sure of the performance benefits w.r.t better performance through compiler optimization. It is up to the specific compiler implementation whether it wants to optimize it at all...
It will be good to know of any performance stats from using final ...
Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.
The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.
Edit
In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.
I let Eclipse do it for me when they are being used in an anonymous class, which is increasing due to my use of Google Collection API.
We do it here for the local variables if we think they will not be reassigned or should not be reassigned.
The parameters are not final since we have a Checkstyle-Check which checks for reassigning parameters. Of course nobody would ever want to reassign a parameter variable.

Is there a Java unit-test framework that auto-tests getters and setters? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
There is a well-known debate in Java (and other communities, I'm sure) whether or not trivial getter/setter methods should be tested. Usually, this is with respect to code coverage. Let's agree that this is an open debate, and not try to answer it here.
There have been several blog posts on using Java reflection to auto-test such methods.
Does any framework (e.g. jUnit) provide such a feature? e.g. An annotation that says "this test T should auto-test all the getters/setters on class C, because I assert that they are standard".
It seems to me that it would add value, and if it were configurable, the 'debate' would be left as an option to the user.
I created the OpenPojo project for solving this exact problem.
The project allows you to validate:
Enforce Pojo coding standard (i.e. All fields private, or no native variables, ...etc)
Enforce Pojo behaviour (i.e. setter does JUST setting, no transformation, etc)
Validate Pojo Identity (i.e. Use annotation based equality & hashcode generation)
See Tutorial
I'm not aware of any readily available library or class that does this. This may mainly be because I don't care as I am on the side of strongly opposing such tests. So even though you asked there must be a bit of justification for this view:
I doubt that autotesting getters and setters benefit your code quality or your coverage: Either these methods are used from other code (and tested there, e.g. 100% covered) or not used at all (and could be removed). In the end you'll leave getters and setters in because they are used from the test but nowhere else in the application.
It should be easy to write such a test, e.g. with Apache Commons BeanUtils, but I doubt you really need it if you have good tests otherwise.
Unitils does this w/ the static method assertRefEquals.
In the most cases setter and getter do more as only setting and getting an internal field. An Object has to check internal rules that it hold only valid values. For example
are null values possible?
are empty strings possible?
or negative values?
or a zero value?
or values from a list are valid?
or is there a maximal value?
or is there a maximum precision on BigDecimal values?
The unit test should check if the behavior correct if there invalid values. This can not be automated.
If you have no logic on the setter and getter then it must be used anywhere in your application. Write a test where your object is a parameter for a more complex test. You can test it then with different values from the list.
Test your business logic and not the getter and setter. The result should also a coverage of the getter and setter. The methods should be any result in your business logic also if you have only a public library. If the getter and setter have no code coverage then removed it.
I've done something like that. A simple java class that takes an object and test all the getters and setter methods.
http://sourceforge.net/projects/getterandsetter/
I do think you should avoid getter and setter methods as much as possible, but as long as they're around and it takes two lines to test them, it's a good thing to do it.
I'll favor OO design over code coverage, and see if I cannot move those fields to the class that needs them. So I would try to see if those getters and setters can be removed, as suggested before.
getters and setters are breaking encapsulation.
I am trying out openpojo
I have kicked the tires and it seems to do the job.
It allows you to check all the pojo's in your project.
It seems to check the best practices on pojo's
Check this tutorial for a quick start
Tutorial
I guess this library is the answer to your question
it tests all the bean's initial values, the setters, the getters, hashCode(), equals() and toString(). All you have to do is define a map of default and non default property/value.
It can also test objects that are beans with additional non default constructors.
Answering the previous comment at #me here because of my reputation:
Vlookward, not writing getters/setters makes no sense at all. The only options for setting private fields is to have explicit setters, to set them in your constructor, or to set the indirectly via other methods (functionally deferring the setter to another place). Why not use setters?
Well, sometimes, there is no need to the field be private (Sorry if my English is not very good). Often, we write our software as it was a library and we encapsulate our fields (our business logic fields) with unnecessary getters/setters.
Other times, that methods are actually necessary. Then, there are two possibilities:
1. There is business logic inside them. Then they sould be tested, but they aren't real getters/setters. I always write that logic in other classes. And the tests test that other classes, not the POJO.
2. There is not. Then, do not write them by hand, if you can. For example, an implementation for the next interface may be fully autogenerated (and also in runtime!) :
interface NamedAndObservable {
String getName();
void setName(String name);
void addPropertyChangeListener(PropertyChangeListener listener);
void addPropertyChangeListener(String propertyName,
PropertyChangeListener listener);
}
So test only what is written by hand. No matter if it is a getter/setter.
I don't write test cases for each property, but instead test all of the setters/getters in a single test case using reflection/introspector to determine the type(s). Here is a great resource that shows this:
http://www.nearinfinity.com/blogs/scott_leberknight/do_you_unit_test_getters.html

How would you access Object properties from within an object method? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method?
I know that from outside of the object you should use a getter/setter, but from within would you just do:
Java:
String property = this.property;
PHP:
$property = $this->property;
or would you do:
Java:
String property = this.getProperty();
PHP:
$property = $this->getProperty();
Forgive me if my Java is a little off, it's been a year since I programmed in Java...
EDIT:
It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though...
This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called).
Personally, I feel like it's important to remain consistent. If you have getters and setters, use them. The only time I would access a field directly is when the accessor has a lot of overhead. It may feel like you're bloating your code unnecessarily, but it can certainly save a whole lot of headache in the future. The classic example:
Later on, you may desire to change the way that field works. Maybe it should be calculated on-the-fly or maybe you would like to use a different type for the backing store. If you are accessing properties directly, a change like that can break an awful lot of code in one swell foop.
I'm fairly surprised at how unanimous the sentiment is that getters and setters are fine and good. I suggest the incendiary article by Allen Holub "Getters And Setters Are Evil". Granted, the title is for shock value, but the author makes valid points.
Essentially, if you have getters and setters for each and every private field, you are making those fields as good as public. You'd be very hard-pressed to change the type of a private field without ripple effects to every class that calls that getter.
Moreover, from a strictly OO point of view, objects should be responding to messages (methods) that correspond to their (hopefully) single responsibility. The vast majority of getters and setters don't make sense for their constituent objects;Pen.dispenseInkOnto(Surface) makes more sense to me than Pen.getColor().
Getters and setters also encourage users of the class to ask the object for some data, perform a calculation, and then set some other value in the object, better known as procedural programming. You'd be better served to simply tell the object to do what you were going to in the first place; also known as the Information Expert idiom.
Getters and setters, however, are necessary evils at the boundary of layers -- UI, persistence, and so forth. Restricted access to a class's internals, such as C++'s friend keyword, Java's package protected access, .NET's internal access, and the Friend Class Pattern can help you reduce the visibility of getters and setters to only those who need them.
It depends on how the property is used. For example, say you have a student object that has a name property. You could use your Get method to pull the name from the database, if it hasn't been retrieved already. This way you are reducing unnecessary calls to the database.
Now let's say you have a private integer counter in your object that counts the number of times the name has been called. You may want to not use the Get method from inside the object because it would produce an invalid count.
PHP offers a myriad of ways to handle this, including magic methods __get and __set, but I prefer explicit getters and setters. Here's why:
Validation can be placed in setters (and getters for that matter)
Intellisense works with explicit methods
No question whether a property is read only, write only or read-write
Retrieving virtual properties (ie, calculated values) looks the same as regular properties
You can easily set an object property that is never actually defined anywhere, which then goes undocumented
Am I just going overboard here?
Perhaps ;)
Another approach would be to utilize a private/protected method to actually do the getting (caching/db/etc), and a public wrapper for it that increments the count:
PHP:
public function getName() {
$this->incrementNameCalled();
return $this->_getName();
}
protected function _getName() {
return $this->name;
}
and then from within the object itself:
PHP:
$name = $this->_getName();
This way you can still use that first argument for something else (like sending a flag for whether or not to used cached data here perhaps).
I must be missing the point here, why would you use a getter inside an object to access a property of that object?
Taking this to its conclusion the getter should call a getter, which should call a getter.
So I'd say inside an object method access a property directly, especially seeing as calling another method in that object (which will just access the property directly anyway then return it) is just a pointless, wasteful exercise (or have I misunderstood the question).
It is better to use the accessor methods, even within the object. Here are the points that come to my mind immediately:
It should be done in the interest of maintaining consistency with accesses made from outside the object.
In some cases, these accessor methods could be doing more than just accessing the field; they could be doing some additional processing (this is rare though). If this is the case, accessing the field directly would mean that you are missing that additional processing, and your program could go awry if this processing is always to be done during those accesses.
If you mean "most encapsulation" by "purist", then I typically declare all my fields as private and then use "this.field" from within the class itself. For other classes, including subclasses, I access instance state using the getters.
The question doesn't require an opinion based answer. It is a subject well covered by computing science for decades from the principle of high cohesion, low coupling and the SOLID principles.
The purist, read correct, OO way is to minimise coupling and maximise cohesions. Therefore both should be avoided and the Law of Demeter followed by using the Tell Don't Ask approach.
Instead of getting the value of the object's property, which tightly couples the two class, use the object as a parameter e.g.
doSomethingWithProperty() {
doSomethingWith( this.property ) ;
}
Where the property was a native type, e.g. int, use an access method, name it for problem domain not the programming domain.
doSomethingWithProperty( this.daysPerWeek() ) ;
These will allow you to maintain encapsulation and any post-conditions or dependent invariants. You can also use the setter method to maintain any pre-conditions or dependent invariants, however don't fall into the trap of naming them setters, go back to the Hollywood Principle for naming when using the idiom.
i've found using setters/getters made my code easier to read. I also like the control it gives when other classes use the methods and if i change the data the property will store.
Private fields with public or protected properties. Access to the values should go through the properties, and be copied to a local variable if they will be used more than once in a method. If and ONLY if you have the rest of your application so totally tweaked, rocked out, and otherwise optimized to where accessing values by going through their assosciated properties has become a bottleneck (And that will never EVER happen, I guarantee) should you even begin to consider letting anything other than the properties touch their backing variables directly.
.NET developers can use automatic properties to enforce this since you can't even see the backing variables at design time.
It depends. It's more a style issue than anything else, and there is no hard rule.
I can be wrong because I'm autodidact, but I NEVER user public properties in my Java classes, they are always private or protected, so that outside code must access by getters/setters. It's better for maintenance / modification purposes. And for inside class code... If getter method is trivial I use the property directly, but I always use the setter methods because I could easily add code to fire events if I wish.
If I don't edit the property, I'll use a public method get_property() unless it's a special occasion such as a MySQLi object inside another object in which case I'll just make the property public and refer to it as $obj->object_property.
Inside the object it's always $this->property for me.
Well, it seems with C# 3.0 properties' default implementation, the decision is taken for you; you HAVE to set the property using the (possibly private) property setter.
I personally only use the private member-behind when not doing so would cause the object to fall in an less than desirable state, such as when initializing or when caching/lazy loading is involved.
I like the answer by cmcculloh, but it seems like the most correct one is the answer by Greg Hurlman. Use getter/setter all the time if you started using them from the get-go and/or you are used to working with them.
As an aside, I personally find that using getter/setter makes the code easier to read and to debug later on.
As stated in some of the comments: Sometimes you should, sometimes you shouldn't. The great part about private variables is that you are able to see all the places they are used when you change something. If your getter/setter does something you need, use it. If it doesn't matter you decide.
The opposite case could be made that if you use the getter/setter and somebody changes the getter/setter they have to analyze all the places the getter and setter is used internally to see if it messes something up.

Categories