Hello, Jim.
In this lesson, we're going to learn optional class API.
We're going to start a lesson from the definition of optional class is understanding of the goal and
purpose of this class will help you to understand that better known this will be an optional class API.
And on real Covid examples I'm going to show you how to work was methods from optional class, and then
to the lesson of explaining when to use optional.
And you will understand in which cases use of optional will be efficient and will not bring more harm
than good.
Besides that, I will answer to the question what alternative techniques might be used instead of optional?
Let's stop.
And let me start from explanation of what optional class is.
And why do we need it?
Do you know what?
No point or exception is?
Probably.
This is one of the most popular exceptions that interrupts our program execution.
Just a reminder to all students that no point or exception is an exception.
That's a strong one.
We try to invoke some Masset on the reference.
It is not initialized.
In other words, we have variables.
It doesn't store reference to any of objects in the heap memory.
And when we call some Massart on the variable, we received no pointer exception.
That tells us that we actually can't invoke any Massart on the nothing.
Is that clear?
And to avoid cases like this, we should never forget to perform no check before any Massart invocation.
The new clause that has been introduced in Java eight is supposed to alleviate some problems.
In my opinion, the introduction of this class is controversial from one side.
It is grades that geoengineers has two legs, this one to indicate places where we may have no potentially.
But from the other side, in my opinion, optional class, often used by developers inappropriately
and brings into the code more complexity and harm than good.
But in this lesson, I will share with you my tips and other you use optional class efficiently.
Generally speaking written and no reference from any massata considered to be a bad practice.
For example, you call getta on the object that doesn't have all fields initialized yet, and you receive
no reference.
Indeed.
What else you should receive if there is nothing yet?
What if a field is really empty and doesn't initialized with any reference yet?
Thorney ha.
One of the giants of computer science wrote I call it my billion dollar mistake.
It was the invention of the no reference in nineteen sixty five.
I couldn't resist the temptation to put in a no reference simply because it was so easy to implement.
I can add to that it wasn't just so easy to implement.
It was also so logical to implement.
Let me start sharing my screen to explain the problems that we have today.
Is it optional?
Closs is intended to solve I open class problem statement from optional package of my little project.
In this example, imagine that we have instance of the computer.
We have some computer and USB drive, potentially USB drive, maybe plugged in or may not.
I can call yet USB drive Massart on my computer object to get the reference to the USB drive in case
Nassan is plugged in.
I receive no correct.
But in case there is a USB drive, I can get access to the right contacts switch to check it state.
In this case, I need to perform no check again.
Can you see how my code looks like?
And the good thing about all this is that I am smart enough to perform such checks.
It would be worse in case such checks wouldn't exist at all.
And to my program would just fail.
Units execution that understands the point, in addition, is just annoying that these checks get in
the way of the business logic.
In fact, Zedek reasons that overall are the beauty of our program.
What would be better than this?
It will be better to build data structure that would indicate presence or absence of the value.
That's what we need.
Optional Class four.
So we agreed that we need a mechanism that allows a massive developer to explicitly denote there's a
return value for a massive may or may not be present optional class acts as a prop for an object that
may not be present.
Therefore, if we know that our get USB drive mass, it may not return a desert object.
We can change message, return type.
Let me open solution class now in this class, you can see is that get USB drive message from my computer
class, has the friends or Chen typed now?
It is optional parametrized by the USB drive.
And then my USB drive.
I have also updated through Chintan.
Now, is this is optional that this parametrized by rights protects, which did not pay a lot of attention
to the details at this moment, namely how we create objects of optional type, why I use this method
and didn't use another one.
We're going to learn optional gloss in a minute was detailed examples.
Now, I'd like you to understand the idea of problem and our solution.
In my main mass, you can see that I use features of optional class and they check whether some value
is present in my USB drive wrapper.
And this present I execute functions that takes USB drive as my argument.
Namely, I'm getting access to the switch, which is also optional.
And in case it is present, I just print switches state to console.
And if no, then nothing.
And in case there is no USB drive object inside the wrapper, I execute another function.
I just print to console.
That USB drive wasn't found.
As you can see on this example, optional is a similar to the wrapper that may or may not contains the
actual value inside itself.
In simple words, you can view optional as a single value container that is a contains a value of doesn't.
It isn't set to be empty fullerenes.
This construction, you make clients responsible to handle messy value.
You're just walking.
That value here may not be present and you decide what you want to do.
In this case, this client's responsible approach means that creators and Massart is not in the position
to define what should be done in case of missing value.
Is a sink is to throw exception Maseru an exception?
Probably not always the best case and proper behavior according to the business logic in the case of
missing value.
Now, I wonder, you look at this example with fresh eyes.
If Java community and software engineers would like to call this more readable code and simple if URL
statement, I am happy to accept it.
Really, guys, I just want to we don't lie to ourselves.
What we have, instead of if as blogs with a few lambda expressions that are also located inside each
other.
And moreover, all our mass is written optional now, and we can't just take value and work with it
in order.
We could avoid no point exception.
Well, definitely optional is a very powerful tool.
But guys, I can't see what we have want in this case.
There are multiple other features in optional that breena's amazing flexibility.
And let us write less lines of code with optional than without it.
That is true.
But again, it should be also a special case to apply those features of optional is a true story from
my life is one developer from my team created few classes, was all massive rechanneled, optional type
parameterized by other types.
I asked him, why would you do that?
And he replied, because we need to use optional everywhere where we may receive no.
Well, guess not everywhere.
And then again, use an optional everywhere.
Wouldn't agree with us for the better with the abilities that we are so struggling for.
So let's not API optional to better understand its power and understand, jaysus, when and where this
might be applicable.
I open optional demo class with a lot of examples here.
Let me walk you through each example.
Seeing the first ones that we are going to review is how to create an object of optional type in most
of the cases to create object of type optional when it is static, factor in masses, optional class.
The first way to create optional is to call static mass of empty.
This is our chance imta optional.
The empty mass is often used when it is known apro or is at no value exists.
If you have some value and you need to create optional call, static method of attention, you need
to have that object behind's a reference that you are going to use to create optional object was of
mass, because in case you pass no value to the of method, you will get no point exception.
In the case, you know its value behind the reference, Megan, now or may not be now, use another
method of nullable.
This will create optional object based on the no and no not.
Various for example, in previous example, in solution, I used of nullable factor in mass because
I knew that I may need to create optional object based on value.
Now let's review methods that allow us to check if value is present or absent, that the masses that
allow us to check the value inside the optional is present and is empty.
Obviously, these masses are controversial.
One is present, returns true, is empty, returns false, and vice versa.
Here's an example.
You can see that I have destry quail and check was an optional is empty or has value and is a similar
test for optional that contains Nassan.
As a result of method execution, you confront and conceal output.
Now let's review example of conditional masses.
I call these methods conditional because based on the specific condition, API allows us to perform
one or another action.
The first method in this example, if present you already you saw me using this method in the example
in solution was use B drive F presence method takes consumer as method argument.
If you're not familiar with lambda expressions and such function interfaces as consumer, I recommend
you to pass my course.
Guanciale programming for Giwa Engineers.
I explained these topics in detail zere.
Just to remind you, consumer takes some argument and returns nothing.
So basically, if the value is present, we pass it.
Does it function and perform any action?
Was it.
What we need in this particular example.
I just printed to console in case there is no value in optional.
We just ignore this function and just do nothing.
Another conditional Massart is if present or else.
I also use this one in solution of the examples that I have already showed.
I believe that from the massive name, it is already clear for you what is this method for.
So in case value is present, will use consumer and will work with the value.
In the case, value is absent, will execute some random that contains lines of code to be executed.
In case there is no value.
The next example is simple and regular gets massive.
You can extract value from optional Bikel and get mass, but be attentive.
In case there is no value, you will get no such element.
The exception.
And here, in example, you can see this just in case optional is empty.
We are catching exception.
In practice, it is recommended to use is present.
Massett, that guarantees that there is a value inside optional.
So just remember this.
Let's imagine that we are using is present Massart.
OK.
Just look at this example.
How far it is from no check from our problem statement was if we again have the similar Evelio.
That's why in most cases we intentionally award to use the get Masset and use one of the other methods.
Such as.
Or else or else through top things of value associated with a populated, optional.
Or perform another action.
Let me show you this in the next example, you can see how to use or else mass.
Basically, it returns a value if at this present and in case it does not.
It returns the values that they passed as a message.
Also, we have or else get method.
What is the difference between orals and this?
Massively different parameters oils.
Yet they supply as methods argument.
Supply is a function that produce something.
It takes nothing and returns some value.
And what does it give us?
Well, probably it is not obvious in this particular example.
But let's look at the next lines.
Imagine that you have some massive that performs a lot of work and calculations and as a result, recharges
your reference to string value and then use your call or else Massett.
And you would like to parse the string returned by these massive PZM Massett is actually involved.
And you spent some time to wait until the mass of the got finished.
But is it the same with or else get method?
No.
Lukins this line you're actually not invoking is a massive you just Parsons's reference to the function
that knows how to get the value for you.
In case this is needed.
This is the main difference.
Lasing insolate Zeeshan in the first case we're invoking Massart no matter was an optional has a value
on.
No.
And in.
The second case would just use functions that knows how to provide us with value only when it is needed,
only when optional has no value.
Does it make sense now in case the value is absent and you want to throw an exception.
You can use or else throw massive.
This method is overloaded.
The version without arguments will throw no such element.
The exception by default.
Or you can post supplier as Mussert argument to generate object of the exception that you would like
to throw.
Now let's somehow filter Massart works.
In case you have the reference to the optional object, you can check it first to understand whether
it is much your predicate.
And in case verification this past, you receive optional was that value.
Otherwise, you receive empty optional.
Let me explain this example.
Imagine that I have optional that contains my full name.
After that, I can call Filton Masset on the optional object and pass predicate.
Let me quickly remind you what Prickett is.
CreditCard is a functional interface that declares one.
Massart is.
It takes one argument and the returns is a true or false.
So here is my function.
I pass full name and I check whether it contains Andry.
If yes, then I receive optional with this name when I call, or else I get the reference to my whole
name and bring that to console in a similar example.
But with a different name, I will get give empty optional.
And you can charge this by console output in the second case paren to console the false string that
they used in or else methods.
Do you understand why we may need to field the method that is normally used to reject wrapt values based
on the predefined tool?
Imagine now in another case we have a user object, and we need to make sure that the users that we
received from database or from another method has Mercier's less than one number than the more than
another number.
How to do that?
We can use map mass simply to convert the rabbit value to another type, Zimet, Mass, that allows
us to convert the value from one object to another.
If an optional is populated, this method can be thought of as a pipeline method, whereas the rabbit
value is passed along the pipeline and transform.
Can you value the remember how Stream API works?
This similar concept is here.
This method works by accepting the function object as it is applied to the rabbit value to produce the
mapped value.
Even the optional is empty, is a function object is never called, and an empty optional is returned
from the map massively.
Let me explain your own example.
I have optional parametrized by type user.
I have arrived here.
User object.
This user has named Igor and his universe is 1990s.
I call map Massart on my optional object to convert data in the pipeline from user to an end.
I need to pass functions that knows how to transform the current type thing.
And when I have int value in pipeline, I can use filter mass to check was a year of birth of the current
user is within the expected range.
In this case, my user matches the current filters and optional was very is returned.
That's why I can print the user's Berthier tokens.
So what does this example please let me know in case you have any questions in case something is still
unclear.
Please.
What's your question below this video?
And there will be happy to answer it.
Let's review another method that is similar to those in Map Mass.
Let's have the flat map Masset as an alternative for values transformation.
There is one main difference between these two masses.
The difference is that map transforms values only when Xe unwrap.
Whereas flat map takes a wrapped value and unwraps it before transforming it.
Let's make sure that you understood this following Z example.
So imagine that we keep working with the same user, but interested in sync in a mass returns, optional
to, for example, get name Massart, which is optional.
It is parametrized by string.
No.
And all what we know that's extracted from the optional parameterized by type user.
The first thing that I do, I want to convert optional of user to the just name.
What I got instead.
Instead, I got optional parameterized by optional the disbursements surprised by string.
That is because my get name Masset returns optional.
Having this wrapper, I can extract optional parameterized by a string.
It should contain the name of the user, and only after that I can extract user.
Don't you think that they added a lot of redundant steps similar to the Stream API from Jaedicke?
So that map doesn't rabs the value was additional optional.
So to achieve the same goal in a little bit simpler way is to call threads, map and parse the references
to get name message.
And now I can apply Ozz masses to extract value like or message.
And in console, you can see that the results are the same.
But the second option, Dukas, less lines of code to achieve is the same result.
Does it make sense?
In my opinion, we have removed all the most important masses from optional API that might come in handy.
But any way opens a source code of GMU to optional class by yourself and investigated.
Now let's discuss when and how to use optional to make sure it is not dangerous and you don't bring
more harm than good.
Let's review different parts of our program and different use cases.
And I will give you my advice.
Return values.
Often optionals are well suited for a chance values.
Originally, this was intended to be zem main use case in documentation that we can find.
Is it optional?
Type is primarily intended for use as a message, Chantae, where there is a growing need to represent
no result.
And we're using now is likely to cause errors.
And here I'd like to pay you extra attention in order you wouldn't follow code style of colleague of
mine who has all methods developed this optional type return.
You should return optional as of this set where there is a clear need to represent no result.
And we're using now is likely to cause errors, not everywhere.
But still, this recommendation leaves error for interpretations.
I would also add one more important thing to consider.
Use optional only in cases when you want to make client of your code responsible for handling of absent
value.
And this is really a good reason not to put optional the chandab everywhere.
Why?
Because in most cases, we need to provide ready to use API, but not make our clients seeing about
each return value, what to do in case value wasn't returned regarding the fields.
Let me put it simple.
You can create fields of optional type, but you shouldn't.
Why?
For me, it is a sign of a bad architecture.
You have fields known from the beginning that they may not be initialized.
But in this case, you have met Iraqui and that or the architecture was not implemented.
Solid principles.
Probably there are some classes that don't need all these fields, and it is just a matter of building
of proper Iraqui.
A lot of questions.
So I'll put it simple, the not to use optionals in fields parameters.
You can use optional methods, parameters.
But again, it is not recommended to do that.
It is recommended instead to have law that.
If you know that, you might need to invoke this method with no parameter or this empty optional, in
other words.
So just with mass, that takes no parameter.
But you also can have our law that was the same name, but which takes parameter.
Is that clear?
Some students ask me what is alternative to use an optional.
Well, the simplest alternative is to leave like our ancestors left.
Just use no value and do not forget, put no checks.
This is still the case in a lot of programs nowadays.
Another alternative might be a sort of an exception if absence of the value really brigg's the way of
your program execution.
Then you need to be prepared to handle specific exception and to handle it properly.
During the handling of this exception, you specify 70 fractions.
What is needed to be done in case the value is absent?
Almost a similar way you do with optional.
And another alternative is no objects.
You can create a time that has the same API, but it is empty inside and all my are error safe.
And when it is seen, you just create.
Instance of the empty object or just parcels, a reference to that empty constantly, for example,
in collections, glossaries, empty, list constant.
And instead of returning, no one least is expected.
You can just return empty.
These constant that will save you from no point exception remembers use of devices.
They're years of experience and millions of dollars behind these advices.
Let's recap what we have learned in this lesson.
In this lesson we learned.
Optional class API and its methods.
It knows the purpose of the optional and when to use it.
And at the end of the lesson, I also explained few alternative techniques to use instead of optional.
That's all for this lesson.
Thanks a lot for your attention.
Have a great day and see you in the next lesson.