To use the 'I' prefix for interfaces or not to

前端 未结 20 1432
长情又很酷
长情又很酷 2021-02-01 02:54

That is the question? So how big a sin is it not to use this convention when developing a c# project? This convention is widely used in the .NET class library. However, I am not

20条回答
  •  借酒劲吻你
    2021-02-01 03:31

    You can choose all names in your program how you like, but it's a good idea to hold naming conversion, if not you only will be read the program.

    Usage of Interfaces is good not only if you design you own classes and interfaces. In some cases you makes other accents in your program it you use interfaces. For example, you can write code like

    SqlDataReader dr = cmd.ExecuteReader (CommandBehavior.SequentialAccess);
    if (!dr.HasRows) {
        // ...
    }
    while (dr.Read ()) {
        string name = dr.GetString (0);
        // ...
    }
    

    or like

    IDataReader dr = cmd.ExecuteReader (CommandBehavior.SequentialAccess);
    if (!dr.HasRows) {
        // ...
    }
    while (dr.Read ()) {
        string name = dr.GetString (0);
        // ...
    }
    

    the last one have looks like the same, but if you are using IDataReader instead of SqlDataReader you can easier to place some parts which works with dr in a method, which works not only with SqlDataReader class (but with OleDbDataReader, OracleDataReader, OdbcDataReader etc). On the other hand your program stay working exactly quick as before.

    Updated (based on questions from comments):

    The advantage is, like I written before, if you'll separate some parts of you code which work with IDataReader. For example, you can define delegate T ReadRowFromDataReader (IDataReader dr, ...) and use it inside of while (dr.Read ()) block. So you write code which is more general as the code working with SqlDataReader directly. Inside of while (dr.Read ()) block you call rowReader (dr, ...). Your different implementations of code reading rows of data can be placed in a method with signature ReadRowFromDataReader rowReader and place it as a actual parameter.

    With the way you can write more independent code working with database. At the first time probably usage of generic delegate looks a little complex, but all code will be really easy to read. I want to accentuate one more time, that you really receive some advantages of using interfaces in this case only if you separate some parts of the code in another method. If you don't separate the code, the only advantage which you receive is: you receive code parts which are written more independend and you could copy and paced this parts easier in another program.

    Usage of names started with 'I' makes easier to understand that now we are working with something more general as with one class.

提交回复
热议问题