Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it better to test if a function is needed inside or outside of it?

what is the best practice? call a function then return if you test for something, or test for something then call?

i prefer the test inside of function because it makes an easier viewing of what functions are called.

for example:

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            this.FixURLCosmetics();
        }

and

private void FixURLCosmetics()
        {
            HttpContext context = HttpContext.Current;
            if (!context.Request.HttpMethod.ToString().Equals("GET", StringComparison.OrdinalIgnoreCase))
            {
                // if not a GET method cancel url cosmetics
                return;
            };

            string url = context.Request.RawUrl.ToString();
            bool doRedirect = false;

            // remove > default.aspx
            if (url.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase))
            {
                url = url.Substring(0, url.Length - 12);
                doRedirect = true;
            }

            // remove > www
            if (url.Contains("//www"))
            {
                url = url.Replace("//www", "//");
                doRedirect = true;
            }

            // redirect if necessary
            if (doRedirect)
            {
                context.Response.Redirect(url);
            }
        }

is this good:

if (!context.Request.HttpMethod.ToString().Equals("GET", StringComparison.OrdinalIgnoreCase))
            {
                // if not a GET method cancel url cosmetics
                return;
            };

or should that test be done in Application_BeginRequest?

what is better?

thnx

like image 562
b0x0rz Avatar asked May 31 '10 18:05

b0x0rz


1 Answers

I feel like testing inside the function is better. If you test outside of the function, you'll have to test everywhere that function could be called (and would cause a lot of duplicate code).

It's nicer to have everything in one place then spread out everywhere.

like image 170
Miles Avatar answered Oct 15 '22 03:10

Miles