Is it good to call instance attributes using getter and setter? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I'm making a battleship java game and throughout the entire process I've used the Point class to store X and Y coordinates. I know how getters and setters work and why we used them, but this specific class has both getters and public attributes so here's my question, what would it be better to use?
p.x or p.getX()
I know it's a good practice to use getters but I'm confused in this case, what should I use?

(to recap, this is about Immutable Objects vs changing primitive position values directly)
I have to counter #rzwitserloot's answer. He has provided three problematic classes:
The first one, the Lombok one, is either also immutable, or using #NonFinal or #PackagePrivate annotations, thus using (creating/allowing) unchecked getters and setters. So when it comes to how safe the code is, that either has the problems of immutability, or it's simply the same level as (directly accessible) public member variables.
The second one, the record, is shallowly immutable. That means that any change to the position cannot be done to the Point itself, but each time a new instance of Point has to be created
The third one, very similar to the second one, is a truly immutable class. Same here: any change to the position cannot be done to the Point itself, but each time a new instance of Point has to be created
So what we see here: immutability. If you want to keep your code nice and clean, immutability is nice. Especially for debugging. Immutability is a fine tool for writing clean software. The dream of tinkerers. But for hands-on guys, in some situations, this soon becomes 'overengineering'.
But with regards to performance there are some problems:
For every change to an immutable class, you have to create a copy of that class, with a few changes
It's harder to change only one aspect/value, then change another value later, without creating multiple objects
So, assuming a stupid JVM,
you'd soon run into memory-based performance problems, due to all those objects you need to create
the speed is a horrible lot slower than simply changing the values.
Gladly, the JVM is very smart:
After a short runtime the JIT finds/knows classes that are used and discarded and optimizes that.
Also, access via getters/setters is a lot slower, but the JVM also can take most of that away in most situations.
Also, with the JVM advancing every year, chances are that the optimization/speed will increase further, reducing or maybe even annihilating any disadvantages of the immutable classes. Also, the optimizations will definitely be safer or at least as safe as anything you could design. But can they be as efficient?
BUT there are also cases where the JVM can do neither optimizations. Especially when interfaces/abstract base classes are involved, even method calling can get slower, because addresses of the real targeted methods has to be resolved at runtime, each and every time.
So in the end, it's up to you to test and decide, what approach you want to use.
If this bit of added safety is really worth the 'drop' in performance.
And how much you expect from the future, regarding JVM optimization.
Where the others are right: don't use AWT classes unless you're really using AWT. Better have your own class that you can fit to your needs.
// BIG UPDATE:
One last thing to consider, and IMO the biggest downside to using an immutable Position type:
(WARNING: This example will get more and more ridiculous! But it shows where that strategy leads)
Let's say we have the following Class: class Ship { Position position; }
So we address that position via ship.position
Now, when we want to change the ship's position, we have to change the reference to the position: ship.position = ... (new Position or ship.position.clone(newX,newY) or ship.position.with(newX,newY)
So whenever we want to change the ship's position, and follow the immutability pattern
semi-consequently: we would at least need another getter/setter for Position in Ship
Anything working with positions would also have to know its containing Classes, for example Ship and any and all other things that have a Position and might be computed by the same logic (yes, interfaces, but where does that stop?)
Also you'd have to check every time if the Ship.position is not null...
fully consequently: the Ship should also be immutable, and on any change to its position or any other status, the Ship in the Scenario would be replaced by a muted immutable copy.
Also, the Scenario would have to be replaced on any change. Wow.
Anything working with the ship would also have to know all the References TO the Ship, so it can update those
If the Scenario changes, the Game should also be immutable and its instance has to be replaced.. wait, what?
So we see that there exist a lot of scenarios where immutable Objects are not a good solution

