U
U
Urukhayy2017-03-11 14:23:26
Java
Urukhayy, 2017-03-11 14:23:26

Is it normal to create instances all the time and use them 1 time?

Is it normal when an instance of a class is created in order to call its method once, and its reference is not stored anywhere?
Example:
new Window("Hello!").show();
Or:

double x = 1.0, double y = 1.0, double z = 1.0;
SomeClass.createObject(new Point(x, y, z)); // Создаётся экземпляр точки, и никуда не записывается. Используется 1 раз

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
dinegnet, 2017-03-11
@Urukhayy

Is normal.
But it affects performance/memory costs.
If for your specific task this is all insignificant and the impact is minimal - use it for health.
After all, programmers' time is worth more than computer hardware.
Re-optimization is not always worth the candle.

N
Noortvel, 2017-03-11
@Noortvel

No, not normal. And why did you take that the instance of the point is not written anywhere? He seems to be sitting in SomeClass.

public class Someclass{
    private Point point;
    public void CreateObj(Point point){
        this.point = point;//ссылка на поинт, злой сборщик не придет.
}
}

C
Cyril, 2017-03-11
@raspier

Everything is very simple. If you need this instance of someone else, then write it to a variable, that's all.
In general, IDEA will even "discolor" this variable, if you don't use it anywhere. So that

double x = 1.0, double y = 1.0, double z = 1.0;
Point point = new Point(x, y, z);
SomeClass.createObject(point);

Or already go to the end))
And then you created variables for the coordinates, but you don’t want to for the instance.

M
MrShaggy, 2017-03-11
@DrNefario

Well...
If we talk about performance, then everything depends on the limitations of your system. Might or not, it's up to you.
If we talk about the "principle of least surprise", then I can say that you surprised me.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question