496
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
this post was submitted on 08 Jul 2023
496 points (97.3% liked)
Programmer Humor
19623 readers
1 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
founded 1 year ago
MODERATORS
Btw. why don't interfaces work + "as argument" (whether it's a constructor in an OOP context or a function parameter)? I think interfaces are exactly built for such a use-case (without all the boilerplate that's necessary with dependency injection as well as factories).
What are you talking about? At least in Java and PHP you can absolutely declare constructor and function parameters as interfaces. As you say that's exactly what they're for.
Yeah that's my point, I don't see a use for factories here, because it's possible to just use generic parameters (whether it's constructors or function arguments).
I'm somewhat confused by your statements, so perhaps I don't understand.
Function/objects that allow changing their behavior by passing different objects into them, based on some interface, is called dependency injection. Some subset of behavior is determined by this passed behavior. E.g. To keep a logger class from having to understand how to write logs, you could create a WriteTo interface and various implementations like WriteToDatabase, WriteToFile, WriteToStdout, WriteToNull.
When you create this example logger, you'll need to make a choice of what object to pass when you write the code. e.g.
new Logger(new WriteToDatabase(config))
But maybe you don't want to make that decision yet -- you want to let a config file decide which writer(s) to create. The pattern to pick between dependencies at runtime is called a factory. In this case, you might make a WriterFactory to pick the right writer, or perhaps a LoggerFactory to hide the creation of both Writer and Factory objects.So, a factory is only really a facade to hide the runtime switching of how an object is created.
Also, the term dependency injection often gets confused with what you see in various Java / C# / and various frameworks in other languages -- those usually use what's called a "DI Container" or "IoC Container". These manage and facilitate how dependency injection happens within the project, often with various annotations (e.g.
@Autowired
). These containers are powerful, but sometimes complicated.However, you can absolutely still do DI without DI containers, and I think advocating for not using DI generally (and related patterns like factories) is rather misguided.