Where to place regex functions in Laravel? - laravel

I have a lot of regex functions that validates the data.
They have a common domain. Where to place them, in service, helper wherelse?
As I know to place it in controller is not good idea, because it is not reusable.

Regex are more close to utility functions. In fact, utilities methods can be used anywhere depending upon the requirements. Therefor, these must be independent to any entity/models, controller or any class in Laravel.
Further, your question is closely connected with software engineering concept known as Coupling vs Cohesion
Coupling is defined as the degree of interdependence between the modules and Cohesion is defined as the degree of relationship between elements of the same module.
So a good software design says that there must always be low coupling and high cohesion.
Therefor, I believe if we create Regex utility module then it should work independently of any module/class/model/controller. They must have least dependency between each other to have low coupling as much as possible. Chances are higher that methods you define in Regex module will reuse across the other controllers/classes.
On the other hand, if you define Regex related methods inside controller or a model, then their inter module dependency will increase and chances are we will not be able to reuse these regex related methods anymore.
Therefor, a good idea is to isolate modules from each other that have no particular dependency and will reuse across the other modules.
In Laravel, we generally create Helper class/methods to achieve this. So you can defiantly go with Helper classes approach. Create a Regex Helper class and reuse it in whole application.
Cheers :)

Related

classes with CRUD methods violating Single Responsibility principle?

I am trying to understand single responsibility principle. I have following questions.
The Single Responsibility Principle (SRP) states that there should never be
more than one reason for a class to change.
Usually our Resource,Service and Repository classes have
create,read,update and delete method. We are changing each class to
modify code for any any of these operations. Is it violating SRP? Do we need
separate class for each action?
When I run sonar lint, I have seen below message.
Classes should not coupled to too many other classes.
Here I am injecting other classes using spring DI. Is there any limit on
number of dependencies?
I may be missing crux of this concept. Please suggest a good resource for understanding this concept better with examples
The SRP states that the class should only do one thing, like persisting entities in the case of repositories. I guess that you've confused "class" and "object" here: if you have several methods that could change the object's state this could be in accordance with the SRP. However the only reason for a repository class to change should have something to do with its purpose, namely persisting or retrieving entities in this case.
The Wikipedia article about the Single Responsibility Principle puts it very well.
To your second point: there is no such thing as a maximum number of dependencies a class can have, but it could be a sign for a design weakness if there are many of them.
The Single Responsibility Principle (SRP) states that there should
never be more than one reason for a class to change.
The Single Responsibility principle doesn't mean a single method or a single type of action by component/class.
It means a single responsibility in the scope of a matter.
Persistence operations makes part of the same matter.
So putting all of them in a single class doesn't violate necessary the principle.
Now if you have dozen and dozen of specific database operations, it would make sense to divide them into distinct classes having a well defined responsibility such as selecting operations, updating operations, and so for.
Usually our Resource,Service and Repository classes have
create,read,update and delete method. We are changing each class to
modify code for any any of these operations. Is it violating SRP?
These are distinct layers.
If you change the model of a layer, others are very often impacted as data passes between layers.
It is like if you add an information in your database, you necessary need to change your GUIs and your processing if you want see/manipulate them.
Now if you change implementation of layers, other layers should have no or very few consequences.

Multiple Controllers appropriate with one entity in spring framework

I'm starting to develop website that use the spring framework.I have three controller.There are newCustomerController,editCustomerController and deleteCustomerController.These controllers are mapped with view that use for create update and delete, but I create only customer.
So, I would like to know.Is it appropriate to declare the controllers like this.
Thank
The answer to this question is subjective and maybe more a topic for https://softwareengineering.stackexchange.com/. However, there is something very spring related about it that I would like to comment.
There are a few principles that attempt at guiding developers of how to strike a good balance when thinking about designing the classes. One of those is the Single responsibility principle.
In object-oriented programming, the single responsibility principle
states that every class should have a single responsibility, and that
responsibility should be entirely encapsulated by the class. All its
services should be narrowly aligned with that responsibility
A catchier explanation is
A class or module should have one, and only one, reason to change.
However, its still often hard to reason about it properly.
Nevertheless, Spring gives you means for it (think of this statement as a poetic freedom of interpretation). Embrace constructor based dependency injection. There are quite a few reasons why you should consider constructor based dependency injection, but the part relevent to your question is adressed in the quote from the blog
An often faced argument I get is: “Constructors just get too verbose
if I have 6 or 7 dependencies. With fields only, this is fine”.
Awesome, you’ve effectively worked around a clear indicator that the
code you write is doing way too much. An increase in the number of
dependencies a type has should hurt, as it makes you think about
whether you should split up the component into multiple ones.
In other words, if you stick to constructor based injection, and your constructor turns a bit ugly, the class is most likely doing too much and you should consider redesigning.
The same works the other way around, if your operations are a part of the logical whole (like CRUD operations), and they use the same dependencies (now "measurable" by the count and the type of the injected deps) with no clear ideas of what can cause the operations to evolve independently of each other, than no reason to split to separate classes/components.
It should be better if you define one controller for Customer class and in that class you should have all methods related to customer operations (edit,delete,create and read).

