Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Is this good code practice?

Is this good code practice?

Scheduled Pinned Locked Moved C#
helpquestion
39 Posts 10 Posters 6 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Lost User

    Well if it's just that you could just go back and add some cases.. right?

    V Offline
    V Offline
    venomation
    wrote on last edited by
    #19

    Ok thanks for all the comments, it appears that a switch is all that is needed :-D

    1 Reply Last reply
    0
    • V venomation

      I used the following code in a programming lesson to help me with a project but the lecturer says it is hard to maintain although I made it like that for better manageability:

          static List \_person = new List();
          static void Main()
          {
              Dictionary methodList = new Dictionary();
      
              methodList.Add("1", (() =>
                  \_person.ForEach(s => Console.WriteLine("{0} {1}", s.Name, s.Title))));
      
              \_person.Add(new Person( "James","Prog" ));
              \_person.Add(new Person( "Claire","Illu"));
      
              Console.WriteLine("Press 1 to show all data or 2 to quit");
      
              string input = Console.ReadLine();
              if (methodList.ContainsKey(input)) methodList\[input\]();
      
              Console.Read();
      
          }
      
      A Offline
      A Offline
      AspDotNetDev
      wrote on last edited by
      #20

      If you need that logic in multiple places, there might be some value in putting it in a dictionary structure (e.g., if you need a combination of the values and the logic for selecting which keys depends on where the dictionary is used). That way, you can pass the dictionary around. Then again, you could just wrap a switch statement in a delegate and pass that around (may not work well if there is custom logic to access several keys). In this specific case, I see no reason a switch statement should not be used. It is certainly simpler and I recommend choosing the simpler approach unless there is a real chance you will need the more complex approach later.

      [Forum Guidelines]

      1 Reply Last reply
      0
      • V venomation

        I used the following code in a programming lesson to help me with a project but the lecturer says it is hard to maintain although I made it like that for better manageability:

            static List \_person = new List();
            static void Main()
            {
                Dictionary methodList = new Dictionary();
        
                methodList.Add("1", (() =>
                    \_person.ForEach(s => Console.WriteLine("{0} {1}", s.Name, s.Title))));
        
                \_person.Add(new Person( "James","Prog" ));
                \_person.Add(new Person( "Claire","Illu"));
        
                Console.WriteLine("Press 1 to show all data or 2 to quit");
        
                string input = Console.ReadLine();
                if (methodList.ContainsKey(input)) methodList\[input\]();
        
                Console.Read();
        
            }
        
        A Offline
        A Offline
        Abhinav S
        wrote on last edited by
        #21

        You might want to move some of this code out of your main method and into other methods. For e.g.

        thebuzzwright wrote:

        methodList.Add("1", (() => _person.ForEach(s => Console.WriteLine("{0} {1}", s.Name, s.Title))));

        might go into a readInput() method.

        thebuzzwright wrote:

        person.Add(new Person( "James","Prog" )); _person.Add(new Person( "Claire","Illu"));

        could go into loadData() or something like that.

        thebuzzwright wrote:

        string input = Console.ReadLine(); if (methodList.ContainsKey(input)) methodList[input]();

        could go into a method called userResponse(). If any of these methods are modified later, these logical groups might make it easier for others to understand what is done where in the program.

        modified on Saturday, May 1, 2010 12:39 AM

        1 Reply Last reply
        0
        • P PIEBALDconsult

          "I know that there are people who do not love their fellow man, and I hate people like that!" -- Tom Lehrer

          R Offline
          R Offline
          Roger Wright
          wrote on last edited by
          #22

          PIEBALDconsult wrote:

          Tom Lehrer

          One of my heroes!

          "A Journey of a Thousand Rest Stops Begins with a Single Movement"

          1 Reply Last reply
          0
          • V venomation

            I used the following code in a programming lesson to help me with a project but the lecturer says it is hard to maintain although I made it like that for better manageability:

                static List \_person = new List();
                static void Main()
                {
                    Dictionary methodList = new Dictionary();
            
                    methodList.Add("1", (() =>
                        \_person.ForEach(s => Console.WriteLine("{0} {1}", s.Name, s.Title))));
            
                    \_person.Add(new Person( "James","Prog" ));
                    \_person.Add(new Person( "Claire","Illu"));
            
                    Console.WriteLine("Press 1 to show all data or 2 to quit");
            
                    string input = Console.ReadLine();
                    if (methodList.ContainsKey(input)) methodList\[input\]();
            
                    Console.Read();
            
                }
            
            S Offline
            S Offline
            Som Shekhar
            wrote on last edited by
            #23

            I see the point your Lecturer is trying to convey. You are at a learning stage. Hence there will always be possibilities that the code you write will need to be improved/modified/tweaked. If this is the final code piece and there cannot be any more changes to be made, this code is fine. However if there is a possibility that someone else may be using your code (as in the case of Open Source/ or in a Production Environment), this code may cause misunderstandings. Consider this, what happens if you join a company and are given this piece of code and are asked to make some changes. How comfortable would you be? (You understand this code. But any other such code example?)

            1 Reply Last reply
            0
            • realJSOPR realJSOP

              Don't you just hate zealots? :)

              .45 ACP - because shooting twice is just silly
              -----
              "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
              -----
              "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

              P Offline
              P Offline
              Pete OHanlon
              wrote on last edited by
              #24

              You rang?

              "WPF has many lovers. It's a veritable porn star!" - Josh Smith

              As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

              My blog | My articles | MoXAML PowerToys | Onyx

              1 Reply Last reply
              0
              • V venomation

                I used the following code in a programming lesson to help me with a project but the lecturer says it is hard to maintain although I made it like that for better manageability:

                    static List \_person = new List();
                    static void Main()
                    {
                        Dictionary methodList = new Dictionary();
                
                        methodList.Add("1", (() =>
                            \_person.ForEach(s => Console.WriteLine("{0} {1}", s.Name, s.Title))));
                
                        \_person.Add(new Person( "James","Prog" ));
                        \_person.Add(new Person( "Claire","Illu"));
                
                        Console.WriteLine("Press 1 to show all data or 2 to quit");
                
                        string input = Console.ReadLine();
                        if (methodList.ContainsKey(input)) methodList\[input\]();
                
                        Console.Read();
                
                    }
                
                P Offline
                P Offline
                Pete OHanlon
                wrote on last edited by
                #25

                As a switch zealot (only kidding), I don't see anything wrong with you using the dictionary - as long as you were doing it for one particular case (you aren't in this case so a switch would be a better choice). If your application was using Dependency Injection with plugins then it could make sense to use the dictionary because you may have more and more plugins so your code would constantly need to be modified. In this case, it looks like the lecturer is complaining about the lambda. I like Expressions in their place but there comes a time when you need to step back and ask yourself if your code is clean and easy to read.

                "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                My blog | My articles | MoXAML PowerToys | Onyx

                V 1 Reply Last reply
                0
                • P Pete OHanlon

                  As a switch zealot (only kidding), I don't see anything wrong with you using the dictionary - as long as you were doing it for one particular case (you aren't in this case so a switch would be a better choice). If your application was using Dependency Injection with plugins then it could make sense to use the dictionary because you may have more and more plugins so your code would constantly need to be modified. In this case, it looks like the lecturer is complaining about the lambda. I like Expressions in their place but there comes a time when you need to step back and ask yourself if your code is clean and easy to read.

                  "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                  As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                  My blog | My articles | MoXAML PowerToys | Onyx

                  V Offline
                  V Offline
                  venomation
                  wrote on last edited by
                  #26

                  Thanks for the replies its quite a mixed view from what im getting so far, from what I understand I should use a switch but if it were to be like a component "plug in and play" style I would use the approach I am using so far. Thanks again ! :-D

                  P 1 Reply Last reply
                  0
                  • V venomation

                    Thanks for the replies its quite a mixed view from what im getting so far, from what I understand I should use a switch but if it were to be like a component "plug in and play" style I would use the approach I am using so far. Thanks again ! :-D

                    P Online
                    P Online
                    PIEBALDconsult
                    wrote on last edited by
                    #27

                    There are two concerns really, and perhaps your lecturer didn't clearly state which he's concerned about (or both?): 0) Switch vs. Dictionary of delegates 1) Regular Method vs. Anonymous Method vs. Anonymous Method with lambda As written, I would go with the switch, as that would also eliminate both concerns. However, when you consider growth, the Dictionary may be the way to go. But before you get there you should make your code more modular (as suggested by Abhinav S). In a command-line-oriented application I'm working on I have an OperationMap class that is a Dictionary of Dictionaries of delegates. The delegates all refer to "regular" methods in the API. Here's most of the Run method of my command line interpreter:

                    Command cmd = null ;

                    do
                    {
                    try
                    {
                    cmd = GetCommand ( interactive ) ;

                        OperationMap \[ cmd.Operation \] \[ cmd.Entity \] 
                        ( 
                            this.api 
                        ,
                            cmd 
                        ) ;
                    }
                    catch ( System.Exception err ) 
                    {
                        System.Console.WriteLine ( err ) ;
                    }
                    

                    }
                    while ( cmd.Operation != Operation.Exit ) ;

                    Notice how things like getting the command from the user is done by another method rather than muddying up this method. Modularity, separation of responsibility, encapsulation, etc. are things you should master before trying to use anonymous methods and lambdas. Also, start thinking of your applications in layers. Generally, your interface should call methods of your API, your API should call methods in your business layer, your business layer should call methods in your data access layer, etc. In the "real world", rather than using anonymous methods and lambdas, your Dictionary will more likely contain references to methods in the API. As an excercise, write a class that implements a collection of your Person class and offers a DumpAllToConsole() method, then add a delegate to DumpAllToConsole to your Dictionary. Oh, and the Person class should probably have an override of ToString that formats itself properly, and maybe a FullName property.

                    V 1 Reply Last reply
                    0
                    • P PIEBALDconsult

                      There are two concerns really, and perhaps your lecturer didn't clearly state which he's concerned about (or both?): 0) Switch vs. Dictionary of delegates 1) Regular Method vs. Anonymous Method vs. Anonymous Method with lambda As written, I would go with the switch, as that would also eliminate both concerns. However, when you consider growth, the Dictionary may be the way to go. But before you get there you should make your code more modular (as suggested by Abhinav S). In a command-line-oriented application I'm working on I have an OperationMap class that is a Dictionary of Dictionaries of delegates. The delegates all refer to "regular" methods in the API. Here's most of the Run method of my command line interpreter:

                      Command cmd = null ;

                      do
                      {
                      try
                      {
                      cmd = GetCommand ( interactive ) ;

                          OperationMap \[ cmd.Operation \] \[ cmd.Entity \] 
                          ( 
                              this.api 
                          ,
                              cmd 
                          ) ;
                      }
                      catch ( System.Exception err ) 
                      {
                          System.Console.WriteLine ( err ) ;
                      }
                      

                      }
                      while ( cmd.Operation != Operation.Exit ) ;

                      Notice how things like getting the command from the user is done by another method rather than muddying up this method. Modularity, separation of responsibility, encapsulation, etc. are things you should master before trying to use anonymous methods and lambdas. Also, start thinking of your applications in layers. Generally, your interface should call methods of your API, your API should call methods in your business layer, your business layer should call methods in your data access layer, etc. In the "real world", rather than using anonymous methods and lambdas, your Dictionary will more likely contain references to methods in the API. As an excercise, write a class that implements a collection of your Person class and offers a DumpAllToConsole() method, then add a delegate to DumpAllToConsole to your Dictionary. Oh, and the Person class should probably have an override of ToString that formats itself properly, and maybe a FullName property.

                      V Offline
                      V Offline
                      venomation
                      wrote on last edited by
                      #28

                      That is an awesome answer thank you for that ! :-D I was not completely sure of what the exercise meant but I gave it a try:

                      class Person
                      {
                          private string \_forName;
                          private string \_surName;
                          private string \_title;
                      
                          public Person(string forname, string surname, string title)
                          {
                              ForName = forname;
                              SurName = surname;
                              Title = title;
                          }
                      
                          public string ForName
                          {
                              get { return \_forName; }
                              set { \_forName = value; }
                          }
                      
                          public string SurName
                          {
                              get { return \_surName; }
                              set { \_surName = value; }
                          }
                      
                          public string Title
                          {
                              get { return \_title; }
                              set { \_title = value; }
                          }
                      
                          public override string ToString()
                          {
                              string fullName = string.Format("{0} {1} {2}", ForName, SurName,Title);
                              return fullName; ;
                          }
                      
                      }
                      
                      class PersonManager
                      {
                          private List \_personList;
                      
                          public PersonManager()
                          {
                              \_personList = new List(10);
                              //add a few people as a test
                              \_personList.Add(new Person("James", "x", "Prog"));
                              \_personList.Add(new Person("Claire", "y", "Illu"));
                          }
                      
                          public void DumpAllToConsole()
                          {
                              //Prints the details of every person
                              foreach (Person p in \_personList)
                              {
                                  Console.WriteLine(p.ToString());
                              }
                          }
                      }
                      
                      class Program
                      {
                          delegate void DictionaryDel();
                          static DictionaryDel \_invokeAction;
                          static Dictionary \_action;
                          static PersonManager \_personManager;
                      
                          static void Main()
                          {
                              \_action = new Dictionary();
                              \_personManager = new PersonManager();
                      
                              \_invokeAction += \_personManager.DumpAllToConsole;
                      
                              \_action.Add(\_personManager, \_invokeAction);
                      
                              \_action\[\_personManager\]();
                      
                      
                              Console.Read();
                      
                          }
                      }
                      

                      ?

                      P 1 Reply Last reply
                      0
                      • V venomation

                        That is an awesome answer thank you for that ! :-D I was not completely sure of what the exercise meant but I gave it a try:

                        class Person
                        {
                            private string \_forName;
                            private string \_surName;
                            private string \_title;
                        
                            public Person(string forname, string surname, string title)
                            {
                                ForName = forname;
                                SurName = surname;
                                Title = title;
                            }
                        
                            public string ForName
                            {
                                get { return \_forName; }
                                set { \_forName = value; }
                            }
                        
                            public string SurName
                            {
                                get { return \_surName; }
                                set { \_surName = value; }
                            }
                        
                            public string Title
                            {
                                get { return \_title; }
                                set { \_title = value; }
                            }
                        
                            public override string ToString()
                            {
                                string fullName = string.Format("{0} {1} {2}", ForName, SurName,Title);
                                return fullName; ;
                            }
                        
                        }
                        
                        class PersonManager
                        {
                            private List \_personList;
                        
                            public PersonManager()
                            {
                                \_personList = new List(10);
                                //add a few people as a test
                                \_personList.Add(new Person("James", "x", "Prog"));
                                \_personList.Add(new Person("Claire", "y", "Illu"));
                            }
                        
                            public void DumpAllToConsole()
                            {
                                //Prints the details of every person
                                foreach (Person p in \_personList)
                                {
                                    Console.WriteLine(p.ToString());
                                }
                            }
                        }
                        
                        class Program
                        {
                            delegate void DictionaryDel();
                            static DictionaryDel \_invokeAction;
                            static Dictionary \_action;
                            static PersonManager \_personManager;
                        
                            static void Main()
                            {
                                \_action = new Dictionary();
                                \_personManager = new PersonManager();
                        
                                \_invokeAction += \_personManager.DumpAllToConsole;
                        
                                \_action.Add(\_personManager, \_invokeAction);
                        
                                \_action\[\_personManager\]();
                        
                        
                                Console.Read();
                        
                            }
                        }
                        

                        ?

                        P Online
                        P Online
                        PIEBALDconsult
                        wrote on last edited by
                        #29

                        Hmmm... just about. :thumbsup: I'm not much for needless local variables, so I wouldn't use the fullName in the ToString and the _invokeAction in Main. I also thought you'd still want to do the menu and have the same Dictionary as before, but use the _personManager.DumpAllToConsole rather than the anonymous method. Also usually += is used with events, not "regular" delegates. (And it still looks like your generic parameters got eaten by the forum -- check the Encode "<" (and other HTML) characters when pasting option.)

                        V 1 Reply Last reply
                        0
                        • P PIEBALDconsult

                          Hmmm... just about. :thumbsup: I'm not much for needless local variables, so I wouldn't use the fullName in the ToString and the _invokeAction in Main. I also thought you'd still want to do the menu and have the same Dictionary as before, but use the _personManager.DumpAllToConsole rather than the anonymous method. Also usually += is used with events, not "regular" delegates. (And it still looks like your generic parameters got eaten by the forum -- check the Encode "<" (and other HTML) characters when pasting option.)

                          V Offline
                          V Offline
                          venomation
                          wrote on last edited by
                          #30

                          Thanks for the reply I left the Person class as it is but changed Program:

                            class Program
                          {
                              delegate void DictionaryDel();
                          
                              static Dictionary<string, DictionaryDel> \_action;
                              static PersonManager \_personManager;
                          
                              static void Main()
                              {
                                  
                                  \_personManager = new PersonManager();
                          
                                  LoadActions();
                          
                                 
                                  \_action\["1"\]();
                          
                          
                                  Console.Read();
                          
                              }
                          
                              static void LoadActions()
                              {
                                  \_action = new Dictionary<string, DictionaryDel>();
                                  \_action.Add("1", \_personManager.DumpAllToConsole);
                              }
                          }
                          

                          modified on Sunday, May 2, 2010 8:01 AM

                          P 1 Reply Last reply
                          0
                          • V venomation

                            Thanks for the reply I left the Person class as it is but changed Program:

                              class Program
                            {
                                delegate void DictionaryDel();
                            
                                static Dictionary<string, DictionaryDel> \_action;
                                static PersonManager \_personManager;
                            
                                static void Main()
                                {
                                    
                                    \_personManager = new PersonManager();
                            
                                    LoadActions();
                            
                                   
                                    \_action\["1"\]();
                            
                            
                                    Console.Read();
                            
                                }
                            
                                static void LoadActions()
                                {
                                    \_action = new Dictionary<string, DictionaryDel>();
                                    \_action.Add("1", \_personManager.DumpAllToConsole);
                                }
                            }
                            

                            modified on Sunday, May 2, 2010 8:01 AM

                            P Online
                            P Online
                            PIEBALDconsult
                            wrote on last edited by
                            #31

                            :thumbsup: Good call on writing LoadActions -- now can you make a class to encapsulate the menu options? Menu menu = new Menu ( _personManager ) ;

                            V 1 Reply Last reply
                            0
                            • P PIEBALDconsult

                              :thumbsup: Good call on writing LoadActions -- now can you make a class to encapsulate the menu options? Menu menu = new Menu ( _personManager ) ;

                              V Offline
                              V Offline
                              venomation
                              wrote on last edited by
                              #32

                              This is the code that I have created so far, your comments are very helpful!

                              class Program
                              {

                                  static void Main()
                                  {
                                      PersonManager personManager = new PersonManager();
                                      Menu mainMenu = new Menu(personManager);
                                      mainMenu.LoadActions();
                                      mainMenu.Display();
                                     
                                      Console.Read();
                              
                                  }
                              }
                              
                                 class Person
                              {
                                  public Person(string forname, string surname, string title)
                                  {
                                      ForName = forname;
                                      SurName = surname;
                                      Title = title;
                                  }
                              
                                  public string ForName { get; set; }
                              
                                  public string SurName { get; set; }
                              
                                  public string Title { get; set; }
                              
                                  public override string ToString()
                                  {
                                      string fullName = string.Format("Name :{0} {1}\\nTitle {2}", ForName, SurName, Title);
                                      return fullName;
                                  }
                              
                              }
                              
                              class PersonManager
                              {
                                  private readonly List \_personList;
                              
                                  public PersonManager()
                                  {
                                      //add a few people as a test
                                      \_personList = new List(10)
                                                        {
                                                            new Person("James", "x", "Prog"),
                                                            new Person("Claire", "y", "Illu")
                                                        };
                              
                                  }
                              
                                  public void DumpAllToConsole()
                                  {
                                      //Prints the details of every person
                                      foreach (Person p in \_personList)
                                      {
                                          Console.WriteLine(p.ToString());
                                      }
                                  }
                              }
                              

                              class Menu
                              {
                              private readonly PersonManager _personManager;
                              private delegate void DictionaryDel();
                              private Dictionary _action;

                                  public Menu(PersonManager personManager)
                                  {
                                      \_personManager = personManager;
                              
                                  }
                              
                                  void GetInput(string input)
                                  {
                                      if (\_action.Count == 0) return;
                                      if (!\_action.ContainsKey(input)) return;
                              
                                      \_action\[input\]();
                                  }
                              
                              
                              
                                  public void LoadActions()
                                  {
                                      \_action = new Dictionary
                                                    {
                                                        {"1", \_personManager.DumpAllToConsole}
                                                    };
                                  }
                              
                                  public void Display()
                                  {
                                      Console.WriteLine("Press 1 to display all students or 2 t
                              
                              P 1 Reply Last reply
                              0
                              • V venomation

                                This is the code that I have created so far, your comments are very helpful!

                                class Program
                                {

                                    static void Main()
                                    {
                                        PersonManager personManager = new PersonManager();
                                        Menu mainMenu = new Menu(personManager);
                                        mainMenu.LoadActions();
                                        mainMenu.Display();
                                       
                                        Console.Read();
                                
                                    }
                                }
                                
                                   class Person
                                {
                                    public Person(string forname, string surname, string title)
                                    {
                                        ForName = forname;
                                        SurName = surname;
                                        Title = title;
                                    }
                                
                                    public string ForName { get; set; }
                                
                                    public string SurName { get; set; }
                                
                                    public string Title { get; set; }
                                
                                    public override string ToString()
                                    {
                                        string fullName = string.Format("Name :{0} {1}\\nTitle {2}", ForName, SurName, Title);
                                        return fullName;
                                    }
                                
                                }
                                
                                class PersonManager
                                {
                                    private readonly List \_personList;
                                
                                    public PersonManager()
                                    {
                                        //add a few people as a test
                                        \_personList = new List(10)
                                                          {
                                                              new Person("James", "x", "Prog"),
                                                              new Person("Claire", "y", "Illu")
                                                          };
                                
                                    }
                                
                                    public void DumpAllToConsole()
                                    {
                                        //Prints the details of every person
                                        foreach (Person p in \_personList)
                                        {
                                            Console.WriteLine(p.ToString());
                                        }
                                    }
                                }
                                

                                class Menu
                                {
                                private readonly PersonManager _personManager;
                                private delegate void DictionaryDel();
                                private Dictionary _action;

                                    public Menu(PersonManager personManager)
                                    {
                                        \_personManager = personManager;
                                
                                    }
                                
                                    void GetInput(string input)
                                    {
                                        if (\_action.Count == 0) return;
                                        if (!\_action.ContainsKey(input)) return;
                                
                                        \_action\[input\]();
                                    }
                                
                                
                                
                                    public void LoadActions()
                                    {
                                        \_action = new Dictionary
                                                      {
                                                          {"1", \_personManager.DumpAllToConsole}
                                                      };
                                    }
                                
                                    public void Display()
                                    {
                                        Console.WriteLine("Press 1 to display all students or 2 t
                                
                                P Online
                                P Online
                                PIEBALDconsult
                                wrote on last edited by
                                #33

                                :thumbsup: (Especially for the automatic properties (or whatever they're called).) Not much else: Maybe GetInput should be named DoAction instead? I would likely call the LoadActions from the constructor. I would have a while loop in Display. You may also consider creating an interface from the PersonManager so the Menu can be used with other types of manager. Come to think of it, maybe the Manager should be generic -- Manager<Person>.

                                V 1 Reply Last reply
                                0
                                • P PIEBALDconsult

                                  :thumbsup: (Especially for the automatic properties (or whatever they're called).) Not much else: Maybe GetInput should be named DoAction instead? I would likely call the LoadActions from the constructor. I would have a while loop in Display. You may also consider creating an interface from the PersonManager so the Menu can be used with other types of manager. Come to think of it, maybe the Manager should be generic -- Manager<Person>.

                                  V Offline
                                  V Offline
                                  venomation
                                  wrote on last edited by
                                  #34

                                  Thanks again, I have implemented your advise and I can see that it is a much more manageable way that what it originally was, even though there is allot more work involved it does pay off! :laugh:

                                  class Program
                                  {
                                  
                                      static void Main()
                                      {
                                          Manager<Person> personManager = new Manager<Person>();
                                  
                                          //adding two people for a test purpose
                                          personManager.Add(new Person("James","x","Soft"));
                                          personManager.Add(new Person("Claire", "y", "Illu"));
                                  
                                          Menu mainMenu = new Menu(personManager);
                                          mainMenu.Display();
                                         
                                  
                                  
                                      }
                                  }
                                  

                                  class Manager<T>
                                  {
                                  private readonly List<T> _managedList;

                                      public Manager()
                                      {
                                          \_managedList = new List<T>(10);
                                      }
                                  
                                      public void DumpAllToConsole()
                                      {
                                          foreach (T p in \_managedList)
                                          {
                                              Console.WriteLine(p + "\\n");
                                              
                                          }
                                      }
                                  
                                      public void Add(T input)
                                      {
                                          if (input.Equals(null)) return;
                                  
                                          \_managedList.Add(input);
                                  
                                      }
                                  
                                      public void Remove(T item)
                                      {
                                         if (!\_managedList.Contains(item)) return;
                                          \_managedList.Remove(item);
                                      }
                                  
                                      public List<T> GetCopyOfList()
                                      {
                                          List<T> list = new List<T>(\_managedList);
                                          return list;
                                      }
                                   
                                  }
                                  

                                  class Menu
                                  {
                                  private readonly Manager<Person> _personManager;
                                  private delegate void DictionaryDel();
                                  private Dictionary<string, DictionaryDel> _action;
                                  private bool _running = true;
                                  public Menu(Manager<Person> personManager)
                                  {
                                  _personManager = personManager;
                                  LoadActions();

                                      }
                                  
                                      void DoAction(string input)
                                      {
                                          if (\_action.Count == 0) return;
                                          if (!\_action.ContainsKey(input)) return;
                                  
                                          \_action\[input\]();
                                      }
                                  
                                  
                                  
                                      void LoadActions()
                                      {
                                          \_action = new Dictionary<string, DictionaryDel>
                                                        {
                                                            {"1", \_personManager.DumpAllToConsole},
                                                            {"2",(() => \_running = false)}
                                  
                                      };
                                      //I personally think using the lambda here is ok...anyone care to tell me otherwise? :P
                                  
                                      }
                                  
                                      public void Dis
                                  
                                  P 1 Reply Last reply
                                  0
                                  • V venomation

                                    Thanks again, I have implemented your advise and I can see that it is a much more manageable way that what it originally was, even though there is allot more work involved it does pay off! :laugh:

                                    class Program
                                    {
                                    
                                        static void Main()
                                        {
                                            Manager<Person> personManager = new Manager<Person>();
                                    
                                            //adding two people for a test purpose
                                            personManager.Add(new Person("James","x","Soft"));
                                            personManager.Add(new Person("Claire", "y", "Illu"));
                                    
                                            Menu mainMenu = new Menu(personManager);
                                            mainMenu.Display();
                                           
                                    
                                    
                                        }
                                    }
                                    

                                    class Manager<T>
                                    {
                                    private readonly List<T> _managedList;

                                        public Manager()
                                        {
                                            \_managedList = new List<T>(10);
                                        }
                                    
                                        public void DumpAllToConsole()
                                        {
                                            foreach (T p in \_managedList)
                                            {
                                                Console.WriteLine(p + "\\n");
                                                
                                            }
                                        }
                                    
                                        public void Add(T input)
                                        {
                                            if (input.Equals(null)) return;
                                    
                                            \_managedList.Add(input);
                                    
                                        }
                                    
                                        public void Remove(T item)
                                        {
                                           if (!\_managedList.Contains(item)) return;
                                            \_managedList.Remove(item);
                                        }
                                    
                                        public List<T> GetCopyOfList()
                                        {
                                            List<T> list = new List<T>(\_managedList);
                                            return list;
                                        }
                                     
                                    }
                                    

                                    class Menu
                                    {
                                    private readonly Manager<Person> _personManager;
                                    private delegate void DictionaryDel();
                                    private Dictionary<string, DictionaryDel> _action;
                                    private bool _running = true;
                                    public Menu(Manager<Person> personManager)
                                    {
                                    _personManager = personManager;
                                    LoadActions();

                                        }
                                    
                                        void DoAction(string input)
                                        {
                                            if (\_action.Count == 0) return;
                                            if (!\_action.ContainsKey(input)) return;
                                    
                                            \_action\[input\]();
                                        }
                                    
                                    
                                    
                                        void LoadActions()
                                        {
                                            \_action = new Dictionary<string, DictionaryDel>
                                                          {
                                                              {"1", \_personManager.DumpAllToConsole},
                                                              {"2",(() => \_running = false)}
                                    
                                        };
                                        //I personally think using the lambda here is ok...anyone care to tell me otherwise? :P
                                    
                                        }
                                    
                                        public void Dis
                                    
                                    P Online
                                    P Online
                                    PIEBALDconsult
                                    wrote on last edited by
                                    #35

                                    :thumbsup: It's turning out better than I thought. In Add, I would use a simple if ( input == null ) (this isn't Java). Yeah, the lambda seems good there. GetCopyOfList is a good idea, but look into list.AsReadOnly() to see if it might be what you want there. I would still argue for an Interface that the Menu class requires -- that way it can (theoretically) be used with different types of Manager. So far I see no need to make Menu be generic, but you may consider it.

                                    thebuzzwright wrote:

                                    "orthogonality"

                                    That's one of the (few) things I remember from college. :thumbsup:

                                    thebuzzwright wrote:

                                    even though there is allot more work involved it does pay off

                                    It certainly can. It may not in this case, but having experience in how to do this sort of abstraction should pay off when it's really needed later.

                                    V 1 Reply Last reply
                                    0
                                    • P PIEBALDconsult

                                      :thumbsup: It's turning out better than I thought. In Add, I would use a simple if ( input == null ) (this isn't Java). Yeah, the lambda seems good there. GetCopyOfList is a good idea, but look into list.AsReadOnly() to see if it might be what you want there. I would still argue for an Interface that the Menu class requires -- that way it can (theoretically) be used with different types of Manager. So far I see no need to make Menu be generic, but you may consider it.

                                      thebuzzwright wrote:

                                      "orthogonality"

                                      That's one of the (few) things I remember from college. :thumbsup:

                                      thebuzzwright wrote:

                                      even though there is allot more work involved it does pay off

                                      It certainly can. It may not in this case, but having experience in how to do this sort of abstraction should pay off when it's really needed later.

                                      V Offline
                                      V Offline
                                      venomation
                                      wrote on last edited by
                                      #36

                                      Thanks again "PIEBALDconsult" you have helped me allot ! I don't feel the need to show the code as its just minor changes but: 1 - I added a IMenu interface which can "Display" so that I can derive new menu's for other situations. 2 - Menu inherits IMenu and I replaced " Menu mainMenu = new Menu(personManager);" with " IMenu mainMenu = new Menu(personManager);" so that I can use different menu's. 3 - I decided to switch the List with an IList so that I can use the "AsReadOnly()" method as I don't need to modify the contents. 4 - For the "Add" method: "if (input != null) ManagedList.Add(input);" looked better for me. Final thoughts: I could apply the strategy pattern to IMenu so that it encapsulates its behaviour if needed, but this project was to show manageable code, and I think that would make it more complicated and unnecessary :laugh: Thanks again!

                                      P A 2 Replies Last reply
                                      0
                                      • V venomation

                                        Thanks again "PIEBALDconsult" you have helped me allot ! I don't feel the need to show the code as its just minor changes but: 1 - I added a IMenu interface which can "Display" so that I can derive new menu's for other situations. 2 - Menu inherits IMenu and I replaced " Menu mainMenu = new Menu(personManager);" with " IMenu mainMenu = new Menu(personManager);" so that I can use different menu's. 3 - I decided to switch the List with an IList so that I can use the "AsReadOnly()" method as I don't need to modify the contents. 4 - For the "Add" method: "if (input != null) ManagedList.Add(input);" looked better for me. Final thoughts: I could apply the strategy pattern to IMenu so that it encapsulates its behaviour if needed, but this project was to show manageable code, and I think that would make it more complicated and unnecessary :laugh: Thanks again!

                                        P Online
                                        P Online
                                        PIEBALDconsult
                                        wrote on last edited by
                                        #37

                                        :thumbsup:

                                        1 Reply Last reply
                                        0
                                        • V venomation

                                          Thanks again "PIEBALDconsult" you have helped me allot ! I don't feel the need to show the code as its just minor changes but: 1 - I added a IMenu interface which can "Display" so that I can derive new menu's for other situations. 2 - Menu inherits IMenu and I replaced " Menu mainMenu = new Menu(personManager);" with " IMenu mainMenu = new Menu(personManager);" so that I can use different menu's. 3 - I decided to switch the List with an IList so that I can use the "AsReadOnly()" method as I don't need to modify the contents. 4 - For the "Add" method: "if (input != null) ManagedList.Add(input);" looked better for me. Final thoughts: I could apply the strategy pattern to IMenu so that it encapsulates its behaviour if needed, but this project was to show manageable code, and I think that would make it more complicated and unnecessary :laugh: Thanks again!

                                          A Offline
                                          A Offline
                                          Alaric_
                                          wrote on last edited by
                                          #38

                                          Just out of curiosity - Where do you attend and what level of student are you currently?

                                          "I need build Skynet. Plz send code"

                                          V 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups