Convention in java - “new” outside of constructor / method?

扶醉桌前 提交于 2020-01-10 19:33:08

问题


Simple question. A friend of mind wrote code similar to this one (which is just to explain you my question, it's not useful at all....)

class Example{
    private int[] tab = new int[10];
    public Example() {
        for(int i = 0 ; i < 10 ; i++)
            tab[i] = (int)(Math.random()*100);
        for(int i = 0 ; i < 10 ; i++)
            System.out.println(tab[i]);
    }
    public static void main(String[] arg) {
        Example ex = new Example();
    }
}

I told him he should put the new inside the constructor

class Example{
    private int[] tab;
    public Example() {
        tab = new int[10];
    ...
}

When he ask me why, I din't know what to answer : I didn't have a definite argument other than "it's better this way". The way I learn it, you can initialize variables with basic types (int, double...) but for arrays you should do it in the constructor.

So:

  • is it really better?
  • Are there some good reasons: Convention, style?
  • Does it change anything like less/more memory used?

I'm not considering the case where the number of element can vary. It will ALWAYS be 10


回答1:


  • is it really better ?

Not really, IMO.

  • is there some good reasons : convention ? style ?

There may be valid reasons for choosing one way over the other is when you have multiple constructors, or when the initial values depend on constructor arguments; e.g.

private int[] tab;

public Example(int size) {
    tab = new int[size];
    for (int i = 0; i < size; i++)
        tab[i] = (int) (Math.random() * 100);
}

or

private int[] tab = new int[10];

public Example(int initial) {
    for (int i = 0; i < 10; i++)
        tab[i] = initial;
}

public Example() {
    for (int i = 0; i < 10; i++)
        tab[i] = (int) (Math.random() * 100);
}

Apart from that (and in your example) there are no general rules about this. It's a matter of personal taste.

  • does it change anything like less/more memory used ?

In your example it will make no difference. In general, there might be a tiny difference in the code size or performance, but it is not worth worrying about.

In short, I don't think your suggestion to your friend has a rational basis.

The way I learn it, you can initialize variables with basic types (int, double...) but for arrays you should do it in the constructor.

You should unlearn that ... or at least recognize that it is just a personal preference.




回答2:


Actually I prefer using the outer method. If he added a constructor and had

private int[] foo = new int[10];

public Example() { }

public Example(int somethVar) { }

Then both constructors would have a foo array ready for use. See this article as the Java compiler is smart enough to just copy that stuff into the constructor, so it really isn't any better.




回答3:


I'm not aware of any functional/performance advantages of one method or another. But here're some thoughts why initializing variable immediately can be better.

  1. If you have three different constructors, you won't want to put new int[10]; in each, right?
  2. Readability. When I see variable used in the code, I can do 'ctrl-click' in my IDE and see both type and value of it. I don't have to search around for a place where it's initialized.



回答4:


This is probably going to be a silly question and thus get voted down, but ... why isn't your friend using an initialization block for, you know, initialization?

I understand fully why he doesn't want to put it in the constructor because it might not be the constructor and endlessly repeating the initialization code in each constructor is obviously bad while using a no-arg constructor and relying on the automatic calls to this() can be unnerving.

So...

Here's the code I'd use myself:

class Example{
    private int[] tab;

    { tab = new int[10]; }

    public Example() {
        for(int i = 0 ; i < 10 ; i++)
            tab[i] = (int)(Math.random()*100);
        for(int i = 0 ; i < 10 ; i++)
            System.out.println(tab[i]);
    }
    public static void main(String[] arg) {
        Example ex = new Example();
    }
}

I'd even roughly use that structure: declare my private members, put in the initialization block, declare my constructors, declare the rest of my methods.




回答5:


I like to initialise my non-static instance variables in the constructor,

doing this makes it easier for other people to recognise which strategy is followed when the constructor is ran.

Each new object will have its very own tab instance, so in your example it doesn't matter if the class stays the same.

The only time I use a constructor is when I need to pass parameters that is applicable to the whole object and not to a specific method, example:

public class Authenticate{
    private String usrname;
    private String password;
    public Authenticate(String usernameParam,String passwordParam){
        this.usrname = usernameParam;
        this.password = passwordParam;
    }

    public void login(){
        //TODO put some code here to authenticate against some server using some technology.
    }

    public String getDepartment(){
        //Get the department where the username and password variable would be necessary if
        //login hasn't been called.
    }
}


来源:https://stackoverflow.com/questions/3830260/convention-in-java-new-outside-of-constructor-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!