How do I know if an object property has a default value?

I use the following snippet of pseudocode to clarify my question (the class used does not matter):

var client = new SmtpClient(); client.Credentials = ...; 

Now, if I want to use this code. How do I know how to use it. I could try setting the property value as follows:

 client.Credentials.User = "MyUsername"; 

which should give me a NullReferenceException because the default credential object is not set. Or I could use it like this:

 client.Credentials = new Credentials("MyUsername",...); 

But the correct way to initialize a property would be to set the value of DefaultNetworkCredentials as follows:

 client.Credentials = CredentialCache.DefaultNetworkCredentials; 

How do I know if an object property has a default value during development without looking at the documentation (if one exists)?

What is the best practice / design for object properties? Should there always be a default value for a property?

+4
source share
3 answers

All in all, this is a bad idea for developing an API where the caller must β€œskip the level”. Your example requires your API user to be aware of the internal credential structure - in particular, these credentials have a username. This is an indication of tight coupling - a thing that API design should avoid.

Through this, it would be possible to expose methods that skip this level of indirection for the user of your API, for example:

 void SetCredentialsUser(string user) { // Do the checks necessary to see if credentials are there; // create a new instance if necessary. } 

Now the user of your API can only work with your API, and not with the API of the Credentials object. The fact that Credentials cannot be set is hidden behind the method. You can even protect yourself from trying to write down your username by exposing the read-only version of the credentials through your API by using the read and write version under covers.

+2
source

You do not know the documentation, because properties are simply methods that can be implemented in any way that the author wants. The property could draw a random number and decide based on this.

So, you need an expression from the author of the class, whether it guarantees you that the property is never null.

I find it often faster to browse a class using Reflector than navigating through MSDN. Also, MSDN sometimes does not document these things.

For user interface components, a property grid often displays a default value. If you set a different value, it becomes bold. This information is taken from DefaultValue . However, there is no guarantee that the attribute is accurate.

+2
source

The best way is to check the documentation, however you can also look for DefaultValue attributes through reflection.

0
source

Source: https://habr.com/ru/post/1495199/


All Articles