Architecture of a class, and best practice? [closed]











up vote
0
down vote

favorite












So I am in charge of creating a project that has to do with calculations of pay. One aspect of the project is to analyze a proper input such as 4:00 PM, and other aspects including calculating the pay for the hours put in, and the type of job etc.



my question more so has to do with the best practices for designing the classes around this.



Should I have one class that analyzes the input string, and only does that? and one class for the calculator to display the proper output or should it all be in one class?



both ways are fine for me to do, but what is considered professional?



is it best practice to split classes based on their unique functionality even if you dedicate a class to simply one method?










share|improve this question













closed as primarily opinion-based by dasblinkenlight, Tim Castelijns, Emmanuel Rosa, rkosegi, JJJ Nov 7 at 11:41


Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.















  • Unrelated to your question, but since you mention analyzes the input string I would recommend forcing the user to insert it in a specific format if you aren't already. If it's up to the user to decide they'll use 4:00 16:00 4.00pm 4pm and whatever else users do, which will cause plenty of headaches when trying to process that.
    – Mark
    Nov 7 at 9:26












  • You should always validate user input as soon as possible, and probably convert it to a proper representation. For instance, if the user inputs a local date, it should be parsed and converted to a LocalDate. Actual calculations should be separated from parsing and validating user input.
    – MC Emperor
    Nov 7 at 9:29






  • 1




    just as the lines of code, the number of methods a class contains is not relevant. It's about what the class is responsible for
    – Tim Castelijns
    Nov 7 at 9:29










  • There is imho no best practice (singular) for this. There are several ways to design software, each with their respective advantages and disadvantages. You may stick to one design pattern you consider good.
    – maio290
    Nov 7 at 9:31






  • 1




    Well, in the aspects of unit testing, Single Responsibility Principle sound reasonable since it allows you to detect the source of the error.
    – ozata
    Nov 7 at 9:44















up vote
0
down vote

favorite












So I am in charge of creating a project that has to do with calculations of pay. One aspect of the project is to analyze a proper input such as 4:00 PM, and other aspects including calculating the pay for the hours put in, and the type of job etc.



my question more so has to do with the best practices for designing the classes around this.



Should I have one class that analyzes the input string, and only does that? and one class for the calculator to display the proper output or should it all be in one class?



both ways are fine for me to do, but what is considered professional?



is it best practice to split classes based on their unique functionality even if you dedicate a class to simply one method?










share|improve this question













closed as primarily opinion-based by dasblinkenlight, Tim Castelijns, Emmanuel Rosa, rkosegi, JJJ Nov 7 at 11:41


Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.















  • Unrelated to your question, but since you mention analyzes the input string I would recommend forcing the user to insert it in a specific format if you aren't already. If it's up to the user to decide they'll use 4:00 16:00 4.00pm 4pm and whatever else users do, which will cause plenty of headaches when trying to process that.
    – Mark
    Nov 7 at 9:26












  • You should always validate user input as soon as possible, and probably convert it to a proper representation. For instance, if the user inputs a local date, it should be parsed and converted to a LocalDate. Actual calculations should be separated from parsing and validating user input.
    – MC Emperor
    Nov 7 at 9:29






  • 1




    just as the lines of code, the number of methods a class contains is not relevant. It's about what the class is responsible for
    – Tim Castelijns
    Nov 7 at 9:29










  • There is imho no best practice (singular) for this. There are several ways to design software, each with their respective advantages and disadvantages. You may stick to one design pattern you consider good.
    – maio290
    Nov 7 at 9:31






  • 1




    Well, in the aspects of unit testing, Single Responsibility Principle sound reasonable since it allows you to detect the source of the error.
    – ozata
    Nov 7 at 9:44













up vote
0
down vote

favorite









up vote
0
down vote

favorite











So I am in charge of creating a project that has to do with calculations of pay. One aspect of the project is to analyze a proper input such as 4:00 PM, and other aspects including calculating the pay for the hours put in, and the type of job etc.



my question more so has to do with the best practices for designing the classes around this.



Should I have one class that analyzes the input string, and only does that? and one class for the calculator to display the proper output or should it all be in one class?



both ways are fine for me to do, but what is considered professional?



is it best practice to split classes based on their unique functionality even if you dedicate a class to simply one method?










share|improve this question













So I am in charge of creating a project that has to do with calculations of pay. One aspect of the project is to analyze a proper input such as 4:00 PM, and other aspects including calculating the pay for the hours put in, and the type of job etc.



my question more so has to do with the best practices for designing the classes around this.