Using an object oriented approach in Ruby

I have two classes, Class A and Class B.
I've recently noticed that they share a lot of the same code. For example:
def viewable_by?(user)
super || clinic.has_staff_member?(user) || user.system_admin? || self.person == user.person
end
I want to minimize the code duplicated between the classes. But in refactoring, I've found that much of it doesn't fit neatly into one class that falls cleanly in the Single Responsibility Principle. I want to put it all into a single module, but the methods will have to do with time formatting, viewing permissions, and a few other things.
As I see it, I have a few choices. (And I bet you can suggest others.) From an object oriented point of view, which approach should I go with and why?
Use one single module shared between both of the classes. It may
not have a specific single responsibility, but it does clean up the
code significantly, and keeps it all in one place.
Make tiny classes and mix in to both classes as modules. They
will all have a single responsibility, but there will be many of
them, some of which may only have one method. Seems like a waste.
Perhaps use a presenter for things like time formatting, and a
permissions module shared between both classes. Perhaps "cleaner,"
but methods are going to be everywhere.
Another possibility I haven't yet considered?
EDIT
This question had previously mentioned Clinic::Appointment and Clinic::Visit classes, rather than A and B. Answers may refer to appointments and visits.
This is a neat question because it deals in a great way with the overall strucuture of your project. I understand that Appointment and Visit are separated things, and an Visit don't need to be linked to an Appointment.
For authorization methods, like viewable_by?, I recommend move all authorizations to other place - you might want to check the cancan structure, that have worked well for many Rails projects, and most likely will work well for any application, even coding an authorization system yourself. So in part, my answer for you is to use (3).
However, since not all code that is shared by the two classes are for authorization purposes, I would try to classify a set of methods, and give an answer for each class of methods you could think of. For method classes that have a similar behavior I would try to encapsulate in a module and include it (so just like (1), but in smaller parts). For example one module HasVisitors with methods like got_on_time? and was_conclusive? (well, maybe not the best examples, but you get it). When your model has a broader scope, like Authorization, that is present in most of your classes, then it is time to go to (3).
I suggest you stop and think again if you should have a Visit class apart from Appointment and it relationship, but not now. After got at home, have fun, take it off from your head, then think again next day.
Would the design be clearer if you shifted the responsibilities? e.g. user.can_view?(resource)

How to identify necessary classes and modules of Ruby software?

Say I am writing a Ruby gem. I want to design classes and modules going to be used.
How to identify them?
Where do I need classes and where do I need modules?
Your question is about one of the main design feature of the Ruby language.
Basically, you can see module as collection of tools, and class as collection of objects which are able to mix with those tools.
Ruby faq says about modules :
Modules are collections of methods and constants. They cannot generate instances.
When you want to provide something, you'll need a class. You can do a MyClass.new, you cannot with a module : MyModule.new won't work.
On the other hand :
Classes may generate instances (objects), and have per-instance state (instance variables).
When you want to provide a way of doing something, you'll a need a module. You can do a MyModule.doSomething(SomeParams). You can also do that with a class methods, but you won't be able to do some mix-in with it.
See this faq for a more detailed answer.
This is a object oriented design task, if you are really new to that I would recommend to study a book like Head First Object-Oriented Analysis and Design. I usually try to identify the core actors/concepts in the business model to discover which classes I need.
A basic rule is to use classes when you need to maintain some states, and modules when there is no need of maintaining states. Ruby has several uses for modules Ruby, there are several articles about this topic in the Practicing Ruby blog: part 1, part 2, part 3, part 4
I use to think of Modules stricly as as behaviour capsules and Classes as state and behaviour capsules (from encapsulation).
So, if you want to encapsulate a behaviour use a module. Otherwise use a class.

What are your best practices when using an MVC-based web framework?

