开发者

Should I create individual properties in a class or just a method to set the values?

I am learning vb.net and I am having trouble wrapping my head around the following...

I can create several properties of a custom class and get/set values or I can create a method to set them all at once. If each property is going to allow read and write should I just make a method to assign values all at once? I assume that I am missing a very important piece here. Example:

I can create 2 properties:

    Public Class Employee
        Public Property LastName as string
        Get 
            Return strLastName
        End get

        Set(ByVal value as string)
            strLastName= value
        End Set
        End Property

        Public Property FirstName as string
        Get 
            Return strFirstName
        End get

        Set(ByVa开发者_JAVA百科l value as string)
            strFirstName= value
        End Set
        End Property
    End Class

or I can create a method:

    Public Class Employee
        Public Sub AddEmployee(ByVal strLastName, ByVal strFirstName)
            LastName = strLastName
            FirstName = strFirstName
        End Sub
    End Class

I apologize for such a noob question, but any insight is greatly appreciated. thank you!


If you only have a single method, you will have to use it even if you only want to change the value of a single field.

Additionally, in such a method, if you need to validate the input, you will need to write quite a lot of code for validation that is not relevant to all of the fields.

If values must be updated together, use a method to update them together and do not provide setters.

The reality of things is that how to do this depends on what you are modelling in your class. There are no hard and fast rules that say that properties are better than methods or vice versa.


There is no reason not to support both properties and a method that sets multiple properties.

Commonly, a constructor is used to create an instance of the class and to set some properties. In VB, naming a class method "New" defines it as a constructor. In your example, if you rename your AddEmployeee method to New, you will have a perfectly fine constructor. Then you program can create new instances as such:

Dim emp1 as New Employee("Burdell", "George") 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