Should I have one class that analyzes the input string, and only does that? and one class for the calculator to display the proper output or should it all be in one class?



both ways are fine for me to do, but what is considered professional?



is it best practice to split classes based on their unique functionality even if you dedicate a class to simply one method?







java






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 7 at 9:23









fsdff

32019




32019




closed as primarily opinion-based by dasblinkenlight, Tim Castelijns, Emmanuel Rosa, rkosegi, JJJ Nov 7 at 11:41


Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.






closed as primarily opinion-based by dasblinkenlight, Tim Castelijns, Emmanuel Rosa, rkosegi, JJJ Nov 7 at 11:41


Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.














  • Unrelated to your question, but since you mention analyzes the input string I would recommend forcing the user to insert it in a specific format if you aren't already. If it's up to the user to decide they'll use 4:00 16:00 4.00pm 4pm and whatever else users do, which will cause plenty of headaches when trying to process that.
    – Mark
    Nov 7 at 9:26












  • You should always validate user input as soon as possible, and probably convert it to a proper representation. For instance, if the user inputs a local date, it should be parsed and converted to a LocalDate. Actual calculations should be separated from parsing and validating user input.
    – MC Emperor
    Nov 7 at 9:29






  • 1




    just as the lines of code, the number of methods a class contains is not relevant. It's about what the class is responsible for
    – Tim Castelijns
    Nov 7 at 9:29










  • There is imho no best practice (singular) for this. There are several ways to design software, each with their respective advantages and disadvantages. You may stick to one design pattern you consider good.
    – maio290
    Nov 7 at 9:31






  • 1




    Well, in the aspects of unit testing, Single Responsibility Principle sound reasonable since it allows you to detect the source of the error.
    – ozata
    Nov 7 at 9:44


















  • Unrelated to your question, but since you mention analyzes the input string I would recommend forcing the user to insert it in a specific format if you aren't already. If it's up to the user to decide they'll use 4:00 16:00 4.00pm 4pm and whatever else users do, which will cause plenty of headaches when trying to process that.
    – Mark
    Nov 7 at 9:26












  • You should always validate user input as soon as possible, and probably convert it to a proper representation. For instance, if the user inputs a local date, it should be parsed and converted to a LocalDate. Actual calculations should be separated from parsing and validating user input.
    – MC Emperor
    Nov 7 at 9:29






  • 1




    just as the lines of code, the number of methods a class contains is not relevant. It's about what the class is responsible for
    – Tim Castelijns
    Nov 7 at 9:29










  • There is imho no best practice (singular) for this. There are several ways to design software, each with their respective advantages and disadvantages. You may stick to one design pattern you consider good.
    – maio290
    Nov 7 at 9:31






  • 1




    Well, in the aspects of unit testing, Single Responsibility Principle sound reasonable since it allows you to detect the source of the error.
    – ozata
    Nov 7 at 9:44
















Unrelated to your question, but since you mention analyzes the input string I would recommend forcing the user to insert it in a specific format if you aren't already. If it's up to the user to decide they'll use 4:00 16:00 4.00pm 4pm and whatever else users do, which will cause plenty of headaches when trying to process that.
– Mark
Nov 7 at 9:26






Unrelated to your question, but since you mention analyzes the input string I would recommend forcing the user to insert it in a specific format if you aren't already. If it's up to the user to decide they'll use 4:00 16:00 4.00pm 4pm and whatever else users do, which will cause plenty of headaches when trying to process that.
– Mark
Nov 7 at 9:26














You should always validate user input as soon as possible, and probably convert it to a proper representation. For instance, if the user inputs a local date, it should be parsed and converted to a LocalDate. Actual calculations should be separated from parsing and validating user input.
– MC Emperor
Nov 7 at 9:29




You should always validate user input as soon as possible, and probably convert it to a proper representation. For instance, if the user inputs a local date, it should be parsed and converted to a LocalDate. Actual calculations should be separated from parsing and validating user input.
– MC Emperor
Nov 7 at 9:29




1




1




just as the lines of code, the number of methods a class contains is not relevant. It's about what the class is responsible for
– Tim Castelijns
Nov 7 at 9:29




just as the lines of code, the number of methods a class contains is not relevant. It's about what the class is responsible for
– Tim Castelijns
Nov 7 at 9:29












There is imho no best practice (singular) for this. There are several ways to design software, each with their respective advantages and disadvantages. You may stick to one design pattern you consider good.
– maio290
Nov 7 at 9:31




