Domanda

I am working inside a public BLL with a number of different static methods. Inside a few of these methods, I need to display a certain string to the user depending on an ID# passed into the method. The situation is identical across these few methods. It's currently like this:

public class myBLL
{
    public static addByID(int ID)
    {
        string myString = grabString(ID);
        //do some stuff
        Console.Writeline("You have added: " + myString);
    }

    public static removeByID(int ID)
    {
        string myString = grabString(ID);
        //do some other stuff
        Console.WriteLine("You have removed: " + myString);
    }

    public static grabString(int ID)
    {
        if(ID == 1)
            return "string 1";
        else
            return "string 2";
     }
}

I feel like I am violating DRY in myMethod1 and myMethod2 because why bother calling grabString twice? However I cannot come up with a way around this.

È stato utile?

Soluzione 2

It's a bit hard to evaluate what you really are looking for. But might I suggest some sort of logger? Or maybe a general class that store the value for later use?

public class myBLL
{
    public static addByID(int ID)
    {
        //do some stuff
        LogString("You have added: {0}", ID);
    }

    public static removeByID(int ID)
    {
        //do some other stuff
        LogString("You have removed: {0}", ID);
    }

    public static LogString(string message, int ID)
    {
        string myString = "";

        if(ID == 1)
            myString = "string 1";
        else
            myString = "string 2";

        Console.WriteLine(string.Format(message, myString);
     }
}

To be honest, I would remove those static function and create a proper class.

public class MyObject
{
    int ID;

    public GetString()
    {
        if(ID == 1)
            return "string 1";
        else
            return "string 2";
     }

}

That way, the string could even be cached.

Altri suggerimenti

What about to use delegate for different parts of methods

public static void myGeneralMethod(int ID, Action<string> method )
{
    string myString = grabString(ID);
    method(myString);
    Console.WriteLine(myString);
}

public static void SomeStuffForAdd(string myString)
{

}
public static void SomeOtherStuffRemove(string myString)
{

}

Or if you want to keep Add/Remove:

public static void removeByID(int ID)
{
   myGeneralMethod(ID, SomeStuff);
} 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top