router icon indicating copy to clipboard operation
router copied to clipboard

Named arguments vs immutable methods

Open xepozz opened this issue 2 years ago • 6 comments

What's the point to create an object every method calls?

Let's take a look at the Route class: image

The coolest thing is you can use auto-complete feature to call any of these methods. Is it all? I think so. Let's imagine an average corporate app with more than 100 routes. Every application bootstrap it create this 100+ routes. But if we count it comes to 100*3.5 created objects: 100 route * 3-4 immutable methods calls, so 350 created object every bootstrap just for the one matched route in the end. That's awful. If we open Route's constructor and let users create it instead we can decrease the created objects numbers back to 100.

class Route {
    public function __construct(
        private string $pattern,
        private array $methods,
        private string $name = null,
        private array $middlewares = [],
}

That's enough to gain performance easy.

So the way to use Route changes as the following:

Route::get('/')
  ->name('site/index')
  ->action([SiteController::index, 'index'])
  ->middlewares([AuthMiddleware::class])
;
new Route(
  pattern: '/',
  name: 'site/index',
  action: [SiteController::index, 'index'],
  middlewares: [AuthMiddleware::class],
);

All of these properties can be readonly, but it's better to later it for the next release. Also all these methods are questionable. Do we really need keep both named arguments and methods?

Due to this changes #179 turns to be real just by one line above the class #[\Attribute]

xepozz avatar Mar 14 '23 07:03 xepozz

Creating an object is quite cheap but the syntax change is to the worse in my opinion.

samdark avatar Mar 14 '23 08:03 samdark

Cheap costs are still greater than zero

xepozz avatar Mar 14 '23 08:03 xepozz

Need to measure these in order to make a decision about if it makes sense to change routing syntax.

samdark avatar Mar 14 '23 08:03 samdark

I like named arguments. More shortly, but without loss of readability.

vjik avatar Mar 14 '23 08:03 vjik

I think we should keep the current syntax.

With these changes, https://github.com/yiisoft/router/issues/179 becomes real just one line above the #[\Attribute] class

We can do it differently. I have an idea how to do it but still in my head 😄

rustamwin avatar Mar 15 '23 03:03 rustamwin

I told a few times long ago that Route should be just a dto, but now it's kind of god object and not the best one.

xepozz avatar Mar 16 '23 08:03 xepozz