Gavin5511
Gavin5511

Reputation: 791

Where should i create my static methods?

I need to create the below static method. Does this need to be in a particular folder (App_Code or Models), or should i create a new folder for this? Is there a particular convention i should follow?

public static DbGeography CreatePoint(double lat, double lon, int srid = 4326)
{
    string wkt = String.Format("POINT({0} {1})", lon, lat);

    return DbGeography.PointFromText(wkt, srid);
}

Also, would i need to specify a new 'using' in my controller to call this?

Upvotes: 1

Views: 781

Answers (1)

Hywel Rees
Hywel Rees

Reputation: 914

Method placement

There are not really any hard and fast rules.

In your case, the code appears to be a type of helper method. On a small, single project application I'd be inclined to create a 'Helpers' folder, and create a static class there, containing methods like this.

You have a dependency on the PointFromText method in the DbGeography class, so this would also need to be moved.

Infact, PointFromText sounds like it performs the same task as CreatePoint, but taking a different input. It would make things cleaner to create an overload of CreatePoint

DbGeography CreatePoint(string wkt, int srid); 
DbGeography CreatePoint(double lat, double lon, int srid = 4326);

You can now call CreatePoint using either a latitude/longitude, or an appropriate string/srid.

Using Directive

The using directive will depend on the namespace that your static method resides in:

namespace Foo
{
    public static class HelperMethods
    {
        public static DbGeography CreatePoint(double lat, double lon, int srid = 4326)
        {
            string wkt = String.Format("POINT({0} {1})", lon, lat);

            return DbGeography.PointFromText(wkt, srid);
        }
    }
}

With the above example, in your calling code you will have a few options. You may

1) call the method directly:

Foo.HelperMethods.CreatePoint(51.5, 0.1);

2) Import the namespace with a using directive, and call the method:

using Foo;
...
HelperMethods.CreatePoint(51.5, 0.1);

3) Import the static class and access the methods directly:

using static Foo.HelperMethods;
...
CreatePoint(51.5, 0.1);

It's really down to your preference which approach you take, I'd probably go for the second option just to aid readability slightly.

Upvotes: 3

Related Questions