constructor methods in interfaces

后端 未结 6 2336
闹比i
闹比i 2021-02-18 21:03

Are constructor methods in interfaces bad?

6条回答
  •  没有蜡笔的小新
    2021-02-18 21:22

    First off, I disagree that interface is just a data passing contract. If that were true you would be allowed to define properties in an interface.

    I wouldn't exactly think it's weird to do something like:

    interface IDBConnection
    {
        function __construct( $connectionString );
        function executeNonQuery( $commandText, $paramters=null);
        function executeScalar( $commandText, $paramters=null);
        function executeSingle( $commandText, $paramters=null);
        function executeArray( $commandText, $paramters=null);
    }
    

    This would enable you to create instances of third party classes for data access based on simple reflection instead of just being a data contract.

    I'm pretty sure that this isn't the best example, I'd go for an abstract base class here in the real world, but I'm also pretty sure that there are perfectly valid reasons for defining a constructor methods' contract in an interface that I haven't thought of.

    I haven't seen it done, but i wouldn't think it to be weird or bad.

提交回复
热议问题