user278618
user278618

Reputation: 20292

Have I good sense of static method

I have class Country which has collections of Cities.

At client I use webmethod

[WebMethod]
public void AddCity(string countryCode,string name)
{
MyFacade.AddCity(countryCode,name);
}

at Facade I have method

public void AddCity(string countryCode,string name)
{
Country.AddCity(countryCode,name); <-in this method is simple sql operation
}

and the core of my question:

public class Country
{
public static void AddCity(string countryCode, string cityName)
{
//insert into table cities new city
}
}

It's ok? Or I must create objectCountry, and there have non static method AddCity?

And another question:

Better use:

City[] cities=  Country.GetAllCities(countryCode)

or

City[] cities=  new Country(countryCode).GetAllCities()

Upvotes: 0

Views: 124

Answers (2)

Thomas James
Thomas James

Reputation: 511

Do you want to be able to unit test your code using a mocking framework?

Building on Ben's answer, replace the Facade with an interface:

[WebMethod]
public void AddCity(string countryCode, string name)
{
    ICountryDataAccess dao = GetDAOFromDI(); // basically get a DI framework to manage this object instance.
    dao.AddCity(countryCode, name);
}

public interface ICountryDataAccess 
{
    void AddCity(string countryCode, string name);
    ICollection<City> GetAllCities(string countryCode);
    // OR !
    Country Retrieve(string countryCode);
    // using an ORM or something Country then as a list of cities
}

public Country 
{
    public virtual string CountryCode {get;set;} 
    public virtual ICollection<City> Cities {get; protected set;}
}

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283921

Accepting both countryCode and cityName as parameters is fine for the data access layer, but I don't see any methods that should be static.

Rather AddCity should be a non-static member of DataConnection or some such, so that you can easily mock it, replace the database, etc. without changing the call interface.

Upvotes: 1

Related Questions