Join Reynald Adolphe for an in-depth discussion in this video Related objects needed once, part of C# Best Practices for Developers.
- [Instructor] Often times an object might depend on another object. For example, we've been working with the actor class and since actors are usually associated with talent agencies we can possibly have an actor class that has an agency as one of its properties and the way that agency object is instantiated depends on how its used. There's three common scenarios. The object might be needed once, for example, the actor might only need to access the agency name one time, or the object might be needed all the time.
Let's say the actor always includes the agency object information. And then there's sometimes. Maybe the agency information associated with the actor is only needed if the actor's employed. Let's go ahead starting off with scenario one to see an example. To get started let's go ahead and create an agency class within the project prestige.bis so I'll go ahead and select Add, Class, Agency.
We'll make this public and create a property called name, that is of a type string and we'll assign it a default value of Prestige Talent, that'll be the name of the agency. We'll save that and the next step will be to add a method in our actor class to get that agency so I'll move down to the last method we have here and create a new one.
It'll be returning a string and we'll call it GetAgency. So let's define our variable as currentAgency and create a new instance and we will return the name. Alright, so now we're ready to test.
Let's go ahead and jump into our test class. So now we are in our actor test class and I will create a method by just copying and pasting the last method that we have here and getting rid of some content that we don't need.
We just need one instance of the actor and before I continue let me rename this to TestGetAgency and we will be invoking the GetAgency method and right now it is complaining. That is because we need to change our type to a string.
Alright, now let's pause and see what we're doing again. Under the Arrange, we have our currentActor. We do need one more line of what we are expecting and that is the name of the talent agency and that's what we're doing in this test here. We're checking to make sure that we get our talent agency name. Okay, so now let's go ahead and save and I will right click and run our selected test, TestGetAgency, and it works just as expected.
Alright, now we're ready to test our second scenario. And that is when we always need the agency object.
- 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