Refactor Code

  • Gravatar
    Displaying Messages to the User

    by azamsharp on 5/3/2008 12:32:48 PM
  • Here I am referring to the messages that you want the user to see on the screen. What is the best way to display the message. Messages like "Customer added successfully","File has been updated" etc. Here is my few implementations.
  • private void AddCustomer(Customer customer)
    {
    string message;

    try
    {
    // add the customer
    }
    catch (Exception ex)
    {
    message = ex.Message;
    }

    lblMessage.Text = message;
    // OR
    SiteHelper.SetUIMessage(message);
    // OR from an xml file that is cached
    SiteHelper.SetUIMessage(UIMessages.INSERT_CUSTOMER_SUCCESSFULL_MESSAGE);

    }
  • Refactor it!
  • Gravatar
    i guess it depends upon need. quickest 1 would be first solution but not flexible lblMessage.Text = message; , better OOP approach would be 2nd SiteHelper.SetUIMessage(message); but i think best practice would be if messages would be bring from some sort of resource file like last 1. SiteHelper.SetUIMessage(UIMessages.INSERT_CUSTOMER_SUCCESSFULL_MESSAGE);
    by MuhammadAdnan on 5/3/2008 1:41:47 PM
  • private void AddCustomer(Customer customer)
    {
    string message;

    try
    {
    // add the customer
    }
    catch (Exception ex)
    {
    message = ex.Message;
    }

    // xml file that is cached
    SiteHelper.SetUIMessage(UIMessages.INSERT_CUSTOMER_SUCCESSFULL_MESSAGE);

    }
  • Gravatar
    When using the last technique then we have to be very careful because if the XML file is very very large then it will be better to the records in the database instead of load them up in the memory.
    by azamsharp on 5/3/2008 2:58:16 PM
  • Gravatar
    Static Classes are a code smell. How are you supposed to isolate this code an create a unit test for it? Better to use dependency injection and instance variables for that sort of thing...
    by subdigital on 5/5/2008 7:30:20 AM
  • private void AddCustomer(Customer customer)
    {
    try {
    //add the customer
    _siteHelper.SetUIMessage(INSERT_CUSTOMER_SUCCESS
    } catch(Exception ex) {
    _siteHelper.SetUIMessage(INSERT_CUSTOMER_ERROR);
    }
    }
  • Gravatar
    Hi Ben, The SiteHelper is regular class (instance class) with the method SetUIMessage a static method.
    by azamsharp on 5/5/2008 9:51:46 AM
  • public class SiteHelper
    {
    public static string Foo()
    {
    return "foo";
    }
    }

    [TestFixture]
    public class TestSiteHelper
    {
    public void should_return_foo_when_Foo_method_is_invoked()
    {
    Assert.AreEqual("foo",SiteHelper.Foo());
    }
    }
Please log in to refactor the code! Login