2

I just started using Firebug in my IntelliJ project.

private byte[] image;

public byte[] getImage() {
    return image;
}

public void setImage(byte[] image) {
    this.image = image;
}

Firebug gives me the error :

May expose internal representation by incorporating reference to mutable object

I really don't understand what the error means and how I can mitigate it.

EDIT

I also get this error with my constructor:

public Design(byte[] image){
    this.image = image;
}

I fixed the error on the Getter thanks to a post and understand what it means, But the errors on the constructor en setter are not very clear to me.

Urban
  • 585
  • 2
  • 13
  • 28
  • Are you sure you're using Firebug and not the [Firefox DevTools](https://developer.mozilla.org/en-US/docs/Tools)? Because Firebug is officially discontinued and [doesn't work anymore starting from Firefox 57](https://hacks.mozilla.org/2017/10/saying-goodbye-to-firebug/). – Sebastian Zartner Nov 07 '17 at 21:19
  • @SebastianZartner Good catch! I'm using the FindBugs plugin. Will edit my question – Urban Nov 08 '17 at 08:24

1 Answers1

4

By calling getImage() you'll get access to the private field image. You can then modify it externally in any way you like, which might give you unwanted results.

You could circumvent it by having the getter return a copy of your underlying array. That way you can ensure the data's integrity.

So instead of

public byte[] getImage() {
    return image;
}

you can make use of java.util.Arrays.copyOf(byte[] original, int newLength)

public byte[] getImage() {
    return Arrays.copyOf(image, image.length);
}

I think that should get rid of that warning and be much safer to use, since your data is now protected from manipulation from the outside.

QBrute
  • 4,405
  • 6
  • 34
  • 40
  • Thanks very much. It resolved the error on the getter. I edited my question, because I get the same errors on the constructor and setter. – Urban Nov 06 '17 at 10:50
  • @Urban Please [ask a new question](https://meta.stackexchange.com/q/188625/205238) instead of changing the old one. – barfuin Nov 09 '17 at 10:16
  • 3
    Am i the only one finding this warning ridiculous, as it's just the way java works. There is no const or mut in the language. It's totally fine to "getList().add(2312)". – kaiser Oct 28 '20 at 14:43