That Point class is an old, obsolete relic that is all sorts of non-idiomatic java. The original mistake is using it in the first place; your code presumably has nothing to do with java.awt, so using a class from within that package was not a great idea. Even if it is, that class is just a mistake at this point, but unfortunately its documentation does not point this out.
Given that the mistake has been made, the question 'which one of these 2 things are better style' is basically moot: Either one is bad.
If you'd have to flip the coin here, go with .getX() which at least looks more idiomatic.
If you have the time, make your own Point class. It should look like:
#Value public class Point {
int x, y;
}
or
public record Point(int x, y) {
}
or
public class Point {
private final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override public int hashCode() {
return (x * 31) ^ y;
}
#Override public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof Point)) return false;
Point p = (Point) other;
return p.x == x && p.y == y;
}
#Override public String toString() {
return String.format("[%d, %d]", x, y);
}
}
Given the wall of text that third one entails, one of the first two options are probably better. The first one uses Project Lombok to avoid the boilerplate, the second one uses a feature you can't really use unless you have Java16 installed.
NB: I am known to contribute to Lombok :)
NB2: The reason java.awt.Point is not going to change is because existing code will have p.x = 5; or whatnot someplace, and thus, changing it like this (making it immutable) would break existing code, which java doesn't do unless there very strong mitigating reasons to do it.

If you have some modification while setting your attribute like hashing or encrypting
, you should make these attribute in private, use getter and setter, else, just make your attribute in public.

Related

Better to abstract out detail or use a setter? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
In terms of best practices, suppose I have this code:
public class ClassObject {
private int someNumber;
public void setSomeNumber(int x){
this.someNumber = x;
}
public int getSomeNumber(int x){
return this.someNumber;
}
//Should I even use this?
public void decreaseSomeNumber(){
--this.someNumber;
}
}
public void doSomeStuff(ClassObject instance){
// do some things
instance.decreaseSomeNumber(); //A
instance.setSomeNumber(instance.getSomeNumber() - 1); //B
}
I am wondering if either lines A or B are code smells. I think decreaseSomeNumber() is likely a redundant/useless function since I can just do instance.setSomeNumber(instance.getSomeNumber() - 1); everwhere.
On the other hand, it seems slightly more verbose doing instance.setSomeNumber(instance.getSomeNumber() - 1). What is the cleanest and good code design between A and B?
If you have a multithreaded environment, having (A) a decreaseSomeNumber method is worth it, however, you should make it threadsafe. Otherwise (B) two parallel threads might try to decrease the value at the same time, resulting in just a single decrease operation if they overlap.
That being said, it's typically hard work to really make code threadsafe, and in simple cases, occasional glitches might not matter. However, occasional is the keyword here: If you ever run into these, reproducing the problem will be horribly hard.
In terms of best practises you must avoid when is possible the form
public void decreaseSomeNumber(){
--this.someNumber;
}
and prefer the standard getters and setters.
But in some cases you need to decrease the value of a variable,
if this thing is occasional is good to use getters and setters
instance.setSomeNumber(instance.getSomeNumber() - 1);
instead in the case you need decreasing the a variable repeatedly (ex. A withdraw in a bank account) using only one method is not bad, but it must be defined like
public void decreaseSomeNumber(int many){
this.someNumber -= many;
}
in this way you are making a code more reusable, and this is good
P.S. the B way is more simple to syncronize in multi-threading enviroments
I would say it depends on more specific details, but I would be probably in favour of decreaseSomething.
With the getter and setter, you implicitly assume that:
The user of the API implements some (albeit trivial) computation.
The computation is performed at the time of the request.
The caller handles to concurrency-related issues on their own.
The (1) is rather a philosophical problem, although it might lead to errors caused by inadvertence, like calling get and set on two different objects.
The (2) can be a practical problem. Maybe you want to use the object from multiple threads. And maybe you don't need the number often, but you need to change it often. I believe that one could come up with some optimizations based on LongAdder or LongAccumulator or AtomicInt, which can optimize some highly concurrent places. With decreaseSomething, you can do it inside the class implementation. With getters and setters, you would need to somehow replace all occurences of x.setSomething(x.getSomething() + 1) by something else. That does not look like a proper encapsulation…
The (3) depends on your objective. Some people just make thread-unsafe code and claim it is programmer's responsibility to handle locks where needed, which can be OK. Sometimes, there might be a demand for thread-safe code. With getter and setter, you would need to use some locking scheme every time you access the data (which also makes (1) a less philosophical issue). Sometimes, it can be awful. Sometimes, it can be OK, because the caller wants to lock something more than just this one object.
As mentioned on the start of the post, I don't say I would prefer it every time. Maybe there are some cases when I would not go this way.
Edited
I would recommend changing this class as follows:
public class ClassObject {
private final int someNumber;
public ClassObject(int someNumber) {
this.someNumber = someNumber;
}
public int getSomeNumber() {
return someNumber;
}
public ClassObject decreaseSomeNumber() {
return new ClassObject(someNumber - 1);
}
public void doSomeStuff(ClassObject instance) {
//New ClassObject with new someNumber(instance's someNumber is decreased one unit)
ClassObject decreasedNumberClassObject = instance.decreaseSomeNumber();
}
}
I mean, if you wanna make a change in the Class properties(decrease, increase, multiply,...), it must return you, new Object(from the same Class), with the new property.
This code completely follows OOP paradigms. It is thread-safe, immutable and software(code) maintenance will be very high with the help of this approach.

