How do programmers practice code reuse

前端 未结 14 1277
天涯浪人
天涯浪人 2021-02-13 14:14

I\'ve been a bad programmer because I am doing a copy and paste. An example is that everytime i connect to a database and retrieve a recordset, I will copy the previous code and

相关标签:
14条回答
  • 2021-02-13 14:35

    The essence of code reuse is to take a common operation and parameterize it so it can accept a variety of inputs.

    Take humble printf, for example. Imagine if you did not have printf, and only had write, or something similar:

    //convert theInt to a string and write it out.
    char c[24];
    itoa(theInt, c, 10);
    puts(c);
    

    Now this sucks to have to write every time, and is actually kind of buggy. So some smart programmer decided he was tired of this and wrote a better function, that in one fell swoop print stuff to stdout.

    printf("%d", theInt);
    

    You don't need to get as fancy as printf with it's variadic arguments and format string. Even just a simple routine such as:

    void print_int(int theInt)
    {
        char c[24];
        itoa(theInt, c, 10);
        puts(c);
    }
    

    would do the trick nickely. This way, if you want to change print_int to always print to stderr you could update it to be:

    void print_int(int theInt)
    {
        fprintf(stderr, "%d", theInt);
    }
    

    and all your integers would now magically be printed to standard error.

    You could even then bundle that function and others you write up into a library, which is just a collection of code you can load in to your program.

    Following the practice of code reuse is why you even have a database to connect to: someone created some code to store records on disk, reworked it until it was usable by others, and decided to call it a database.

    Libraries do not magically appear. They are created by programmers to make their lives easier and to allow them to work faster.

    0 讨论(0)
  • 2021-02-13 14:37

    I'll do this at two levels. First within a class or namespace, put that code piece that is reused in that scope in a separate method and make sure it is being called.

    Second is something similar to the case that you are describing. That is a good candidate to be put in a library or a helper/utility class that can be reused more broadly.

    It is important to evaluate everything that you are doing with an perspective whether it can be made available to others for reuse. This should be a fundamental approach to programming that most of us dont realize.

    Note that anything that is to be reused needs to be documented in more detail. Its naming convention be distinct, all the parameters, return results and any constraints/limitations/pre-requisites that are needed should be clearly documented (in code or help files).

    0 讨论(0)
  • 2021-02-13 14:41

    Good rule of thumb is if you use same piece three times, and it's obviously possible to generalize it, than make it a procedure/function/library.

    However, as I am getting older, and also more experienced as a professional developer, I am more inclined to see code reuse as not always the best idea, for two reasons:

    1. It's difficult to anticipate future needs, so it's very hard to define APIs so you would really use them next time. It can cost you twice as much time - once you make it more general just so that second time you are going to rewrite it anyway. It seems to me that especially Java projects of late are prone to this, they seem to be always rewritten in the framework du jour, just to be more "easier to integrate" or whatever in the future.

    2. In a larger organization (I am a member of one), if you have to rely on some external team (either in-house or 3rd party), you can have a problem. Your future then depends on their funding and their resources. So it can be a big burden to use foreign code or library. In a similar fashion, if you share a piece of code to some other team, they can then expect that you will maintain it.

    Note however, these are more like business reasons, so in open source, it's almost invariably a good thing to be reusable.

    0 讨论(0)
  • 2021-02-13 14:42

    Depending on the size of the project can change the answer.

    For a smaller project I would recommend setting up a DatabaseHelper class that does all your DB access. It would just be a wrapper around opening/closing connections and execution of the DB code. Then at a higher level you can just write the DBCommands that will be executed.

    A similar technique could be used for a larger project, but would need some additional work, interfaces need to be added, DI, as well as abstracting out what you need to know about the database.

    You might also try looking into ORM, DAAB, or over to the Patterns and Practices Group

    As far as how to prevent the ole C&P? - Well as you write your code, you need to periodically review it, if you have similar blocks of code, that only vary by a parameter or two, that is always a good candidate for refactoring into its own method.

    Now for my pseudo code example:

    Function GetCustomer(ID) as Customer
       Dim CMD as New DBCmd("SQL or Stored Proc")
       CMD.Paramaters.Add("CustID",DBType,Length).Value = ID
       Dim DHelper as New DatabaseHelper
       DR = DHelper.GetReader(CMD)
       Dim RtnCust as New Customer(Dx)
       Return RtnCust
    End Function
    
    Class DataHelper
      Public Function GetDataTable(cmd) as DataTable
        Write the DB access code stuff here.
        GetConnectionString
        OpenConnection
        Do DB Operation
        Close Connection
      End Function
      Public Function GetDataReader(cmd) as DataReader
      Public Function GetDataSet(cmd) as DataSet
      ... And So on ...
    End Class
    
    0 讨论(0)
  • 2021-02-13 14:42

    to get code reuse you need to become a master of...

    1. Giving things names that capture their essence. This is really really important
    2. Making sure that it only does one thing. This is really comes back to the first point, if you can't name it by its essence, then often its doing too much.
    3. Locating the thing somewhere logical. Again this comes back to being able to name things well and capturing its essence...
    4. Grouping it with things that build on a central concept. Same as above, but said differntly :-)
    0 讨论(0)
  • 2021-02-13 14:42

    I think the best way to answer your problem is that create a separate assembly for your important functions.. in this way you can create extension methods or modify the helper assemble itself.. think of this function..

    ExportToExcel(List date, string filename)

    this method can be use for your future excel export functions so why don't store it in your own helper assembly.. i this way you just add reference to these assemblies.

    0 讨论(0)
提交回复
热议问题