Encapsulation is the act of protecting data integrity. A class is properly encapsulated when its internal data cannot possibly be set to an invalid or inconsistent state. This can be achieved by: 1) Information hiding: removes the class's internals from the eyes of its clients so that there is less risk of corrupting of corrupting those internals. 2) Bundling of data and operations: helps establish a single entry point for all actions to be done on this class. This way you can perform all required validation and integrity checks before modifying this class. Each class has a number of invariants, these are conditions that must be true at all times. It is the responsibility of the software developer that these invariants are never violated and the best way to do that is to encapsulate your classes so that this is never an option. Example: the set method of the invariants are marked as private so only the class may set it. In this a course cannot be active if the nu...
The whole point of Encapsulation and Separation of concerns is to reduce complexity The more coupling leads to an exponential growth of complexity With separation of concerns we can maintain the same number of elements but reduce the coupling or connections between them. Public setters in domain classes is a red flag. Setters prevent the class from maintaining invariants because this class has no control over how its clients use those setters. Always make property setters in domain classes private by default. Proper way to set up many-to-one relationships with EF Core with private constructor and reference to a the FavouriteCourse model: And with the mappings: The query to select the join: To reduce complexity and bugs, always load all entities whether they are required or not. This is called Eager loading of relationships. To add Lazy Loading, you need to add the following Avoid the use of explicit lazy loaders such as this...
Exceptions should represent a defect in the codebase. If we throw exceptions for validations then it is not part of the method signature and is hidden. Example of code that comprises readability by throwing exceptions for validations: Should be written like this without exceptions, return a non empty string: Exceptions are for use cases you didn't take into account. It is not exceptional for users to enter invalid data. Example: In this example, the validation of UpdateName is essentially part of the public contract, its preconditions. This is acceptable, as for this to be thrown, some mistake must have been made in the domain logic for a null value in name to reach that part of the code. Hides potential issues. The best way to handle unexpected situations is to let the code fail. Example: this may be an exceptional situation for the repository, but it doesn't have to be for your codebase. Catch a specific exception and return false to fail gra...
Comments
Post a Comment