Is excessive DataTable usage bad?

前端 未结 5 1965
面向向阳花
面向向阳花 2021-01-31 05:10

I was recently asked to assist another team in building an ASP .NET website. They already have a significant amount of code written -- I was specifically asked build a few indiv

5条回答
  •  孤街浪徒
    2021-01-31 05:36

    Datatables can be used for good and evil.

    Acceptable Use

    I would find the following to be an acceptable use of a datatable or a datarow:

    public class User
    {
        private DataRow Row { get; set; };
        public User(DataRow row) { this.Row = row; }
    
        public string UserName { get { return (string)Row["Username"]; } }
        public int UserID { get { return (int)Row["UserID"]; } }
        public bool IsAdmin { get { return (bool)Row["IsAdmin"]; } }
        // ...
    }
    

    The class above is ok because it maps a DataRow to a typesafe class. Instead of working with strings and untyped datarows, now you have real datatypes and intellisense to assist you. Additionally, if your database schema changes, you can modify a column name in your object, instead of modifying the column name everywhere its used. Finally, you can map ugly column names like "dtaccount_created" to a property named "AccountCreated".

    Of course, there's really no good reason to write this wrapper class, since Visual Studio will automatically generate typed datasets for you. Or, as an alternative, a good ORM like NHibernate allows you to define classes similar to the one above.

    Whether you you should use plain old ADO.NET, typed datasets, or a full fledged ORM depends on the requirements and complexity of your application. Its hard to say whether your team is doing the right thing withotu actually seeing some sample code.

    Additionally, I occasionally find it useful to databind lists and grids with a datatable, because changes to the underlying datarow will automatically cause the GUI to refresh. If you create your own type-safe wrapper, then you need to implement the IPropertyChanging and IPropertyChanged interfaces manually.

    Unacceptable Use

    Unfortunately, I've seen programmers use datatables for ad hoc containers, alternatives to classes, etc. If you see your team doing this, throw rocks at them. That style of programming just doesn't work in a statically typed language, and its going to make development a nightmare.

    Main problem with datatables: they aren't typed, so you can't do anything useful with them without giving them a string and casting whatever mystery object they contain into the right type. Additionally, refactoring a column name is nearly impossible to automate since they are based on strings, so you can't rely on intellisense to help you write correct code, and you can't catch errors at compile time.

    I say trust your instinct: if you think design is flakey, it probably is.

提交回复
热议问题