Home Writing elegant code
Simplify your code
When writing complex algorithms, try and write the simplest and cleanest version of the code possible.
This can be challenging – the ideal is to simultaneously write elegant code with no redundancy while still being fully efficient. Sometimes, you can accomplish this ideal by making minor adjustments to your code; sometimes you need to rethink your entire approach.
There are some simple things we can do to simplify complex code.
For example, it's often possible to combine conditions and loops together by thinking about what each is checking. As an example, suppose we wanted to iterate through a series of listnodes, but only when it's not empty. Naively, we might try expressing the logic like this:
if (this.front != null) { ListNode current = this.front; while (current != null) { System.out.println(current.data); current = current.next; } }
However, if you think carefully about what this snippit of code is doing, we can remove the if statement entirely! The while loop will already not run if the list is empty, so there's no need to have an explicit check for it:
ListNode current = this.front; while (current != null) { System.out.println(current.data); current = current.next; }
When working on your code, you should keep this idea in mind. Think carefully about each piece of code you've written, and ask yourself if that segment is actually something you need. Be sure to test after you've made a change! You don't want to accidentally introduce a bug by deleting someting essential.
There are also some more complex things we can do to reduce complexity. Unfortunately, it's a little hard to give concrete examples for each one, so instead, here are some questions you should consider:
- Can you combine certain cases in your code?
- What information do you have available to you?
- Can you use information you already have to get what you need, instead of having to do another search?
- What problem are you trying to solve? Can you try solving a slightly different problem to more easily get what you need?
- Can you write helper methods to abstract out some common operations you're performing?
- Have you refactored too prematurely? If you were to "unrefactor" your code, are there opportunities to rearrange your code in a way that's more elegant overall?
Re-implementing convenience methods
Whenever possible, you should avoid re-implementing methods. Two common offenders
are using list.size() == 0
instead of list.isEmpty()
and
using stringA.toLowerCase().equals(stringB.toLowerCase())
instead of
stringA.equalsIgnoreCase(stringB)
.
If you're not sure if you're allowed to use a convenience method/if using it would count as advanced material, ask. As a good rule of thumb, if a method is listed on a cheat sheet from section, you may use it.