Search code examples
phplaravellaravel-6

The primary danger of facades is class scope creep [Laravel]


I came through this phrase, while reading about Laravel Facades The primary danger of facades is class scope creep. It is the second paragraph and here is the link https://laravel.com/docs/6.x/facades#when-to-use-facades

What class scope creep means?

I could not find any resource to understand class scope creep.


Solution

  • The answer to your question is actually given on the next sentence, however, I'd admit that I'd have been very confused when beginning in Laravel. So basically:

    Since facades are so easy to use and do not require injection, it can be easy to let your classes continue to grow and use many facades in a single class.

    What this means is that using facades (not only in Laravel but in general) too much could make your code more bloated and harder to read. (defeating the main point behind why you SHOULD use a facade)

    Facades can also grow to do many things beyond their original purpose, as refactoring guru (no affiliation) put it, facades - when used incorrectly - can turn into god objects.

    if you're going to use facades and you're still unclear about how to use them, I suggest reading up on the Single-Responsibility principle and (opinion ahead) when in doubt, don't use facades.

    Example

    This part is literally a "don't do this" guide, for the fast readers of SO, DON'T do these!

    I've edited my answer to include a rather ridiculous example of facade overuse in two different ways.

    1. You realize that facades really deal with the pain of the dependency injection pattern, who wants to worry about all the stuff with scopes and statics and traits? So you start using facades for everything. Need to add a where to a previous query? Simple! Make a facade for it and call it Scope::where($model, $column, $equals), wanna talk to the database but DB::query is just getting too long? Facades got your back, put them in a DataModel::longQuery() and use them everywhere. Tired of calling ProductResource::collection all the time? Put it in a new facade called Resource::collection($model).

    2. You have added a facade that helps you with generating payment links so you call it Payment and initially use it with Payment::generateLink(), after a while, you'll find out that you also need to generate views for an in-website payment widget, so you add a Payment::view(), and a few months down the road, when you need to talk to your payment provider about the history of your invoices, you just slap it onto the Payment::getReceipts method. Your payment facade is now a gigantic class that handles too many unrelated things in the same place.

    In both examples, you can clearly see an overuse of the facades through common coding mistakes. Although my examples are a bit too exaggerated, I think it's easy to imagine how these things can happen in real life over the span of months.