Where to put my Big Ole' Array
I have an array of states and abbreviations that I check when a user is performing a search. If the items is not in the array it moves on to using a geocoded service. I do the initial check currently in the controller and geocoding method is in the model.
My questions is where should I put this initial state check array? I feel like it bloats the controller or the model since it is many lines.
You could make a separate class for this. This makes for a good use case because you're really talking about a service of sorts and it's not really the responsibility of either the controller or the model. Maybe call it something like
class LookupService def call(query) if in_array?(query) # Return value from array else # Look up through geocoding service end end end
Thank you. I knew it didn't feel right in either or mixed between the two. The new service class feels much better!
Whenever you can, try to rely on abstraction. Separation of concerns and responsibilities is a good pattern to follow. Note, you can go a little crazy with this, but in general good abstraction is what you want to keep maintainable code.
Thanks James. I try to keep this in mind, almost like I have Sandy Metz looking over my shoulder. :P
However, I often find myself questioning when and where to abstract. How small is too small of an object, should I place this method in the model or is it better suited in the controller or.. do I make a new Class since it's "kind of" a service object. It's not so much when it's black and white but the grey area that I still struggle with.
I think like you said I should ask myself more often if I can separate the concerns and/or responsibilities. -Thanks
For sure! And Sandi Metz is a really good person to have looking over your shoulder. She's the queen of abstraction (among others).
I can tell you from my experience that I don't always abstract. When a class becomes > 200 LOC that's typically a sign for me to abstract. Personally, I try to put as many methods into a Model/Class that I can. In the beginning my controllers were out of control with some really complex methods. But after Chris showed me some basic refactoring and abstraction I learned to start pulling logic and complicated methods out of the controller and into classes or modules. It's made my life much easier.
There is no "hard and fast" rule on when to abstract. Really it's a gut feeling more than anything. If you think that small objects are fine in one class, then stick with it. If you feel that it's going to be hard to maintain, then abstract it. There's really not a right or wrong answer here, just general guidelines.
As you progress more you'll start to sniff the "code smells" and will figure out when it's best to separate. One thing that helps me is looking at older code I wrote and figuring out how I could abstract better. It helps when refactoring old code and makes me a better developer moving forward.
You got this! :P