A few general questions to those who are well-versed in developing web-based applications.
Question 1:
How do you avoid the problem of "dependency carrying"? From what I understand, the first point of object retrieval should happen in your controller's action method. From there, you can use a variety of models, classes, services, and components that can require certain objects.
How do you avoid the need to pass an object to another just because an object it uses requires it? I'd like to avoid going to the database/cache to get the data again, but I also don't want to create functions that require a ton of parameters. Should the controller action be the place where you create every object that you'll eventually need for the request?
Question 2:
What data do you store in the session? My understanding is that you should generally only store things like user id, email address, name, and access permissions.
What if you have data that needs to be analyzed for every request when a user is logged in? Should you store the entire user object in the cache versus the session?
Question 3:
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model? What are the advantages to this approach?
Question 4:
If your site is driven by a user id, how do you unit test your code base? Is this why you should have all of your data-retrieval methods in a centralized place so you can override it in your unit tests?
Question 5:
Generally speaking, do you unit test your controllers? I have heard many say that it's a difficult and even a bad practice. What is your opinion of it? What exactly do you test within your controllers?
Any other tidbits of information that you'd like to share regarding best practices are welcome! I'm always willing to learn more.
How do you avoid the problem of "dependency carrying"?
Good object oriented design of a BaseController SuperClass can handle a lot of the heavy lifting of instantiating commonly used objects etc. Usage of Composite types to share data across calls is a not so uncommon practice. E.g. creating some Context Object unique to your application within the Controller to share information among processes isn't a terrible idea.
What data do you store in the session?
As few things as is humanly possible.
If there is some data intensive operation which requires a lot of overhead to process AND it's required quite often by the application, it is a suitable candidate for session storage. And yes, storage of information such as User Id and other personalization information is not a bad practice for session state. Generally though the usage of cookies is the preferred method for personalization. Always remember though to never, ever, trust the content of cookies e.g. properly validate what's read before trusting it.
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model?
I prefer to use the Repository pattern for my models. The model itself usually contains simple business rule validations etc while the Repository hits a Business Object for results and transformations/manipulations. There are a lot of Patterns and ORM tools out in the market and this is a heavily debated topic so it sometimes just comes down to familiarity with tools etc...
What are the advantages to this approach?
The advantage I see with the Repository Pattern is the dumber your models are, the easier they are to modify. If they are representatives of a Business Object (such as a web service or data table), changes to those underlying objects is sufficiently abstracted from the presentation logic that is my MVC application. If I implement all the logic to load the model within the model itself, I am kind of violating a separation of concerns pattern. Again though, this is all very subjective.
If your site is driven by a user id, how do you unit test your code base?
It is highly advised to use Dependency Injection whenever possible in code. Some IoC Containers take care of this rather efficiently and once understood greatly improve your overall architecture and design. That being said, the user context itself should be implemented via some form of known interface that can then be "mocked" in your application. You can then, in your test harness, mock any user you wish and all dependent objects won't know the difference because they will be simply looking at an interface.
Generally speaking, do you unit test your controllers?
Absolutely. Since controllers are expected to return known content-types, with the proper testing tools we can use practices to mock the HttpContext information, call the Action Method and view the results to see they match our expectations. Sometimes this results in looking only for HTTP status codes when the result is some massive HTML document, but in the cases of a JSON response we can readily see that the action method is returning all scenario's information as expected
What exactly do you test within your controllers?
Any and all publicly declared members of your controller should be tested thoroughly.
Long question, longer answer. Hope this helps anyone and please just take this all as my own opinion. A lot of these questions are religious debates and you're always safe just practicing proper Object Oriented Design, SOLID, Interface Programming, DRY etc...
Regarding dependency explosion, the book Dependency Injection in .NET (which is excellent) explains that too many dependencies reveals that your controller is taking on too much responsibility, i.e. is violating the single responsibility principle. Some of that responsibility should be abstracted behind aggregates that perform multiple operations.
Basically, your controller should be dumb. If it needs that many dependencies to do its job, it's doing too much! It should just take user input (e.g. URLs, query strings, or POST data) and pass along that data, in the appropriate format, to your service layer.
Example, drawn from the book
We start with an OrderService with dependencies on OrderRepository, IMessageService, IBillingSystem, IInventoryManagement, and ILocationService. It's not a controller, but the same principle applies.
We notice that ILocationService and IInventoryManagement are both really implementation details of an order fulfillment algorithm (use the location service to find the closest warehouse, then manage its inventory). So we abstract them into IOrderFulfillment, and a concrete implementation LocationOrderFulfillment that uses IInventoryManagement and ILocationService. This is cool, because we have hidden some details away from our OrderService and furthermore brought to light an important domain concept: order fulfillment. We could implement this domain concept in a non-location-based way now, without having to change OrderService, since it only depends on the interface.
Next we notice that IMessageService, IBillingSystem, and our new IOrderFulfillment abstractions are all really used in the same way: they are notified about the order. So we create an INotificationService, and make MessageNotification a concrete implementation of both INotificationService and IMessageService. Similarly for BillingNotification and OrderFulfillmentNotification.
Now here's the trick: we create a new CompositeNotificationService, which derives from INotificationService and delegates to various "child" INotificationService instances. The concrete instance we use to solve our original problem will delegate in particular to MessageNotification, BillingNotification, and OrderFulfillmentNotification. But if we wish to notify more systems, we don' have to go edit our controller: we just have to implement our particular CompositeNotificationService differently.
Our OrderService now depends only on OrderRepository and INotificationService, which is much more reasonable! It has two constructor parameters instead of 5, and most importantly, it takes on almost no responsibility for figuring out what to do.

Resources