by shortrounddev2 · 3y ago · 0 comments
app.handleGet("/route/goes/here", (req, res) => {
});
Which seems like it's useful for making really quick and dirty micro-services (nano-services, even), but I still vastly prefer the more declarative and modular schemes of bootstrap or asp.net: // Middleware automatically routes "/Foo" to FooController
[Controller]
public class FooController : Controller
{
private IMyService _service { get; init; }
// Declarative dependency injection
FooController(IMyService service)
{
this._service = service;
}
// HTTP Method and Route are declarative
[HttpGet("/")]
public ActionResult GetBar([FromBody] Model myModel)
// ^ automatic user input validation using reflection
{
this._service.create(myModel); // or whatever you need to do
return Ok();
}
}
This has always seemed way more maintainable to me. Even microsoft has added the ability to do these quick and dirty HTTP routing methods along with top level statements.Many people (myself included) hate decorators. Keep my code declarative and free of black magic, please. This pattern also conflates class structure with route structure. What if I wanted to assign a method in this class to another base route? You end up with routing strewn all over the application.
Sure there is. It's metaprogramming. Anyone in the world who can read code can understand this immediately:
app.get('/', (req, res) => {
res.send('hello world')
})
Throw decorators in the mix, and now I need to learn exactly what this specific environment is doing with those annotations. I have absolutely no way of understanding it at a glance. And you're now also stuck with vendor lockin to whatever framework/compiler was using them, and your code can no longer be fully isolated and unit tested without the framework.> And you're now also stuck with vendor lockin to whatever framework/compiler was using them
I don't understand. If you choose a web framework, you are locked in to developing things in that framework from now on. In what world do companies try to change web frameworks without having to change any of the underlying code? In what world would they want to do so?
I don't know why, but I truly do not like this. So if I create a "HelloController" class does the middleware just start automatically routing "/hello" to it?
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
https://learn.microsoft.com/en-us/aspnet/core/mvc/controller...If you don't call one of the MapController methods, requests will not be routed to controllers even if they exist in the same project.
The second example has poor readability. And that's even before we get to the issue that this approach has fallen out of favor exactly because it result in code that can be a pain in the neck to figure out.
Please don't do this. This is the kind of legacy approach that I try to teach people working for me NOT to follow.
Only if you don't know C# or asp.net (or bootstrap). In which case: why would you be working for an organization which does?
> And that's even before we get to the issue that this approach has fallen out of favor exactly because it result in code that can be a pain in the neck to figure out.
This kind of structured approach has fallen out of favor because it's become more popular to hire javascript and react developers straight out of boot camp who have only been taught how to code one or two things.
The argument that code needs to be inherently readable to someone with 3 weeks of experience is how you get hundreds of poorly written spaghetti code microservices written in node or typescript and not a language better suited for backend development. If you want your code base to constantly look like it was written by someone following their first javascript tutorial, then by all means continue using this top-level express JS crap
> Please don't do this. This is the kind of legacy approach that I try to teach people working for me NOT to follow.
You are setting yourself up for some bad tech debt in the future
You've never taken a job working in a language you don't know yet? Anecdotally this is a common thing. In fact, my most recent job hired me to write C# with nothing but prior Go/Python experience.
> This kind of structured approach has fallen out of favor because it's become more popular to hire javascript and react developers straight out of boot camp who have only been taught how to code one or two things.
This comes across to me as needlessly bitter to folks with less experience than you.
So then it shouldn't be a problem for you to learn a new skill based on a very common pattern with many examples in different languages
> This comes across to me as needlessly bitter to folks with less experience than you.
If those folks are forcing the business to make tech decisions based on their lack of experience, it makes life harder for others. If you are going to choose between "should we write our backend in C# or javascript", and the decision comes down to "well our bootcamp grads don't know C# and they don't have a background in software engineering, so getting them up to speed on C# will take months", then you're willingly choosing inferior tech to make up for subpar employees
IMO it makes it much easier to get an overview of the overall functionality of the app, and to find the code which implements each route. It's also a lot more flexible if you ever need to support routes which do not fit the conventional pattern of the framework (perhaps for legacy reasons).
You can of course still use dependency injection, etc with this central route registration model.
So what you are saying is that the IoC / Decorator approach is the way to avoid spaghetti code? That's an interesting assertion.
> You are setting yourself up for some bad tech debt in the future
You mean like being saddled with a product that depends on a large framework that fewer and fewer people want to deal with?
The way to avoid tech debt is to retain plasticity, keep more options open and not paint yourself into a corner where your choice of framework dictates how you structure entire systems.
And, of course, to hire people based on talent and ability rather than a line on their CV that promises experience with a given framework.
You're also doing more in your second example. You can still do service injection in JavaScript.
1. Uses declarative routing, which looks better and makes more sense than running a function to handle routing (e.g, you read it as "There is a handler named GetFoo living within the Foo controller that exists at the base route"). Declaration is more important to the end user than implementation when creating an interface. It also allows you to export these classes to a different Main method which can generate documentation for you without having to even run the HTTP server (the declarations can be picked up using RTTI and not actually having the runtime server activated). You can also add named parameters to the routes and then add them to the body of the handler with their proper types, e.g:
[HttpGet("/{id}")]
public ActionResult GetFoo(int id)
And that input validation is handled automatically. Named parameters exist on a lot of these frameworks as well, but Javascript doesn't provide static typing so it's not a good language for writing a backend in2. Handles input validation under the hood or through middleware so you don't have to manage it in the controller body
3. Can also handle user auth under the hood using attributes so you don't have to handle it in the controller body
4. Uses middleware to handle routing in a predictable way (e.g: the name of the controller is the name of the route by default)
5. Uses class-based controllers to encapsulate the services available to the controller through the constructor, and also helps pair a single model to a single controller for making really simple RESTful interfaces
You can also define a custom controller interface or abstract class which provides a bunch of default functionality that you commonly re-use (e.g: ApiController with some built in response wrappers/handlers for error codes, etc.)
God the number of bugs and bad practices I've had to deal with and work around do to auto-magic casting of url segments, or JSON blobs into language native types, is too damn high. Auto input validation based on function parameter types sounds good, until you think about for more than a couple of seconds and start to realise type primitives definitions vary significantly between languages. Using them for input validation just means exporting your languages type primitives into your API, with zero consideration of if that's a good idea.
The classic example of this is people using the `int` type for `id`s just because the IDs happen to contain only digits. Ignoring the fact that identifiers aren't numbers (performing numeric operations on them doesn't make any sense), but because you've now blindly exported the `int` type into your API, you also export nastiness like precision (try preserving leading zeros with your `int` type) and rollovers into your API. Two things that make zero sense when dealing with identifiers, and two things that often change depending on the exact platform your software is running on.
I'd really encourage you to explore other languages. If you're one of those "JavaScript is bad" people, there's plenty of others: Go, Ruby, Python... I'm surprised to be seeing this kind of comment on Hacker News to be honest.
I know that angular is really good at this, but I'm not sure what pure js frameworks would allow a service to be defined as an interface first, and then injected into the constructor of a controller (or even a handler function) based on the implementation method selected somewhere else. I just haven't seen it happen.
app.MapGet("/", async (
[FromBody] User user,
[FromServices] MyService service) =>
{
await service.Handle(user);
return Results.Ok();
});I also dislike functions and controllers without explicitly defined return types.
Then you add an extensions method for WebApplication that registers all of your route groups when configuring your app pipeline. Each time you create a new route group, you add that group to your WebApplication extension method and it's wired up.
It's a little extra work up-front when you're first creating your app, but it also results in a clearer structure for how routes are defined once the app grows into the size you're describing.
Even .NET is moving towards your first example by providing minimal APIs that allow simple binding of a route to a handler function.
Thankfully it looks like even ASP.NET Core is no longer using this kind of syntax. https://learn.microsoft.com/en-us/aspnet/core/fundamentals/r...