filmov
tv
Why does my java code throw a null pointer exception - how to fix?
Показать описание
A common reason for Null Pointer Exceptions in Java is a variable redeclaration instead of instantiation. Learn what that means, how to avoid it, and how to spot it, in this presentation.
# FAQ - why does my code throw a null pointer exception - common reason #1 Redeclaration
- Any 'variables' we instantiate need to be 'fields' rather than variables
- We want to instantiate them in the setup method rather than redeclare them
- To make the code readable
- I could do that
- but I don't think I would have declared a new variable after the refactorings because I have a working code example that I'm moving.
# In General
- Try to write one test at a time so that if you have a problem it is easier to identify where the problem is
- Try to write working isolated tests and then refactor to a more general solution when you need it - that way, you know it was working, so you just have to work backwards to find out what went wrong
- Try to use automated IDE refactoring rather than move code around manually
- Use the IDE syntax highlighting to help spot any issues
For more details see Blog Post:
SlideShare:
# FAQ - why does my code throw a null pointer exception - common reason #1 Redeclaration
- Any 'variables' we instantiate need to be 'fields' rather than variables
- We want to instantiate them in the setup method rather than redeclare them
- To make the code readable
- I could do that
- but I don't think I would have declared a new variable after the refactorings because I have a working code example that I'm moving.
# In General
- Try to write one test at a time so that if you have a problem it is easier to identify where the problem is
- Try to write working isolated tests and then refactor to a more general solution when you need it - that way, you know it was working, so you just have to work backwards to find out what went wrong
- Try to use automated IDE refactoring rather than move code around manually
- Use the IDE syntax highlighting to help spot any issues
For more details see Blog Post:
SlideShare:
Комментарии