Join Reynald Adolphe for an in-depth discussion in this video Related objects needed sometimes, part of C# Best Practices for Developers.
- Now for our final scenario, we're considering when we need an object sometimes. There's no need to use a constructor as it's going to be a waste. Why create an instance every time when we're only going to use an object occasionally? So we should wait and create it when we really need it. And that's when lazy loading comes into play. So in our default constructor let's go ahead and comment out where we are creating a new instance of the agency and instead let's modify our property by adding an if clause.
I'll type in if and use that snippet by hitting tab, tab and then enter in if the current agency is null and at this point we can create a new instance for that currency. A new instance of an agency. If it's not the case it's going to return the current instance. So let's go ahead and save that and we'll run our test one more time.
And it looks like it worked successfully. And this is ideal, once again, for when we know we're going to need an agency occasionally and not create an instance every single time. So to touch on best practices, so just keep in mind that if you're working with objects that have relations to each other and that the pennant object is needed only one time like in our case with the agency in our first scenario. Consider instantiating manually in a method if an object is needed always, consider creating a property using the default constructor.
And if an object is only needed sometimes then consider instantiating it using a property via lazy loading.
- Naming and handling classes
- Running a unit test
- Using constructors
- Naming and handling methods, fields, and properties
- Using properties correctly
- Managing objects efficiently
- Common design patterns as best practices