This is in the continuation of Small classes and methods, but code still difficult to maintain and follow as I have matured the problem and will rebound on people's answers.
Here are all the elements that should be modeled:
1.Model (in this case a link directory)
2.Validations (of the model fields from user submitted form)
3.Database CRUD operations of the model
I'm thinking of properly organizing all these elements into classes to respect the traditional principles of abstraction, loose coupling and encapsulation.
Here is how I did it currently, which is uncomfortable to maintain because of a loose coupling problem or so I think: when I must perform an operation, I see myself jumping around:
- Module 1:
- Link model class: with only data members
- Validation function that takes in all models data, and return either a bool if no error are found or a message back with all validation error. It does not contain the validation logic, which is contained in another module 4.
- Module 2: the controller file It grabs the CRUD http operations and send instructions to a utility service file that holds the database code that will perform the CRUD operations.
- Module 3: the database utility service file This takes the instructions sent by the model and perform the crud operations. It is un the form of a simple function.
- Module 4: the validation logic service The validation code in the model just send the data from the model to the validation logic service file here.
From the answers of gbjbaanb in the other thread, I think my problem is a coupling and encapsulation problem. he said:
you should be thinking in terms of making the entity self-contained, so you can think of making the entity and operating on it in much simpler terms, like creating it is one action, validating it another and so on
Which I think is a very important point. Thus I plan to remodel my structure as such:
Module 1:
- Link model class
- data members
- Create method
- Update Method
- Read Method
- Delete method
Module 2: the controller This will simply grab the http requests and instantiate corresponding model class method.
A question I have is, how to handle validation ? Logically I would put code in the model class as a method, since its coupled with model. But validation code is quite complex and is in own service file, so how to organize it, considering that validation could be reused by other classes ? The current way with validation function in model module, and logic in service file, is very unpractical.
As for the database code, I think I should leave it in it's own module, which would create a coupling between model and database class, but I think it's unavoidable as it will be used by other classes.
Also, if you have another suggestion to organise this, please advise. For example, would you put the crud operations in the model as I did, or in the database class ?