user8753793
user8753793

Reputation:

Side effect of the new keyword

What does someone mean when they say the new keyword has side effects? On SSE, a comment was given for an answer, but I didn't understand the comment.

Clearly the factory methods in the question call new, they have side effects. However, that side effect is identical to just calling a public constructor, so they are no more difficult to test than the latter.

The question had to do with using a static method to construct an object with a private constructor. What's the side effect to using the new keyword and how am I suppose to create my objects?

Upvotes: 3

Views: 222

Answers (2)

Felk
Felk

Reputation: 8224

By "side effect", programmers usually mean any effect a function has that isn't fully contained within the function itself. Basically, if the "world" has changed as a result of calling a function, it has side effects. If you can call the function as many times as you want and the "world" doesn't ever change, it doesn't.

Quick example: System.out.println("Hello world!"); does IO, hence it has side effects. Math.min(5, 10) just returns 5 without having any additional effects on anything, hence it has no side effects.

In your example, the function you call seems to do not much except constructing a new object with new. Have a look at this example:

static Foo createFoo() {
    return new Foo();
}
// ...
while (true) {
    createFoo();
}

The obvious side effect we see right away is memory allocation. Calling createFoo() will cause a heap memory allocation. Arguably Math.min(5, 10) also consumes memory, on the stack, but that memory consumption is temporary and fully contained within the function's execution if you don't explicitly assign the return value yourself, at what point it's the caller who causes the memory consumption. Heap allocation outlives the function call, until it eventually gets cleaned up by the garbage collector.

I guess it's not clear cut when you can speak of "no side effects" in Java, as almost everything can cause a heap allocation and it's usually fine to consider objects to be gone by the time you drop their reference and let the GC clean it up later.

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140504

The full comment is:

Clearly the factory methods in the question call new, they have side effects. However, that side effect is identical to just calling a public constructor, so they are no more difficult to test than the latter.

He is saying that the side effect is that a new object is created; but the side effect of invoking new in a static factory method is no different from invoking new directly.

Upvotes: 3

Related Questions