From: "Molitor, Stephen L" Date: 2006-06-07T00:10:47+09:00 Subject: Re: Ruby and the Open-Closed Principle > Could be... but I guess I understood the essence of OCP to mean I > can't modify the original *behavior*. If I decide to change the > definition of Time.now, I haven't modified the original library > code, but I've changed the expected and well-documented behavior, > which pragmatically is all that really matters. > In other words, the "open" in OCP does seem to only talk about > extending classes; but in Ruby, since I can actually change behavior > in classes that would normally be "closed" in, say, C# or Java, then > it seems that the ability to open up an existing method and redefine > it is, essentially, not obeying the laws of OCP. Jeff, I would say that if in redefining a method you violate the original contract of the method, including any preconditions, post conditions, and class invariants, then you have violated the OCP. But if you're just extending the behavior of the method then you're OK. If the original unit tests for the class still pass, then assuming the tests are adequate then I would say you haven't violated OCP. To pick a simple example, if I redefine a method to add logging and still call the original method definition, then I have extended the method with extra behavior (logging) but I haven't changed or broken the original behavior. And the original unit tests should still pass. From this point of view the tests ensure the contract, not 'final' keywords or the like which are too coarse grained a mechanism as they restrict legitimate extensions in addition to prohibiting modifications. But of course we're not usually in the habit of running the original unit tests against redefined methods. In the absence of a run-time DBC mechanism a la Eiffel that might not be a bad idea though. Hmmm.... Now in white-box unit tests I often intentionally violate OCP. I would argue that redefining Time.now to return a configured time probably is violating OCP. But in unit tests I sometimes do want to change the behavior of classes not under test, to make things easier. Steve