Null Safety
What’s the problem with null?
Section titled “What’s the problem with null?”If you have been programming any amount of time, you’ve provably had a program crash because you tried to call a method on a variable you didn’t realized was a null
void main() { String name; print(name.length);}Uncaught TypeError: Cannot read properties of null (reading 'get$length')Error: TypeError: Cannot read properties of null (reading 'get$length')Null safety enables the compiler to help you find and fix those bugs before you run the code.
- Goal is not to eliminate
null, the absence of data is like part of life right? - some people don’t have middle names, some attributes doesn’t have values, So
nullis a great way to model data you don’t have - it has short little syntax, many developers familiar with it, so
nullis not a problem, calling the methods onnullis
How we right code?
Section titled “How we right code?”- We right some code
- Expect it to be worked
- Run our program
- On a good day it works on bad day we get an exception
- and we repeat
Productivity of a developer will increase if we ease done this iterations
So we have introduced non nullable type by default which means Null Safety
Type Systems
Section titled “Type Systems”In dynamically types types language , I might have to run my program and get an exception before I realised the mistake, but in Dart type checker immediately tells me there’s something fishy here
- but if you add some runtime features in language → potential to increase set of things user can do
- Type systems don’t work that way, we mostly get compile errors which prevent your code from running
We can make type check dance the way want→ lets say to check even or odd number
but it doesn’t help us to build apps right
Static analysis helps
- to check every possible way our code could executes
- every path it could be taken
- the value variable might have
Live Coding
Section titled “Live Coding”- change
seBackgroundColorparameter as nullable and call is nullsafe- assign before accessing the value
- check is it is null or not
- change
seBackgroundColorparameter as nullsafe and call is nullable- assign before accessing the value
- Random().nextBool() to show case control flow
- ??