When NOT to use the static keyword in Java?

后端 未结 9 845
轮回少年
轮回少年 2020-11-27 13:29

When is it considered poor practice to use the static keyword in Java on method signatures? If a method performs a function based upon some arguments, and does not require a

9条回答
  •  自闭症患者
    2020-11-27 14:25

    What you say is sort of true, but what happens when you want to override the behavior of that method in a derived class? If it's static, you can't do that.

    As an example, consider the following DAO type class:

    class CustomerDAO {
        public void CreateCustomer( Connection dbConn, Customer c ) {
           // Some implementation, created a prepared statement, inserts the customer record.
        }
    
        public Customer GetCustomerByID( Connection dbConn, int customerId ) {
           // Implementation
        }
    }
    

    Now, none of those methods require any "state". Everything they need is passed as parameters. So they COULD easily be static. Now the requirement comes along that you need to support a different database (lets say Oracle)

    Since those methods are not static, you could just create a new DAO class:

    class OracleCustomerDAO : CustomerDAO {
        public void CreateCustomer( Connection dbConn, Customer c ) {
            // Oracle specific implementation here.
        }
    
        public Customer GetCustomerByID( Connection dbConn, int customerId ) {
            // Oracle specific implementation here.
        }
    }
    

    This new class could now be used in place of the old one. If you are using dependancy injection, it might not even require a code change at all.

    But if we had made those methods static, that would make things much more complicated as we can't simply override the static methods in a new class.

提交回复
热议问题