---
title: "Extract And Override Focus"
url: "https://courses.osherove.com/courses/legacy-code-hero/extract-and-override-focus.md"
canonical: "https://courses.osherove.com/courses/legacy-code-hero/extract-and-override-focus/"
tags: []
author: "Roy Osherove"
description: "Lesson 4 of 5 in Legacy Code Hero (Refactoring), 21:17. Free video by Roy Osherove."
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# Extract And Override Focus

1. [Courses](https://courses.osherove.com/#courses)
2. [Legacy Code Hero](https://courses.osherove.com/courses/legacy-code-hero/)
3. Refactoring

Lesson 4 of 5

Duration: 21:17 [Watch on YouTube](https://www.youtube.com/watch?v=JIPB3peXJSA)

In this video Roy Shows how to use, slowly, the [Extract and Override technique](https://osherove.com/blog/2005/6/16/mock-objects-vs-quotinherit-amp-overridequot.html "Mock Objects vs. \"Inherit & Override\" (osherove.com)").

## In this lesson

Roy Osherove applies [extract and override](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-3#ch03lev1sec5 "Variations on refactoring techniques (The Art of Unit Testing, 2nd ed., ch. 3)") to a login manager that calls a static logger: the call moves into a protected virtual method with as little logic as possible, which a [testable subclass](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_95 "Partial mocks (The Art of Unit Testing, 3rd ed., ch. 4)") overrides to save the message for the test to check. He extends the example to a logger that throws an exception, a call to a static web service and the machine name, then shows extract and override returning [fake](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec2 "The difference between mocks and stubs (The Art of Unit Testing, 2nd ed., ch. 4)") objects. He also answers a question on whether extracted methods should be protected or public.

## Transcript

2,922 words

[\[00:16\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=16s) Now what we're going to do is we're going to take a look at another technique and it's called [extract and override](https://osherove.com/blog/2012/5/16/test-driven-validation-logic-with-extract-override.html "Test Driven Validation Logic with Extract & Override (osherove.com)"). And this technique is something that I I first learned about this in the book called [working effectively with legacy code](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-12#sigil_toc_id_226 "Read Michael Feathers’ book on legacy code (The Art of Unit Testing, 3rd ed., ch. 12)"). And now we're kind of jumping into the realm of what happens when you have code that is not very testable and you don't want to use one of the profilerbased frameworks to test it. Okay. How do you refactor the code to be more testable?

[\[00:48\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=48s) So here we have the example of login manager with statics. Now the problem here is that I want to test that static logger.Write gets called but I don't have a way to inject the dependency into this. So what I'm going to do is I'm going to refactor the code to make it more testable without changing the functionality. So refactoring the definition is changing code without changing functionality. So making it more testable, more readable, maintainable as long as it does exactly the same as it did before.

[\[01:22\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=82s) Nothing more, nothing less. So extract and override is built on top of the idea that you can create a a function, make it virtual, then you can override it by inheriting from the class in your tests. So instead of checking that stat static logger.Write got called, I can do the next best thing. I can extract a method from this control alt m let's call it call logger

[\[01:57\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=117s) In the method I'm going to make it protected and virtual it cannot be static that way I can override it in my derived classes in my tests and another another important part is that I want want the method to be to have as less logic as possible. It has to be a simple and stupid method because if it has any logic including the string here in my test, I'm going to be overwriting this method. So there is no way for me to check that the logic inside it is correct.

[\[02:32\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=152s) So I'm going to get everything the method needs as a parameter. Ctrl P to extract the parameter. Let's call it text. And now up here we have the method. This is an earlier version of the same method. So we have this and we have call logger and they're connected to each other. So instead of checking that call logger the static logger got called I can check the next best thing that call logger got called and I assume that if this got called then static logger itself got called.

[\[03:09\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=189s) That's the next best thing. So the way I [break the dependency](https://osherove.com/blog/2005/8/23/issues-in-breaking-dependencies-for-unit-testing.html "Issues in breaking dependencies for unit testing (osherove.com)") is by creating another layer of indirection in my application. Now in my code I can inherit from the class. So I can create what's called a testable login manager.

[\[03:39\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=219s) I like the word testable in the beginning because it tells me that this is not a regular [fake](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-5#ch05lev1sec2 "Dynamically creating a fake object (The Art of Unit Testing, 2nd ed., ch. 5)") class. This is a version of the real class that I'm testing, but it's a more testable version. And in this testable version, I've broken the dependency to make it more testable. So instead of login manager with statics, this is a testable login manager with statics.

[\[04:10\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=250s) I'm just going to change all these change all testable login manager to this. So my test looks like this. In the testable login manager I override the call logger but nothing else. That means that instead of a fake class I actually have just a fake method inside the real class. Everything else around this method behaves just the way it did. But this method itself isn't really calling the static logger. It's just saving the value

[\[04:43\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=283s) Just like we do with every other just like we do with every every other fake class. In this case, it's just a fake method. We save the last log message as a public field. Testable login man me manager with statics. I then create it in my test. Instead of the real class, I create the testable class. I call as login. Okay. And then I use string assert to prove that the lm.last message

[\[05:15\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=315s) Contains what I'm expecting. And this is the basic idea of extracting override. I can take this a bit further. And you'll see just how powerful this idea really is. First of all, it doesn't force me to introduce a new interface into the system. So it has very little impact and also I can I can break with it almost anything. Let's say that I wanted to prove that not only logger gets called but in a separate requirement I would have if call if the logger throws an exception I wanted to catch it and call the static web service.

[\[05:59\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=359s) Okay. So I can take the static web service and I can prove this was called just like I did before. Extract call web service but this time instead of getting the logger exception I don't I don't want to have this logic inside. So let me just make this protected virtual

[\[06:30\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=390s) And instead what I'm going to do is I'm going to expect this whole thing as a parameter because if I expect this as a separate parameter and this is a se separate parameter the plus here is actually a piece of logic. I won't have any test to prove that I'm connecting these two things. So instead I'll extract both of these as the expected message. And I don't need the logger exception anymore like this. So now this method is again pretty stupid

[\[07:03\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=423s) And all the logic of connecting the message in the current environment machining is in the call to the web service. So now if I wanted to I could have a test that uses testable login manager. So this time if I wanted to simulate an exception, I could put another field public exception to throw equals null.

[\[07:34\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=454s) And now I could say something as simple as if to throw is not null then throw whatever it is you need. And now I need to also override the other method call web service and not call the base because then I wouldn't have done anything. I didn't break anything. But here I can just save to let's say last web service

[\[08:09\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=489s) Message equals text. Let's make this field. Make it public. That's all I'm doing. And I'm going to assert that the text here is going to be saved to to be saved. So if I write this as a new test, I can say is login. Okay. But the logger throws an exception

[\[08:39\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=519s) Then it calls the calls the web service with message and machine name. Okay. So now again I will use the testable login manager with statics and I will say lm to throw equals

[\[09:09\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=549s) Exception or whatever I want to simulate. Dude, this is totally a fake section. Then I would still do the same thing is login okay with something and pass

[\[09:48\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=588s) Dude. This is complete a fake exception. We can also just contain the current machine name. This is where things begin to get interesting. I can use the current machine name, but I don't want to do this. Plus environment machine name. Why is this not a great idea? Hm. >> Okay. Well, u

[\[10:23\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=623s) The machine name will be different somewhere else and and yeah, exactly. The machine name is going to be different on every different machine. Now, that's not a bad idea per se, but the problem is that that means that this test is going to be a different test every time it runs on a different machine. And what we want from a [unit test](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_17 "Defining unit testing, step by step (The Art of Unit Testing, 3rd ed., ch. 1)") is consistency. So we want to control the machine name so that it always is the same. If you wanted to prove that we can that the machine name local is working etc.

[\[10:56\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=656s) We would use an [integration test](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_25 "Integration tests (The Art of Unit Testing, 3rd ed., ch. 1)"). But for now this is this is the beginning of our solution. We can choose that it contains but if we knew the machine name in the first place we wouldn't need to do this because this is logic inside my test and most likely I'm also repeating production code from here. So this is really important. This could be a big problem. If there is a bug here for example I'm missing space and it's also missing in my production code. I'll never find out because my test is also expecting no space.

[\[11:29\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=689s) So, I'd rather have fake exception on machine name. This is much better for me, more readable and expectable. How do I control the machine? Well, I go back to the login manager with statics and I I'll use extract and override again because environment domachine name machine name is just a static property.

[\[12:03\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=723s) A property is just a static method. So I can go ahead and extract that again. Extract to a method get machine name. I like methods better than properties. I don't know why. It just feels righter, more more more correct. And again, make it protected virtual. And now I can have full control of the machine name here in the testable version. I can override

[\[12:34\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=754s) Get machine name. Now I could say machine name, but that would be a problem. It would be a problem because the reader of my test is going to look and say blah blah blah blah on machine A. Where the hell did machine A come from? So in terms of [readability](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-9 "Readability (The Art of Unit Testing, 3rd ed., ch. 9)"), it's going to look like a magic string. And I want my test to be fully readable. So I don't want my testable and fake classes to have this kind of logic inside them because it hurts readability and I don't want the reader of my test to look in two places to understand what's going on.

[\[13:13\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=793s) So instead I will tell it to return machine name. So my test is going to say this lm dot machine name equals machine name. Let's make it play field. That's it. I'm not even going to use a property again because a field is simpler than a property in my tests.

[\[13:46\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=826s) So now I can read the test. I can see machine name here and I can see it here. I can see this here and I can see this here and I can fully understand this and I don't have a problem with the the fact that I'm repeating myself in this test because I'd rather repeat myself than hurt the [trust](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-7#sigil_toc_id_134 "How to know you trust a test (The Art of Unit Testing, 3rd ed., ch. 7)") of creating something dynamically that I assert against. I don't want I'd rather not have bugs and this is not a big maintainability issue and it definitely helps to breability. So, as we've seen, extract and override is really powerful and it's actually very simple to do.

[\[14:22\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=862s) You just have to get used to doing this. Now, most of the frameworks out there support extract and override. As we've seen, I have an example here with [mock](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_76 "Interaction testing, mocks, and stubs (The Art of Unit Testing, 3rd ed., ch. 4)"). If you had such a thing with mock, you could do mock of let's say login manager with virtual method and lm.protected because it method is not public. setup write to log to to accept this and then gets called but we can also say dot

[\[14:54\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=894s) What was it we can also tell it to return various things sorry doesn't really matter how to do it right now the the the the the important thing is that this API exists in all of the frameworks so if you wanted to you can use the framework to do it if the method that you we extracted we would make it public then it would work just the same as any other method that we can override. Okay. Personally I hate this API inside the inside the mock because

[\[15:32\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=932s) If I wanted to verify it I have to say verifiable here and then I have to verify here. It's kind of a problem. So most of the time I actually use the testable version of something and if there are a lot of methods to override in a testable version then I would use one of the frameworks. Are there any questions about this before we continue? I'll show you another case where this is really helpful. Let's say that we don't have just a static method that let's say that we have a future object.

[\[16:06\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=966s) We can use extract and override not just to fake a value but we can actually use it to return a fake object. Let's say that we could if we wanted to inherit from real logger if we could do that we could extract this thing into a virtual method that returns anything that inherits from real logger or i logger in this case. So we can say extract method like get logger and this method

[\[16:36\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=996s) Public public static would make it to protected virtual ey logger get logger. By default it returns the real logger but then in our testable version we could return a fake logger. So then anyone who wants to get an instance of a logger actually gets an instance of a fake logger. So extract an override can be used not just to check that the method got called it can also be used to return fake objects and fake values. Another example,

[\[17:08\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=1028s) We can use it just like we use it for environment name. We could have used it for configuration settings or for or here we can actually give ourselves two options. The same as here we could either get return here a fake web service or we could fake the whole thing here into a virtual method. So we have two choices of which scope we want to fake. the do we want to return a fake object with an interface or do we just want to prove that some virtual method got called?

[\[17:41\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=1061s) The choice is up to us but both of these will be really easy to do. Okay. Now, most of the time I will check that the method got called because it's easier than returning a fake object etc. It makes test more readable. But I still don't have really great ideas on when to use which. Sometimes something feels a bit wrong with just overriding the whole thing. But at the end of the day, it's almost the same.

[\[18:11\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=1091s) Should making sure that everything gets sent in with the correct string, etc. Both of these will work just the same. So, you can use this as really, really powerful technique to to work on with a lot of legacy code bases. Another option where I've seen this really helpful is if you have a method with a lot of logic inside it that gets that depends on a lot of decision-m like if this is true then do this if this is true then do this or a method that does a lot of verifications like validations on an email or details and so then you can just extract and override each one of the validations

[\[18:47\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=1127s) So that you can set a lot of flags very easily from the test. You can say in the test this validation will return true, this validation will return false, this will return false. Now let's see what happens. So extracting override is really powerful for that kind of stuff as well. >> Yes, >> one question if we have the way and extracting to a protected method we have to we either get the ugly API in case of mock or it's not an issue if you have our own test version of that class.

[\[19:19\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=1159s) But if we if we say it's it's not an issue for us and we make it a public message, we can just use it and it's virtual we can we can just use it with a normal way of of using the mocking classes. Yeah. >> Yes. >> So the it really I I see see a big point with a special test version. So that's not the thing. you would say just yeah I was still not decided what I would prefer more just because otherwise we get a lot of classes just for these test versions

[\[19:56\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=1196s) And other hand we just have it potentially repeated in the in the test so >> so you're you're still undecided whether you like me keeping things protected or keeping things public. Well, personally, I I I like keeping them protected because I don't want to make too many methods public >> because it kind of spoils the API. On the other hand, yeah, because the point is that this method signifies to me that an external resource got called.

[\[20:27\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=1227s) >> Mhm. And if it's public, it's like calling the external resource directly. >> So you would have in that public API one method that eventually calls another public method. Yeah. >> And so it it kind of feels weird in terms of design, >> but so if if it wasn't meant to be public in the first place and it's just to satisfy a compiler, I'm not sure it's a good idea. >> Yeah. Yeah. >> But I could be wrong.

[\[20:57\]](https://www.youtube.com/watch?v=JIPB3peXJSA&t=1257s) I still I'm still in dilemmas about this myself. >> Other questions? >> Okay. So continue the exercises from login manager with statics. Okay, don't use any of the frameworks for now. Just use extract and override.

## Related

- [Mock Objects vs. "Inherit & Override"](https://osherove.com/blog/2005/6/16/mock-objects-vs-quotinherit-amp-overridequot.html) · osherove.com

    Roy compares mock objects with subclassing and overriding a virtual method, the technique shown slowly in this lesson.

- [Variations on refactoring techniques](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-3#ch03lev1sec5) · The Art of Unit Testing, 2nd ed., ch. 3

    The 2nd edition's section on variations of refactoring techniques, where it covers extract and override for fake results.

- [Partial mocks](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_95) · The Art of Unit Testing, 3rd ed., ch. 4

    The 3rd edition's section on partial mocks, its term for overriding selected methods of the class under test.

- [Performance vs. Testability and semi-virtual method calls](https://osherove.com/blog/2005/7/10/performance-vs-testability-and-semi-virtual-method-calls.html) · osherove.com

    Roy on the cost of making methods virtual for testability, relevant to the protected virtual methods extracted here.

### Also linked in this lesson

#### The Art of Unit Testing, 3rd ed.

- [Read Michael Feathers’ book on legacy code](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-12#sigil_toc_id_226), ch. 12
- [Defining unit testing, step by step](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_17), ch. 1
- [Integration tests](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-1#sigil_toc_id_25), ch. 1
- [Readability](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-9), ch. 9
- [How to know you trust a test](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-7#sigil_toc_id_134), ch. 7
- [Interaction testing, mocks, and stubs](https://livebook.manning.com/book/the-art-of-unit-testing-third-edition/chapter-4#sigil_toc_id_76), ch. 4

#### The Art of Unit Testing, 2nd ed.

- [The difference between mocks and stubs](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-4#ch04lev1sec2), ch. 4
- [Dynamically creating a fake object](https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-5#ch05lev1sec2), ch. 5

#### osherove.com

- [Test Driven Validation Logic with Extract & Override](https://osherove.com/blog/2012/5/16/test-driven-validation-logic-with-extract-override.html)
- [Issues in breaking dependencies for unit testing](https://osherove.com/blog/2005/8/23/issues-in-breaking-dependencies-for-unit-testing.html)

[Previous lesson Instance Delegator Focus](https://courses.osherove.com/courses/legacy-code-hero/instance-delegator-focus/) [Next lesson Extract And Override With Validation Logic](https://courses.osherove.com/courses/legacy-code-hero/extract-and-override-with-validation-logic/)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