There is imho no best practice (singular) for this. There are several ways to design software, each with their respective advantages and disadvantages. You may stick to one design pattern you consider good.
– maio290
Nov 7 at 9:31




1




1




Well, in the aspects of unit testing, Single Responsibility Principle sound reasonable since it allows you to detect the source of the error.
– ozata
Nov 7 at 9:44




Well, in the aspects of unit testing, Single Responsibility Principle sound reasonable since it allows you to detect the source of the error.
– ozata
Nov 7 at 9:44












2 Answers
2






active

oldest

votes

















up vote
1
down vote













At the boundary of your application you'll be accepting requests through a user interface or a system interface. You should treat anything originating from outside your application as untrusted and potentially wrong. For example, if you receive a HTTP request there is no guarantee that it is valid and contains the fields you expect. If you read form a file, it might be incorrectly formatted.



There should be a layer at the boundary of your application which takes input (which is just a bunch of bytes in the end) and turns it into a representation as Java objects of the suitable type (e.g. Boolean, LocalDate). If everything is a String, you are probably doing it wrong.. If this layer is unable to do this, it should send back an error.



Once you have expressed the request as a correctly typed Java objects, your business logic should process the request. This makes it possible to use the same logic when data is provided through a different interface, separates plumbing (parsing) from business logic (calculations). It allows the business logic to be more easily unit tested.



When you output a response back to the user (or system), you should convert from your nicely structured Java objects back to the output representation at the last moment.






