What’s new in Xcode 13.3
21st April 2022Best Hybrid App Development In Junagadh
2nd May 2022As a beginner developer, improving your code skills is probably one of your top priorities. But where do you start? With so much information out there, it can be tough to know which techniques are worth learning and which ones will actually help you write better code.
1. Start with a plan
One of the best ways to write better code is to start with a plan. Before you start coding, take a few minutes to think about what you want your code to do.
Don’t just jump into writing code because you think you know what needs to be done. Take some time to really understand the problem at hand.
- What are the inputs and outputs?
- What are the expected results?
- What are the steps involved in getting from one to the other?
- What data structures will you need?
- Are there any edge cases that need to be considered?
Answering these questions before you start coding can help you avoid getting lost in rabbit holes for hours or days. It gives you a chance to solidify your mental conceptualization of how the project will work, validate it against any clear leaps of magical thinking, and develop a set of test cases to check your work against as you go.
Winging it can be fun (and often tempting) but this approach doesn’t need to box you in constrictive ways or take up hours of time. Even a few minutes sketching a diagram on paper before you fire up your editor will pay outsized dividends.
Developing a clear understanding of what needs to be done enables you to turn your idea into a concrete plan. Even if the high-level program structure you develop isn’t perfect (and let your inner perfectionist off the hook — it won’t be!), you’ll find the resulting code easier to read and the complexity of extending the code much more manageable.
Tips for developing a high-level plan
- Develop a clear understanding of the problem you’re trying to solve.
- Before you start coding, take some time to think about what you want your code to do in order to solve that problem.
- Write pseudocode before you start coding. Pseudocode is code that isn’t quite real code yet. It’s useful for sketching out the structure of your code without getting bogged down in the details.
- Draw a diagram. Visualizing the problem can help you better understand what needs to be done and how the different pieces fit together.
- Check your work. Once you have a plan, check it against any clear leaps of magical thinking and make sure it’s feasible.
- Use inline comments to explain your thought process. Once you’re writing your code, including inline comments to explain what you’re doing and why. These comments can be very helpful when you or someone else comes back to the code later. This is especially true if you’re working on a complex problem that’s likely to be confusing to someone else.
2. Write meaningful variable and function names
One of the hallmarks of well-written code is that it’s easy to read and understand. A big part of making your code easy to read is using meaningful variable and function names.
Picking good names for things is hard. But it’s important, even in web development. Your variable and function names are usually the first thing people look to when they’re trying to understand your code.
- Camel case: Variable names are written in a series of words that are joined together, with each word except the first beginning with a capital letter. Example: firstName, lastName, printFullName(). Camel case is very common in JavaScript.
- Pascal case: Pascal case is similar to the camel case, but the first word is also capitalized. Example: FirstName, LastName, PrintFullName().
- Snake case: The snake case uses all lowercase letters and underscores to separate words. Example: first_name, last_name, print_full_name().
- Kebab case: Kebab case is similar to snake case but with hyphens instead of underscores. Example: first-name, last-name, print-full-name().
Tips for writing clear variable names
Variable and function names should be:
- Descriptive.
- Easy to remember and pronounce.
- Consistent with other names in the code.
To achieve this, you should:
- Use descriptive names. The name of a variable or function should describe its purpose.
- Avoid single letter names, unless the meaning is very clear from the context. For example, it’s usually okay to use i as an index in a for loop, because that’s a common convention.
- Avoid magic numbers. A magic number is a numeric literal that’s used in the code without a clear explanation of its meaning.
- Decide on a naming convention, then stick to it.
- As always, comment your code. When a clear name isn’t enough and you do need to review the original function or variable, you’ll be able to refresh your memory quickly.
3. Write small, modular functions
Functions are one of the most powerful tools in a programmer’s toolbox. They allow you to take a large problem and break it down into smaller, more manageable pieces.
Smaller functions are easier to test, easier to debug, and easier to reuse. They also make your code more readable because the purpose of each function is clear.
Consider this example:
function multiplySquaredNumbers(x, y) {
let xSquared = x * x;
let ySquared = y * y;
return xSquared * ySquared;
}
console.log(multiplySquaredNumbers(5, 6)); // Output: 360
There are other ways we could approach simplifying this function, which you may already have spotted. Here’s one:
function square(x) {
return x * x;
}
function multiplySquaredNumbers(x, y) {
return square(x) * square(y);
}
console.log(multiplySquaredNumbers(5, 6)); // Output: 360
4. Comment your code liberally
Comments are lines of code that are not executed but are there for the developer to leave notes for themselves or others. In JavaScript, comments are denoted with // for single-line comments and /* */ for multi-line comments:
Comments are a great way to improve the readability of your code. Use comments to explain what your code is doing and why you’re doing it.
Comments are important for two main reasons: they can help you remember what your code is doing, and they help others understand your code. It’s important to get in the habit of commenting your code as you write it. This will help you keep track of your thoughts and make it easier for others to understand your code.
Tips for commenting code
- Use comments to explain what your code is doing and why you’re doing it.
- Use comments to leave notes for yourself about things that need to be done or fixed.
- Use comments to explain complex or non-obvious code.
- Use comments to enhance readable code, not as a crutch.
- Comment your code as you write it. Don’t wait until later.
- Don’t over-comment your code. Only comment the parts that need explanation.
- Use clear and concise language in your comments.
- Avoid using acronyms or jargon.
- Keep your comments up-to-date with your code. If you change your code, change your comments.
- Delete obsolete comments.
5. Use arrays and loops for efficiency
Arrays and loops are foundational but powerful tools that can help you write better code. If you’ve started learning to code, you probably already know about them.
By using arrays, you can store data in an organized way. This can make your code more efficient and easier to read. Loops, on the other hand, can help you automate repetitive tasks.
Once you know how to use them properly, they can save you a lot of time and effort. For example, they can often eliminate the need for complicated, nested conditional blocks.
6. Write self-documenting code whenever possible
Self-documenting code is code that is easy to read and understand without the need for comments. This type of code is written in a way that makes its purpose clear.
This doesn’t replace good commenting habits, but it does force you to keep your high-level program structure in mind. You’ll produce more understandable code that’s easier to maintain and less error-prone.
Here are some ways to make code self-documenting:
- Avoid unnecessary code. This includes dead code (code that is no longer used but has not been removed) and comments that state the obvious.
- Write code that is easy to test. This means that your code should be modular and have a well-defined interface. It should also handle errors gracefully and in a consistent way.
- Keep the codebase small. This makes it easier to find what you’re looking for and understand how the code works.
- Keep your code well-organized. This means using a consistent coding style and structure, and using comments to explain complex code.
- Documentation is important, but self-documenting code is even better. It’s easier to read, understand, and maintain. So next time you’re writing code, ask yourself if there’s anything you can do to make it more self-documenting.
7. Don’t Repeat Yourself (DRY)
One of the most important principles of good coding is the DRY principle: don’t repeat yourself.
This means that you should avoid duplicating code whenever possible. Duplicated code is more difficult to maintain and more error-prone.
There are many tools that can be employed to avoid duplication in your code.
- Functions and modules. Functions allow you to encapsulate code that you want to reuse, which we looked at earlier (when we first mentioned the DRY principle). Modules allow you to group related functions together.
- Data structures. Data structures can be used to store information in a way that is easy to access and modify. For example, if you have a list of names, you can store them in an array rather than hard-coding them into function calls throughout your code.
- Inheritance. A more advanced way to avoid duplication is to use inheritance. This is a way to share code between classes by having one class inherit from another. We won’t go into detail about inheritance here, but suffice it to say that it’s a powerful tool that can help you avoid duplicating code.
- Libraries. Finally, you can avoid duplication by using tools and libraries. There are many open-source libraries that you can use to perform common tasks.
8. Use a Version Control System
A version control system is a tool that allows you to track changes to your code over time.
This can be a helpful way to revert back to previous versions of your code, or to see who made changes to your code and when. Using a version control system can also help improve collaboration, as it allows multiple people to work on the same codebase simultaneously.
There are a few different version control systems available, but some of the most popular ones include Git and Mercurial.
We recommend learning Git, because you can safely assume that most teams you join in the future will be using it.
Conclusion
Writing good code is an important skill for any developer, but it’s one that takes time and practice to master.
If you’re just getting started, the techniques in this post will help you write better code right away.
And as you continue to improve your skills, keep these tips in mind and refer back to them when necessary. With practice, you’ll be writing great code in no time!