Karthikeyan Sakthivel

Greenhorn

Posts: 3

posted 10 years ago

I wish to know whether there is any security issue when returning a New Object from a Method.

EXAMPLE

*******

public class MEReturnParameter {

public static Dimension getRectangleSize(int x1, int y1, int x2, int y2) {

return new Dimension(Math.abs(x1-x2), Math.abs(y1-y2));

}

}

Whether the following line is a problem or Not

return new Dimension(Math.abs(x1-x2), Math.abs(y1-y2));

EXAMPLE

*******

public class MEReturnParameter {

public static Dimension getRectangleSize(int x1, int y1, int x2, int y2) {

return new Dimension(Math.abs(x1-x2), Math.abs(y1-y2));

}

}

Whether the following line is a problem or Not

return new Dimension(Math.abs(x1-x2), Math.abs(y1-y2));

K.S.KARTHIKEYAN

Karthikeyan Sakthivel

Greenhorn

Posts: 3

posted 10 years ago

Actually I was asked to pass the parameter instead of creating an new objects inside the method.

Original Example

public class ReturnParameter {

public static Dimension getRectangleSzie(int x1, int y1, int x2, int y2) {

return new Dimension(Math.abs(x1-x2), Math.abs(y1-y2)); //VIOLATION

}

}

I was asked to write the code as follows.

public class ReturnParameter {

public static Dimension getRectangleSize(int x1, int y1, int x2, int y2, Dimension returnValue) {

returnValue.width = Math.abs(x1-x2);

returnValue.height = Math.abs(y1-y2);

return returnValue; // FIXED

}

}

Trying to understand why the above Original Example is not allowed

Original Example

public class ReturnParameter {

public static Dimension getRectangleSzie(int x1, int y1, int x2, int y2) {

return new Dimension(Math.abs(x1-x2), Math.abs(y1-y2)); //VIOLATION

}

}

I was asked to write the code as follows.

public class ReturnParameter {

public static Dimension getRectangleSize(int x1, int y1, int x2, int y2, Dimension returnValue) {

returnValue.width = Math.abs(x1-x2);

returnValue.height = Math.abs(y1-y2);

return returnValue; // FIXED

}

}

Trying to understand why the above Original Example is not allowed

K.S.KARTHIKEYAN

Stan James

(instanceof Sidekick)

Ranch Hand

Ranch Hand

Posts: 8791

posted 10 years ago

No, I don't see the point of that change. There is some potential if you keep a reference to the object you create and return or if you just return a member variable ...

because now somebody else has access to something I consider private. They can change it without my knowing. I think FindBugz flags this as a warning.

because now somebody else has access to something I consider private. They can change it without my knowing. I think FindBugz flags this as a warning.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |