News for hackers. Stuff that matters.
Re:Dependency Injection is a Virtue by alexatkeplar on Monday January 07, 2013 @05:20AM (#5020327)
Totally agree. The oddest thing is the example DHH picked and the language he used:

    > If your Java code has Date date = new Date(); buried in its guts, how do you
    > set it to a known value you can then compare against in your tests? Well, you
    > don't. So what you do instead is pass in the date as part of the parameters
    > to your method. You inject the dependency on Date. Yay, testable code!
It suggests that the whole of functional programming has completely passed him by. To re-write that paragraph:

If your Java function has Date date = new Date(); buried in its guts, then you have a side-effect which makes it much harder to reason about what that function is doing. Pass the date in as a function argument, and you now have (or are closer to having) a pure function: pure functions have no observable effect on the execution of your program, other than to compute a result given their inputs. A pure function like this is easier to reason about, easier to test, and easier to parallelize.

It just feels like DHH is fighting yesterday's battles. Dependency Injection in Java? David, the 1990s called and asked for their book on Spring back. Why can't we be comparing Ruby's approach to something like the cake pattern in Scala (http://jonasboner.com/2008/10/06/real-world-scala-dependency...), or even the pure keyword in Rust (http://static.rust-lang.org/doc/rust.html#pure-functions)?

If DHH spent some time building something with Clojure/Haskell/OCaml/Rust/Scala/F# and less time racing cars, he might come up with some interesting views again.

Re:Dependency Injection is a Virtue by mattmanser on Monday January 07, 2013 @06:22AM (#5020494)
Do you pass Random in? Or how about new file streams? Hell why should we even bother with local variables, lets just promote everything up the chain? Sure our method signatures would get longer and longer. We'd have to keep declaring variables again and again even though they're all used in one place.

There's a line where it gets absurd as it makes the code more complex. There's no good reason to be adding a date variable to your method signature just to make everything functional. Because you then have to declare and initialize that variable extra times.

That's the opposite of code reuse, that's bad programming. What happens when you need to refactor the method? What if the method call is in a different site to the date declaration? Why do that to yourself?

This hasn't got anything to do with functional programming. It's just simply about DRY and pointing out dogmatic coding approaches like DI being applied without actually understanding why you're doing it.

Re:Dependency Injection is a Virtue by lusr on Monday January 07, 2013 @07:07AM (#5020619)
Finally, somebody talking sense. You define a class to encapsulate rules (data, permissions) specific to a class of problems in your domain so that you don't have to repeat those rules elsewhere, which has all sorts of problems (the worst of which become impossible to address in some scenarios, e.g. where one executes potentially malicious code).

If you're passing in DateTime.Now to your Publish method then the caller (probably a UI element or a web callback) is implementing business logic that does not belong to it, which violates the single responsibility principle and will eventually cause your code to become unmaintainable.

Part of the problem with these posts is the authors seldom have experience building software in some of the more tricky real-world software development environments. While DHH is rightfully respected for many things, I can find nothing in his history [1] to suggest he has the relevant experience to criticise "enterprise development": as far as I can see, he's never had to work on a millions-of-lines code base with 3+ years of cruft written and maintained by large disparate teams of mediocre developers using poorly chosen technologies to solve problems within time, quality and scope constraints outside his control.

In these sorts of environments, saying "start over" or "choose better" is not an option and things like DI and well designed interfaces make it possible for a small team of architects to ensure the mediocre developers actually accomplish something and software gets released.

I'll repost what I posted yesterday on the other post:

    interface IArticleService {
       void Publish(int id);
    }
    
    class ArticleService : IArticleService {
       protected IArticleRepository ArticleRepository;
       protected ITimeService TimeService;
    
       public ArticleService(IArticleRepository articleRepository, ITimeService timeService) {
           ArticleRepository = articleRepository;
           TimeService = timeService;
       }

       public void Publish(int id) {
           ArticleRepository.Publish(id, TimeService.Now);
       }
    }
Some features of this design pattern:

- the consumer of the service doesn't need to know anything about the publish time: e.g. whether it's UTC or local time, whether it needs to have +1 second added to deal with a bug in some legacy interface, or perhaps a switch to database time, etc. The problem of "publish time" is strictly limited to the ArticleService, which is an expert on the matter of publish times.

- any new business rules regarding publish times or Publish-related activities are strictly limited to this service and none of the consumers have to be modified when the rules change

- the ArticleService is easily testable by swapping in one or more testing ITimeService implementations (e.g. one that returns a fixed test date time, one that returns bad times, etc.)

- your software has a consistent, single view of time (which is critical in a time dependent application, for example)

[1] http://en.wikipedia.org/wiki/David_Heinemeier_Hansson

Re:Dependency Injection is a Virtue by discreteevent on Monday January 07, 2013 @11:47AM (#5021833)
I agree with you and it reminds me of this thread on "State and Modularity":

http://lambda-the-ultimate.org/classic/message9361.html

In which Peter Van-Roy states that: "In our experience, true state (destructively assignable entities) is essential for reasons of program modularity (which for this discussion I take as meaning: the ability to change one part of a program in a significant way without changing the rest of the program). Threaded state, e.g., monads as used by Haskell or DCGs as used by Prolog, cannot substitute for it."

He goes on to give an example that is also published in CTM. The evidence in the example is conclusive in support of his statement (I think). By using a mutable variable he is able to have communication of information between two indirectly related modules in a system without modifying any existing interfaces.

In a functional program you would be required to redefine all the method signatures in the call stack between the two modules (or make everything monadic or pass around the state of the world which are both edging twoard defining a stateful language on top of your functional one). Anyway, the pure functional solution is not modular. But some functional programmers would argue that this is a good thing because in fact what Van-Roy is does in his example is to introduce a side-effect with all the downsides of that. The functional programmer would say that this mutation of a variable behind everyone's back is a kind of sneaky behaviour. It's action at a distance. The functional approach is more explicit and transparent. I don't think anyone who has spent a significant amount of time chasing down bugs would disagree with more transparency.

However I think that its a tradeoff myself. Its fine to think that we should make everything explicit but often it just isn't practical in large systems to have to change the whole call stack for a minor update. We often do want genuine modularity. In Van-Roys example (a call counter) its easy to verify that the change is harmless. That's the point I think. Some side effects are harmless - maybe we need to relax a bit. Or as another comment on the thread said, the main thing to remember is that "local state is nice; global state isn't." (which is what the author is arguing in "Dependency Injection is a Virtue")

Re:Dependency Injection is a Virtue by rapala on Monday January 07, 2013 @09:40AM (#5021121)
To me it seems that you (in your code example) have just split the function in two. Two thirds of the parameters are given to the constructor and the last one to the method. It might be what your application needs, but it seems arbitrary taken out of context.

In some other language one could implement this with a function returning a function and it would be about the same as declaring the fields in your example final:

  (defn publisher [repository clock]
    (fn [id]
      (publish repository id (now clock))))
Re:Dependency Injection is a Virtue by lusr on Monday January 07, 2013 @09:54AM (#5021191)
Your "function returning a function" is a closure, and yup the class's instance variables act much like a (mutable) closure here.

The clever bit is that the consumer (e.g. a web callback or UI event handler) of IArticleService is not the constructor of ArticleService. The consumer simply receives a reference to an IArticleService and uses it, while the constructor of the service knows how to wire things up and hand out service references to consumers that need it so that the consumers don't need to know how to do the wiring up; this is precisely what a dependency injection engine does.

It's the difference between you walking to a Post Office and saying "mail(this envelope)" and you saying "mail(this envelope, put it into truck x, route it via [A, B, C, D], find it in the corner of truck D weeks later and route it through E, give it to Alice to give to Bob to place it in the customer's post office box)". Somebody constructed the Post Office with all these rules encapsulated and you just consume the service.

It's the reason society can scale despite nobody knowing how everything works exactly, and the same principles apply to creating maintainable code that scales among many developers of varying degrees of skill.

Re:Dependency Injection is a Virtue by jurre on Monday January 07, 2013 @07:39AM (#5020683)
>as far as I can see, he's never had to work on a millions-of-lines code base with 3+ years of cruft written and maintained by large disparate teams of mediocre developers using poorly chosen technologies to solve problems within time, quality and scope constraints outside his control.

But he doesn't say that it's bad to use DI in those situations, does he? Just that it's probably a bad idea to do it when you're working on a ruby project.

Re:Dependency Injection is a Virtue by lusr on Monday January 07, 2013 @09:58AM (#5021211)
If you're building a simple system then it probably won't matter what you do. My opinion is it's good practice to follow sound architectural principles and just because your language lets you get away with crazy stuff doesn't necessarily mean it's the best choice. I listed a number of features of the approach I took - I'm not sure why I'd want to give all that up just to save a few lines of code.
Re:Dependency Injection is a Virtue by btilly on Monday January 07, 2013 @10:40AM (#5021449)
If you're building a simple system then it probably won't matter what you do.

Nothing could be farther from the truth.

When you're building simple systems you're up against hard limits for efficient team size - you need the system to remain simple. The reason is that a totally flat team structure only remains incredibly productive until you get to 5-8 people or so. Then you're stuck. Adding a person adds more communication overhead than useful work. Adding process makes everyone less efficient. The result is that you need to do both - and according to published literature don't get your old level of productivity back until your team has 20+ people on it.

Therefore the prime rule is to maximize efficiency. If you're going with the "small team of competent people" approach you can assume competence, but need to do what is efficient.

Efficiency here means long-run efficiency. This isn't just "throw together spaghetti and hope it works". This is throwing together stuff fast, and making it maintainable by a small team (partly through keeping it simple enough that people can hold program state in their heads).

I listed a number of features of the approach I took - I'm not sure why I'd want to give all that up just to save a few lines of code.

As long as the code is not crazy, lines of code is approximately the same as effort. Therefore adding lines of code reduces efficiency. You also added complexity - which gives more to think about during debugging which also reduces efficiency.

It is true that you gain a number of advantages. However the advantages you name fall under the YAGNIY principle. You Ain't Gonna Need It Yet. If you do need it, rewriting stuff to add that is likely to be a reasonable amount of work. In the meantime we save effort in writing, save effort in comprehending, and get to move on faster if we just leave it out.

Re:Dependency Injection is a Virtue by Peaker on Monday January 07, 2013 @06:46AM (#5020565)
Yes, you pass in Random, and file streams.

If you need to pass the same set of multiple things to multiple functions, you declare a type that represents all these arguments. At least this is the approach used in Haskell, with semi-explicit (explicit in type, implicit in the value) passing of parameters.

If you take a time argument, you have to declare an extra argument, not an extra variable, and in a powerful language, you can abstract its passing around.

If you move the method to a new location where its input is not available, you propagate up the input requirement in the form of argument passing, which conveys the new dependency up the call chain.

Re:Dependency Injection is a Virtue by adamauckland on Monday January 07, 2013 @07:33AM (#5020668)
> If you need to pass the same set of multiple things to multiple functions, you declare a type that represents all these arguments. At least this is the approach used in Haskell, with semi-explicit (explicit in type, implicit in the value) passing of parameters.

So might one call this a Context object?

Re:Dependency Injection is a Virtue by jerf on Monday January 07, 2013 @09:37AM (#5021108)
In Haskell, they call this a Reader. This parallels the Writer, which lets code just 'write' to the provided values but not use them (more useful than it sounds, for instance, logging). But it is basically a context value, yes.
Re:Dependency Injection is a Virtue by Peaker on Tuesday January 08, 2013 @06:06AM (#5025704)
Well, the nice thing about this abstraction in Haskell, is that you can give a name to the notion of receiving a bunch of values (Reader), outputting a bunch of values (Writer), threading state that can be both Read and Written (State), non-determinism (List), etc. You can thus compose all these behaviors you want into a single type constructor and build your programs as composites of this type.
Re:Dependency Injection is a Virtue by laureny on Monday January 07, 2013 @09:57AM (#5021206)
> There's a line where it gets absurd as it makes the code more complex. There's no good reason to be adding a date variable to your method signature just to make everything functional. Because you then have to declare and initialize that variable extra times.

Exactly, and that's why DI is useful: it forces you to make a distinction between dependencies and real parameters. You really want your method signature to only accept parameters that are going to change throughout the life of your application while being injected with the dependencies it needs. Something like:

    @Inject
    private Database db;
    
    public void updateName(String id, String name) {
      User u = db.find(id);
      u.setName(name);
      db.save(u);
    }
Your logic is now clearly separated from the dependencies and trivial to test.
Re:Dependency Injection is a Virtue by dgregd on Monday January 07, 2013 @06:46AM (#5020563)
Someone asked Java DI related question. All answers were dogmatic.

http://stackoverflow.com/questions/131975/what-are-the-benef...

I tend to think that sometimes guys choose (or are forced to choose) solutions like configuration xml files over source code files just to keep quiet all these inquisitors.

Re:Dependency Injection is a Virtue by flyinRyan on Wednesday January 09, 2013 @09:08AM (#5031506)
I didn't see any concise answers there so I'll say why I use this a lot at work:

- If I use Spring.Net I never have to put stupid trace logging on any functions but I get it for free. I make one change in the XML config files and suddenly every function for every inject object has full tracing turned on.

- Getting new code installed into production is a huge drama/pain but changing a config file doesn't have the same level of bureaucracy.

Re:Dependency Injection is a Virtue by martinced on Monday January 07, 2013 @09:03AM (#5020949)
Of COURSE you pass random in.

Or the seed + current value of the PRNG.

That's how companies like Blizzard do to reproduce any game state in games like Warcraft III. For example a replay file is tiny: the only thing that is saved are player inputs and the time at which they happened, as well as the seed to the PRNG.

You're likely confused because you think "random" means "true randomness" while typically we're using seeded PRNGs.

In addition to that, in language supporting high-order functions it's very common to pass a function to/from a function.

Passing in a PRNG function and the current value the PRNG is at is a very good way to get a 100% deterministic function inside a functional programming language.

Stop spreading FUD about FP.

Re:Dependency Injection is a Virtue by brazzy on Monday January 07, 2013 @09:43AM (#5021134)
> David, the 1990s called and asked for their book on Spring back.

Psst... the first milestone release of Spring was in 2004.