jeudi 18 juillet 2019

Elegant design for returning error codes C#

I have this piece of code which initializes a hardware device. When i call the initialize method, I am doing checking for each dll call method, whether it returns an error so that I can know which particular dll call causes the error.

Here is the initialize code.

public class Hardware {
        int e;
        int f;

    public int Initialize()
    {
            int a = 0;
            int b = 0;
            int c = 0;
            int d = 0;



            try
            {
                if (MyClass.InitDevice())

                {

                    e = MyClass.DoSomething();

                    if (e >= 0)
                    {

                        if (MyClass.DoSomething1(0, e) < 0)
                            return 6;

                        if (MyCLass.DoSomething2(ref a, ref b, ref c, ref d, e) < 0)
                        return 5;

                        f = 0;
                        if (!DoSomething3(false))
                            return 4;

                    }
                    else
                        return 3;
                }
                else
                    return 2;
            }
            catch
            {
                return 1;
            }

            return 0;
        }

MyClass wraps the dll methods InitDevice, DoSomething1, DoSomething2, DoSomething3 etc.

Eg.

public MyClass
    public bool InitDevices()
    {
        return StaticClass.InitDevices(); // InitDevices is the actual dll method call
    }

The code seems to be quite complicated with the nested if's. Is there a cleaner way to go about achieving it ? The return codes are basically error codes to indicate what point of failure happened in the hardware class.

What would be a good software engineering practice to reduce code ?

Aucun commentaire:

Enregistrer un commentaire