CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Good design?

  1. #1
    Join Date
    Mar 2007
    Posts
    155

    Good design?

    Is the below design OK?

    Code:
        public abstract class MyAbstract
        {
            public Dictionary<int, ushort> Table
            {
                get;
                protected set;   
            }
    
            protected MyAbstract()
            {
                PopulateTable();
            }
    
            protected abstract void PopulateTable();
        }
    Table will be initialized inside PopulateTable() by it's derived classes;
    Last edited by thomus07; April 16th, 2010 at 03:24 AM. Reason: added more details :)

  2. #2
    Join Date
    May 2007
    Posts
    1,546

    Re: Good design?

    Calling virtual (or abstract) methods in a constructor is generally not a good idea as it will 'break' any initialisation of member variables which a subclass performs.

    If someone subclasses 'MyAbstract' and initialises variables in their constructor which they rely on in their implementation of PopulateTable - those variables will be null when PopulateTable is called. The easiest way to work around this issue is to only create instances of MyAbstract through a factory so you can do something like:

    Code:
    public T Create <T> () where T : MyAbstract, new ()
    {
        T instance = new T ();
        instance.PopulateTable ();
        return instance;
    }
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

  3. #3
    Join Date
    Mar 2007
    Posts
    155

    Re: Good design?

    Thanks, that makes sense.

    I have now modified to:
    Code:
        public abstract class MyAbstract
        {
           public abstract Dictionary<int, ushort> Table { get; } 
        }
    And I think the above code doesn't bring big difference to interface
    Last edited by thomus07; April 16th, 2010 at 05:48 AM. Reason: added code tags

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured