vendredi 1 octobre 2021

What is the proper way to validate the respective local variables are assigned before executing a specific method in C#? [closed]

I have a Builder pattern as below

public class RequestBuilder
        {
            private string id;
            private JObject jsonBody;
            private string method;
            private HttpResponseMessage httpResponseMessage;

            public RequestBuilder Withid(string value)
            {
                id = value;              
                return this;
            }

            public RequestBuilder WithMethod(enumMethods value)
            {
                switch (value)
                {
                    case enumMethods.Method1:
                        method = "start";
                        break;
                    case enumMethods.Method2:
                        method = "stop";
                        break;                   
                    default:
                        method = string.Empty;
                        break;
                }
               
                return this;
            }

            public RequestBuilder WithPayload(JObject value)
            {
                jsonBody = value;               
                return this;
            }

            public async Task<HttpResponseMessage> ExecuteRequest()
            { 
                ValidateProperValues();              
                httpResponseMessage = await myService.SendCommand(id, method, jsonBody);
                return httpResponseMessage;
            }

            public void ValidateProperValues()
            {
                if(id == string.Empty)
                {
                    throw new Exception("id can't be empty");
                }
                if(method == string.Empty)
                {
                    throw new Exception("Method can't be empty");
                }
                if(jsonBody == null)
                {
                    throw new Exception("Json Body can't be null");
                }
            }
        }

Before executing the method ExecuteRequest(), the variables need to be assigned properly by other methods. If not I need to throw exception. I am doing this currently by having ValidateProperValues() method. Is there any other better way to handle this?

Aucun commentaire:

Enregistrer un commentaire