Is there any pros and cons of calling one constructor from another?

Consider the following case of calling one constructor from another:
public Pet(int x) {
this.x = x; // “this” means this object
}
public Pet (int x, String y) {
this(x); // calls constructor public Pet(int id)
this.y = y; // ”this” means this object
}
.
.
.
public Pet (params,[...]) { // [...] shows the number of params
this(params,[...])
//...
}
And separate overloaded constructor body.
public Pet(int x, int y, int z, int a, int b, [...]) {
this.x = x;
this.y = y;
this.z = z;
this.a = a;
this.b = b;
//[...] and so on
}
This is obvious goal can achieve with less lines of code.
(According above scenario my question)
Is this good/bad practice to call one constructor from another? What will be the pros and cons when we are developing enterprise applications; if we think with respect of performance, memory etc.
You should always be following the Rules of Optimization when thinking about whether or not something is performant and/or optimal to use in certain scenarios.
That aside, there are some clear pros and cons.
The pro to this approach is less duplicated code. With each constructor being added in, the calls to super get a bit longer, but there's no repeated operation of this.x = x anywhere.
The con to this approach is that you expose more ways to construct this object, when you may be looking for a factory or a builder instead which reduces the visibility of the multiple constructor approach.
This is much better than duplicating initialization code in multiple constructors. Performance and memory should not be affected. Just more clean code.
it's not about cons and pros, it's about an aim to what you're trying to reach.
generally speaking calling one constructor from another is not a bad practice and if you're lessening the prospective (likely duplicate) code, then you better use this approach.
From my experience, when you are instantiating your classes, there will be a lot of times when you will not get values for all the properties, or maybe none.
I pretty much always make a full and an empty constructor, because sometimes I need to instantiate the classes without assigning values to the properties until later, so I guess it pretty much depends on what your code does.
Also another important thing is, that it's good to have some flexibility on your code while not making a mess, because when you are working on a project with more people, odds are high that someone will need to use or change your code afterwards, and the more flexible your code is, the other people will have an easier time working with it.

