Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to create separate service class for one function in java

I have person class and then class like

Countries 
Languages

I have separate classes for countries and langauages. I need to display all counries in drop down and all languagaes. So do I need to create a CountryService class and a languagaeService class? With functions like getLanguages and getCountries in there?

Looking for a good solution.


2 Answers

The answer depends on the growth path you expect for this code base.

If you don't see much else being added to a CountryService or LanguageService class besides the functions you mention, then adding 2 new classes may be over-engineering the solution. In this case it may be better to do something more along the lines of adding a static method getLanguages to the Language class, and getCountries to the Country class

If you see your self expanding the role and functionality a CountryService and a LanguageService class then this approach would be fine.

like image 127
Tom Neyland Avatar answered Dec 12 '25 01:12

Tom Neyland


Your solution isn't wrong, but generally methods like getAvailableCountries() and getAvailableLanguages() are declared as static methods in their respective classes. That way, you can use them like this:

List<Country> lc = Country.getAvailableCountries();
List<Language> ll = Language.getAvailableLanguages();

Are you saving these objects in a database? In that case, I would use either of the following designs:

  • The object is responsible for saving itself:

    new Country("United States").save();
    new Language("English").save();
    
  • The class is responsible for saving the object:

    Country.save(new Country("United States"));
    Language.save(new Language("English"));
    
like image 45
Matheus Moreira Avatar answered Dec 12 '25 02:12

Matheus Moreira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!