share|improve this answer




























    up vote
    0
    down vote













    I suggest you take a look at the javax.validation package and the Bean Validation JSR's 1.0 and 2.0



    Using this approach you can create Java classes to represent your data and annotate them with the required validations. Triggering the validation to happen depends a little bit on the context.



    In a Spring Boot application putting @Valid on the received controller parameter does the trick. See also this cheat sheet:



      import javax.validation.Valid;
    import com.company.app.model.Article;

    @Controller
    public class ArticleController {

    ...

    @RequestMapping(value="/postArticle", method=RequestMethod.POST)
    public @ResponseBody String postArticle(@Valid Article article, BindingResult result, HttpServletResponse response){

    if(result.hasErrors()){
    String errorMessage = "";
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    List<ObjectError> errors = result.getAllErrors();

    for( ObjectError e : errors){
    errorMessage+= "ERROR: " + e.getDefaultMessage();
    }
    return errorMessage;
    }

    else{
    return "Validation Successful";
    }
    }
    }


    In a standalone application it could be done like this:



    public class BeanValidationExample {
    public static void main (String args) {
    Configuration<?> config = Validation.byDefaultProvider()
    .configure();
    ValidatorFactory factory = config.buildValidatorFactory();
    Validator validator = factory.getValidator();
    factory.close();

    Person person = new Person();
    person.setDateOfBirth(new Date(System.currentTimeMillis() + 10000));

    Set<ConstraintViolation<Person>> violations = validator.validate(person);
    violations.forEach(v -> System.out.println(v.getPropertyPath() +
    "- " + v.getMessage()));
    }
    }





    share|improve this answer




























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote













      At the boundary of your application you'll be accepting requests through a user interface or a system interface. You should treat anything originating from outside your application as untrusted and potentially wrong. For example, if you receive a HTTP request there is no guarantee that it is valid and contains the fields you expect. If you read form a file, it might be incorrectly formatted.



      There should be a layer at the boundary of your application which takes input (which is just a bunch of bytes in the end) and turns it into a representation as Java objects of the suitable type (e.g. Boolean, LocalDate). If everything is a String, you are probably doing it wrong.. If this layer is unable to do this, it should send back an error.



      Once you have expressed the request as a correctly typed Java objects, your business logic should process the request. This makes it possible to use the same logic when data is provided through a different interface, separates plumbing (parsing) from business logic (calculations). It allows the business logic to be more easily unit tested.



      When you output a response back to the user (or system), you should convert from your nicely structured Java objects back to the output representation at the last moment.






      share|improve this answer

























        up vote
        1
        down vote













        At the boundary of your application you'll be accepting requests through a user interface or a system interface. You should treat anything originating from outside your application as untrusted and potentially wrong. For example, if you receive a HTTP request there is no guarantee that it is valid and contains the fields you expect. If you read form a file, it might be incorrectly formatted.



        There should be a layer at the boundary of your application which takes input (which is just a bunch of bytes in the end) and turns it into a representation as Java objects of the suitable type (e.g. Boolean, LocalDate). If everything is a String, you are probably doing it wrong.. If this layer is unable to do this, it should send back an error.



        Once you have expressed the request as a correctly typed Java objects, your business logic should process the request. This makes it possible to use the same logic when data is provided through a different interface, separates plumbing (parsing) from business logic (calculations). It allows the business logic to be more easily unit tested.



        When you output a response back to the user (or system), you should convert from your nicely structured Java objects back to the output representation at the last moment.






        share|improve this answer























          up vote
          1
          down vote










          up vote
          1
          down vote









          At the boundary of your application you'll be accepting requests through a user interface or a system interface. You should treat anything originating from outside your application as untrusted and potentially wrong. For example, if you receive a HTTP request there is no guarantee that it is valid and contains the fields you expect. If you read form a file, it might be incorrectly formatted.



          There should be a layer at the boundary of your application which takes input (which is just a bunch of bytes in the end) and turns it into a representation as Java objects of the suitable type (e.g. Boolean, LocalDate). If everything is a String, you are probably doing it wrong.. If this layer is unable to do this, it should send back an error.



          Once you have expressed the request as a correctly typed Java objects, your business logic should process the request. This makes it possible to use the same logic when data is provided through a different interface, separates plumbing (parsing) from business logic (calculations). It allows the business logic to be more easily unit tested.



          When you output a response back to the user (or system), you should convert from your nicely structured Java objects back to the output representation at the last moment.






          share|improve this answer












          At the boundary of your application you'll be accepting requests through a user interface or a system interface. You should treat anything originating from outside your application as untrusted and potentially wrong. For example, if you receive a HTTP request there is no guarantee that it is valid and contains the fields you expect. If you read form a file, it might be incorrectly formatted.



          There should be a layer at the boundary of your application which takes input (which is just a bunch of bytes in the end) and turns it into a representation as Java objects of the suitable type (e.g. Boolean, LocalDate). If everything is a String, you are probably doing it wrong.. If this layer is unable to do this, it should send back an error.



          Once you have expressed the request as a correctly typed Java objects, your business logic should process the request. This makes it possible to use the same logic when data is provided through a different interface, separates plumbing (parsing) from business logic (calculations). It allows the business logic to be more easily unit tested.



          When you output a response back to the user (or system), you should convert from your nicely structured Java objects back to the output representation at the last moment.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 7 at 9:45









          WW.

          17.4k1274107




          17.4k1274107
























              up vote
              0
              down vote













              I suggest you take a look at the javax.validation package and the Bean Validation JSR's 1.0 and 2.0



              Using this approach you can create Java classes to represent your data and annotate them with the required validations. Triggering the validation to happen depends a little bit on the context.



              In a Spring Boot application putting @Valid on the received controller parameter does the trick. See also this cheat sheet:



                import javax.validation.Valid;
              import com.company.app.model.Article;

              @Controller
              public class ArticleController {

              ...

              @RequestMapping(value="/postArticle", method=RequestMethod.POST)
              public @ResponseBody String postArticle(@Valid Article article, BindingResult result, HttpServletResponse response){

              if(result.hasErrors()){
              String errorMessage = "";
              response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
              List<ObjectError> errors = result.getAllErrors();

              for( ObjectError e : errors){
              errorMessage+= "ERROR: " + e.getDefaultMessage();
              }
              return errorMessage;
              }

              else{
              return "Validation Successful";
              }
              }
              }


              In a standalone application it could be done like this:



              public class BeanValidationExample {
              public static void main (String args) {
              Configuration<?> config = Validation.byDefaultProvider()
              .configure();
              ValidatorFactory factory = config.buildValidatorFactory();
              Validator validator = factory.getValidator();
              factory.close();

              Person person = new Person();
              person.setDateOfBirth(new Date(System.currentTimeMillis() + 10000));

              Set<ConstraintViolation<Person>> violations = validator.validate(person);
              violations.forEach(v -> System.out.println(v.getPropertyPath() +
              "- " + v.getMessage()));
              }
              }





              share|improve this answer

























                up vote
                0
                down vote













                I suggest you take a look at the javax.validation package and the Bean Validation JSR's 1.0 and 2.0



                Using this approach you can create Java classes to represent your data and annotate them with the required validations. Triggering the validation to happen depends a little bit on the context.



                In a Spring Boot application putting @Valid on the received controller parameter does the trick. See also this cheat sheet:



                  import javax.validation.Valid;
                import com.company.app.model.Article;

                @Controller
                public class ArticleController {

                ...

                @RequestMapping(value="/postArticle", method=RequestMethod.POST)
                public @ResponseBody String postArticle(@Valid Article article, BindingResult result, HttpServletResponse response){

                if(result.hasErrors()){
                String errorMessage = "";
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                List<ObjectError> errors = result.getAllErrors();

                for( ObjectError e : errors){
                errorMessage+= "ERROR: " + e.getDefaultMessage();
                }
                return errorMessage;
                }

                else{
                return "Validation Successful";
                }
                }
                }


                In a standalone application it could be done like this:



                public class BeanValidationExample {
                public static void main (String args) {
                Configuration<?> config = Validation.byDefaultProvider()
                .configure();
                ValidatorFactory factory = config.buildValidatorFactory();
                Validator validator = factory.getValidator();
                factory.close();

                Person person = new Person();
                person.setDateOfBirth(new Date(System.currentTimeMillis() + 10000));

                Set<ConstraintViolation<Person>> violations = validator.validate(person);
                violations.forEach(v -> System.out.println(v.getPropertyPath() +
                "- " + v.getMessage()));
                }
                }





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  I suggest you take a look at the javax.validation package and the Bean Validation JSR's 1.0 and 2.0



                  Using this approach you can create Java classes to represent your data and annotate them with the required validations. Triggering the validation to happen depends a little bit on the context.



                  In a Spring Boot application putting @Valid on the received controller parameter does the trick. See also this cheat sheet:



                    import javax.validation.Valid;
                  import com.company.app.model.Article;

                  @Controller
                  public class ArticleController {

                  ...

                  @RequestMapping(value="/postArticle", method=RequestMethod.POST)
                  public @ResponseBody String postArticle(@Valid Article article, BindingResult result, HttpServletResponse response){

                  if(result.hasErrors()){
                  String errorMessage = "";
                  response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                  List<ObjectError> errors = result.getAllErrors();

                  for( ObjectError e : errors){
                  errorMessage+= "ERROR: " + e.getDefaultMessage();
                  }
                  return errorMessage;
                  }

                  else{
                  return "Validation Successful";
                  }
                  }
                  }


                  In a standalone application it could be done like this:



                  public class BeanValidationExample {
                  public static void main (String args) {
                  Configuration<?> config = Validation.byDefaultProvider()
                  .configure();
                  ValidatorFactory factory = config.buildValidatorFactory();
                  Validator validator = factory.getValidator();
                  factory.close();

                  Person person = new Person();
                  person.setDateOfBirth(new Date(System.currentTimeMillis() + 10000));

                  Set<ConstraintViolation<Person>> violations = validator.validate(person);
                  violations.forEach(v -> System.out.println(v.getPropertyPath() +
                  "- " + v.getMessage()));
                  }
                  }





                  share|improve this answer












                  I suggest you take a look at the javax.validation package and the Bean Validation JSR's 1.0 and 2.0



                  Using this approach you can create Java classes to represent your data and annotate them with the required validations. Triggering the validation to happen depends a little bit on the context.



                  In a Spring Boot application putting @Valid on the received controller parameter does the trick. See also this cheat sheet:



                    import javax.validation.Valid;
                  import com.company.app.model.Article;

                  @Controller
                  public class ArticleController {

                  ...

                  @RequestMapping(value="/postArticle", method=RequestMethod.POST)
                  public @ResponseBody String postArticle(@Valid Article article, BindingResult result, HttpServletResponse response){

                  if(result.hasErrors()){
                  String errorMessage = "";
                  response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                  List<ObjectError> errors = result.getAllErrors();

                  for( ObjectError e : errors){
                  errorMessage+= "ERROR: " + e.getDefaultMessage();
                  }
                  return errorMessage;
                  }

                  else{
                  return "Validation Successful";
                  }
                  }
                  }


                  In a standalone application it could be done like this:



                  public class BeanValidationExample {
                  public static void main (String args) {
                  Configuration<?> config = Validation.byDefaultProvider()
                  .configure();
                  ValidatorFactory factory = config.buildValidatorFactory();
                  Validator validator = factory.getValidator();
                  factory.close();

                  Person person = new Person();
                  person.setDateOfBirth(new Date(System.currentTimeMillis() + 10000));

                  Set<ConstraintViolation<Person>> violations = validator.validate(person);
                  violations.forEach(v -> System.out.println(v.getPropertyPath() +
                  "- " + v.getMessage()));
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 7 at 9:43









                  Adriaan Koster

                  12.3k33046




                  12.3k33046















                      這個網誌中的熱門文章

                      Academy of Television Arts & Sciences

                      L'Équipe

                      1995 France bombings