Separation of concerns is something that strikes at the heart of writing clean code. If you’re new to programming, this may be a new concept to you. It is a very important concept that you should learn from the beginning. The idea is actually quite simple: write code in a way that class or function focuses on its primary purpose. The concerns can be many different things, but normally they are the user interface, business logic, and data access.
If you’re just starting out with a language chances are you might just be doing good old console input and output. That still can provide separate concerns. Let’s say for example you are creating an application that has the following requirements:
- Create a hotel reservation application.
- The applicatipn gathers the following input: room price, number of rooms, number of nights, and taxes as percentage.
- The application provides a discount of 10% when 4 or more rooms are reserved.
- The application provides and additional 10% discount when the number of nights exceeds 3.
- Process the user input to compute and provide the following output:
- Number of Rooms
- Number of Nights
- Room Price
- Room Price after discounts:
- Sub total price before taxes
- Total price
- Validate all user input as follows
- room price must be between $1 and $500
- Number of rooms must be between 1 and 20
- Number of times must be between 1 and 10
- Taxes must be between 0 and 15%
This application has several concerns. First, it has user interface concerns – all input data must be gathered. Second, it has business logic – the data to be validated. If the data is valid then it must be processed to gather the calculated values. Finally, there are more user interface concerns in the form of output.
Here is the code. Study it and see what I mean by separating your concerns. You can do this even on a newbie app like this one.
Notice how, by separating your concerns, you can reuse code more effectively. Instead of tying the calculations with validation, we can re-use the validation logic. Similarly, we can re-use the user interface logic to gather the input.
Also, if you wrote unit tests against your business logic you would be able to test it easily.
Just read it and study it a bit. Perhaps it can be improved upon, but it’s a better start than mixing input and output with business logic.