Question

What are the pros and cons of using Primitve Types or Complex Types?

When should you use primitive types over complex types and vice versa?

i.e.:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public int IQ { get; set; }
}


public void FooPrimitiveTypes (string firstName, string lastName, int age, int IQ)
{

}

public void FooComplexTypes(Person person)
{

}
Was it helpful?

Solution

  1. To pass each property separately are generally used when you are dealing with disjoint values. Also, sometimes used on constructors. Bad practice.

  2. This way is preferred when the values are related.

Why #1 is a bad practice - suppose you needed to add height. I'd much rather update one class by adding another property, instead of 50 methods.

OTHER TIPS

Does Foo conceptually deal with a Person? Does all (or at least most) of Person get used by Foo, or is it just using a few bits of information that happen to be in Person? Is Foo likely to ever deal with something that's not a Person? If Foo is InsertPersonIntoDB(), then it's probably best to deal with Person.

If Foo is PrintName(), then maybe PrintName(string FirstName, string LastName) is more appropriate (or alternatively, you might define a Name class instead and say that a person has a Name).

If you find yourself creating half initialized temporary Person objects just to pass to Foo, then you probably want to break down the parameters.

Something to note is that when you use primitives they are being passed by value... the object reference is also being passed by value but since all the underlying references to the values are references it is effectively pass by reference. So depending on what you are doing this pass by value or pass by reference could be of importance. Also in the first case modifications to the primitives will not affect the values of the variables in the calling scope however modifying the object passed in will affect the object in the calling scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top