How to program if conditionals, and when does one approach become better than the other [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am wondering, mostly as an industry standard approach, or as a explicitly best practice approach how would one usually program if conditionals.
I find myself using the first approach below very often, never truly had a problem with it. But I'm still wondering when should either be used.
This is just an example to illustrate what I mean, it shouldn't be taken as the normal complexity of the comparisons usually utilized.
Example
public class Validation {
int x = 5,
y = 10,
z = 100,
a = 1;
public void compare() {
if (x < y) {
// Do Something
if (y < z) {
// Do Something
if (z < a) {
System.out.println("Whatever");
}
}
}
}
public void alternate() {
if (compareNumbers(x, y)) {
// Do something
if (compareNumbers(y, z)) {
// Do something
if (compareNumbers(z, a)) {
System.out.println("Whatever");
}
}
}
}
public boolean compareNumbers(int a, int b) {
return a < b;
}
}
Which one of those would be better practice? This being a super simple example, imagining you would normally use more complex validations.
And if 'alternate' is better, how many times would the comparison method/function have to be called for it to be better?
I am sorry if this belongs in StackExchange, I wasn't very sure of which one to post it in.
To narrow the scope to StackOverflow lets say this question applies exclusively to Java. Although a general programming view/response would be appreciated.
Extracting code to methods has several advantages:
It makes the code readable
It allows for easily changing the implementation of the method
It allows for unit testing of this specific method
If all your method does is to apply the < operator to the two arguments, I'd say none of the three reasons above apply, and that you're over-complicating things.
Just use the < method, and refactor your code once you need to apply a test with some more "meat" to it.
There are no "industry standards" for this kind of thing. For good reason.
As far as whether a < b is better that compareNumbers(a, b) ... the answer depends on the actual context.
In your example, most people would agree that a < b is better1. But this is an artificial example, and the answer could be different for other (more realistic) examples.
The same goes for all sorts of other questions about the best way to express algorithms, etc in code. It is rare for questions like this to have a single objectively correct answer. It is typically a matter of opinion ... and the context really matters.
But the bottom line is that the only real "industry standard" here is:
Use your professional knowledge, skills and judgement.
... and that means things like:
thinking about each particular problem and finding an appropriate (justifiable) solution,
considering coding effort, readability2, reliability, maintainability for your solution,
considering the economics of the situation; i.e. there is a trade-off between time spent "polishing" your code and time spent doing other things like implementing functionality, testing, writing documentation, meeting deadlines.
1 - If I have to scroll down a couple of pages to check what compareNumbers is doing, this is an impediment ... compared with an inline comparison using <. Now if there was some deeper semantic behind the comparison, then method abstraction could be a good thing, especially if there were comments in the method that explained the semantics. But in this example, compareNumbers(a, b) is less semantically meaningful than a < b.
2 - Another answer states (without supporting evidence) that abstracting code to methods improves readability. This is a gross over-simplification, and often it is demonstrably false. It is important technique ... but not always the right one.
From my personal experience I would use the original compare if I know the conditions are always going to stay the same, however I would use the alternate if there were even the slightest chance of needing to change the conditions. That way I wouldn't have to go back and replace every single condition individually.
To build upon breaking out the methods, I know your example is just that, a quick example, but rather than focus on the evaluation I would focus on the task and organize the code like this:
public void someMethodThatCares(int x, int y, int z, int a)
{
taskXY(x, y);
}
public void taskXY(int x, int y)
{
if (x < y)
{
taskYZ(y, z);
}
}
public void taskYZ(int y, int z)
{
if (y < z)
{
taskZA(z, a);
}
}
public void taskZA(int z, int a)
{
if (z < a)
{
}
}
Now you can build your dependencies as you need them, test each piece of functionality independently, maintain the logic in a clean fashion, and reuse it as needed.
Actually, I focus on the complexity of the code and the importance of that logic in my project. therefore, I might use all alternatives in the same class or even in the same method.
I would suggest reading Design Patterns by the Gang of Four for more information on how to decide. For every problem the approach would be different. For example if you needed to write multiple programs that individually checked each variable, the first program doing a less than check, the second doing a greater than check, the third doing a equals check it may make sense to use the Strategy Design Pattern for each of these cases to prevent the need to create multiple programs and using a Factory creator to decide which Strategy to use. The factory pattern could decide which one to use at run time based on user input or some other method.

What is more practical, two properties or one object with said properties?

If this place is not the proper place, please, point me where could I discuss/solve my doubts before closing the question.
It's a little thing I've had in my mind for a bit. In Java, and maybe other OOP languages, what would be better, to have...
class Entity {
[final] int xPos;
[final] int yPos;
// ...
}
or rather...
class Entity {
Position p;
// ...
}
class Position {
[final] int x;
[final] int y;
}
What are the pros and the cons of this? To me, it seems more practical to have the second approach, especially when you need to enter both properties as method parameter or return value, but I'm also thinking if this would produce too many unneeded procedures (creating new objects for minor things)...
Or you could just not write a custom class and use Point. Really it's up to you. If you need to perform calculations involving the co-ordinates, or need to pass the object's co-ordinates around a lot, then it's best to wrap them up in an object to keep your code simpler. If they are constant, and will never change (which you can never really know) then you can keep them as int values.
You'd only really need a separate class definition if it represents something that has an independent purpose - so in the future might be required elsewhere or include independent functionality (division of responsibility). As Chris mentioned your example relates directly to the Point class so the latter is more appropriate.
Neither. The best design would be the following:
class Position {
final int x;
final int y;
}
interface Positionable {
Position getPosition();
}
class Entity implements Positionable {
private Position p;
public Position getPosition() {
return position;
}
}
Reasoning:
Allows Position to evolve - maybe you want to add a z coordinate
Allows Position to be immutable
Allows Position to be passed around without the baggage of being contained within a heavier object
Allows you to freely add methods to Position, eg float distanceFrom (Position p)
Allows Position to outlive the object it describes
Allows other classes to easily be given a Position
Decouples as much as possible the various concerns
Note that Point is mutable, so using it or extending it is inferior from a good design perspective, because immutability seems a wise choice for such a class (it's considered a mistake that Point is mutable - for other "mistakes in java", see this answer)

Premature optimization in Java: when to use "x = foo.getX()" vs simply "foo.getX()"

When I find myself calling the same getter method multiple times, should this be considered a problem? Is it better to [always] assign to a local variable and call only once?
I'm sure the answer of course is "it depends".
I'm more concerned about the simpler case where the getter is simply a "pass-along-the-value-of-a-private-variable" type method. i.e. there's no expensive computation involved, no database connections being consumed, etc.
My question of "is it better" pertains to both code readability (style) and also performance. i.e. is it that much of a performance hit to have:
SomeMethod1(a, b, foo.getX(), c);
SomeMethod2(b, foo.getX(), c);
SomeMethod3(foo.getX());
vs:
X x = foo.getX();
SomeMethod1(a, b, x, c);
SomeMethod2(b, x, c);
SomeMethod3(x);
I realize this question is a bit nit-picky and gray. But I just realized, I have no consistent way of evaluating these trade-offs, at all. Am fishing for some criteria that are more than just completely whimsical.
Thanks.
The choice shouldn't really be about performance hit but about code readability.
When you create a variable you can give it the name it deserves in the current context. When you use a same value more than one time it has surely a real meaning, more than a method name (or worse a chain of methods).
And it's really better to read:
String username = user.getName();
SomeMethod1(a, b, username, c);
SomeMethod2(b, username, c);
SomeMethod3(username);
than
SomeMethod1(a, b, user.getName(), c);
SomeMethod2(b, user.getName(), c);
SomeMethod3(user.getName());
For plain getters - those that just returns a value - HotSpot inlines it in the calling code, so it will be as fast as it can be.
I, however, have a principle about keeping a statement on a single line, which very often results in expressions like "foo.getBar()" being too long to fit. Then it is more readable - to me - to extract it to a local variable ("Bar bar = foo.getBar()").
They could be 2 different things.
If GetX is non-deterministic then the 1st one will give different results than the 2nd
Personally, I'd use the 2nd one. It's more obvious and less unnecessarily verbose.
I use the second style if it makes my code more readable or if I have to use the assigned value again. I never consider performance (on trivial things) unless I have to.
That depends on what getX() actually does. Consider this class:
public class Foo {
private X x;
public X getX() { return x; }
}
In this case, when you make a call to foo.getX(), JVM will optimize it all the way down to foo.x (as in direct reference to foo's private field, basically a memory pointer). However, if the class looks like this:
public class Foo {
private X x;
public X getX() { return cleanUpValue(x); }
private X cleanUpValue(X x) {
/* some modifications/sanitization to x such as null safety checks */
}
}
the JVM can't actually inline it as efficiently anymore since by Foo's constructional contract, it has to sanitize x before handing it out.
To summarize, if getX() doesn't really do anything beyond returning a field, then there's no difference after initial optimization runs to the bytecode in whether you call the method just once or multiple times.
Most of the time I would use getX if it was only once, and create a var for it for all other cases. Often just to save typing.
With regards to performance, the compiler would probably be able to optimize away most of the overhead, but the possibility of side-effects could force the compiler into more work when doing multiple method-calls.
I generally store it locally if:
I'm will use it in a loop and I don't want or expect the value to change during the loop.
I'm about to use it in a long line of code or the function & parameters are very long.
I want to rename the variable to better correspond to the task at hand.
Testing indicates a significant performance boost.
Otherwise I like the ability to get current values and lower level of abstraction of method calls.
Two things have to be considered:
Does the call to getX() have any side effects? Following established coding patterns, a getter should not alter the object on which it is called, the in most cases, there is no side effect. Therefore, it is semantically equivalent to call the getter once and store the value locally vs. calling the getter multiple times. (This concept is called idempotency - it does not matter whether you call a method once or multiple times; the effect on the data is exactly the same.)
If the getter has no side effect, the compiler can safely remove subsequent calls to the getter and create the temporary local storage on its own - thus, the code remains ultra-readable and you have all the speed advantage from calling the getter only once. This is all the more important if the getter does not simply return a value but has to fetch/compute the value or runs some validations.
Assuming your getter does not change the object on which it operates it is probably more readable to have multiple calls to getX() - and thanks to the compiler you do not have to trade performance for readability and maintainability.

Categories