It's a question about the if statement

Asked 2 years ago, Updated 2 years ago, 32 views

Code is Java, but not limited to Java. The code below is to create a class in a single tone pattern.

public class Company {
    Create constructor with privateCompany(){}; //private
    private static Company com =new Company();

    public static Company getInstance() {
        if(com==null) {
            com=new Company();
        }
        return com;

    }
}

The question I want to ask here is

 if(com==null) {
            com=new Company();
        }
        return com;

Code above and

 if(com==null) {
            com=new Company();
``          ``          return com;
        }
       else
        return com;

I was wondering if there was a difference. Can you tell me the difference between writing if only one and writing if-else?

java c c++

2022-09-22 18:54

3 Answers

The behavior of each language will vary slightly, but the grand principle is roughly like this.

Therefore, the two blocks that you uploaded perform the same logic:

But depending on the intent of the whole method, there's room for some modification or choice.


2022-09-22 18:54

Unless it's for a special purpose (For the purpose of stating in advance that each block may use a different return value...) I think it's a convention or just a difference in taste. h

As you expected, the chords are different, but the movements are the same. Even if you go through code optimization in the compilation stage, Both codes are likely to be translated into the same machine language.


2022-09-22 18:54

In fact, com cannot be null when viewed only by the given code (i.e., when it is Java).

In other words, the if syntax is meaningless and will be optimized and deleted by the compiler.

This unnecessary branching optimization is the same for c/c++.

It is recommended that the code for the question be written as follows.

public class Company {
    Create constructor with privateCompany(){}; //private
    private static Company com =new Company();

    public static Company getInstance() {
        return com;
    }
}

It's better down than down.

public class Company {
    private static Company com; 
    static {
        com =new Company();
    }
    Create constructor with privateCompany(){}; //private

    public static Company getInstance() {
        return com;
    }
}


2022-09-22 18:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.