Join Simon Allardice for an in-depth discussion in this video What you need to know, part of Foundations of Programming: Refactoring Code.
As with most of my foundations or programming courses I want you to find this one really useful across many different languages. But that presupposes a couple of things, first that you can already program in an object or into a language. I don't really care which one, but we're doing a course here all about improving existing code. So, you need to understand the code your intending to improve. Refactoring is something you can only do to code you can already read, write and understand. Now I say, object oriented language because while there are many of these refactoring techniques that apply to a non-object oriented language.
Now as you might imagine, I will need to show some code from time to time. And rather than jump between a dozen different languages, I'm typically going to use Java. This might sound like personal preference, but really isn't. I don't program in Java anymore; I haven't for over ten years, but java is simply the most generic language I could use for this. If you're a C++, C sharp, objective C programmer, you shouldn't have any problem reading Java, even if you've never written a line of it. And I would wager, more Ruby and Python programmers are comfortable enough reading a C style language than the other way round. That doesn't mean you need to an expert on Java syntax, that's not neccessary, it does mean that I could bring up some code like this. And you would understand this is a method called calculateDiscount, that takes in a parameter, performs some simple operations, and returns the result. But all along, we're going to be focusing on the concepts, it's not about the syntax here.
So you should be easily able to apply these ideas, in whatever language you choose. With the same end in mind, I will always use as simple an example as I can to illustrate any of these techniques. And that means you should fully expect to see some really straightforward code, say, a method that takes two values, adds them together, and returns the result. And sure, we wouldn't really be worried about improving an introductory level program like that. But if I can illustrate a technique here using very simple code, then I will.
Conversely, if there is something that only makes sense with a complex inherited situation well then, we'll use a complex inheritance situation. But with that in mind, let's cover exactly what refactoring is and clear up the common misconceptions people have about it.
- What is refactoring?
- Recognizing common code smells
- Simplifying method calls
- Making conditions easier to read
- Using refactorings at the method, class, and application level