OO style options and type options

Say you have two methods:

Number 1:

void AddPerson(Person person)
{
  // Validate person
  if(person.Name != null && IsValidDate(person.BirthDate)
    DB.AddPersonToDatabase(person);
}

Number 2:

void AddPerson(string name, DateTime birthDate)
{
  Person p = new Person(name, birthDate);
  DB.AddPersonToDatabase(person);
}

Which of the two methods is the best? I know that the first one is more correct OO-wise, but I feel that the second one is more readable, and you do not need to check that the object is valid, as the parameters guarantee this. I just don't like checking objects anywhere I pass them as parameters. Are there other approaches?

EDIT: thanks for all the answers. To clarify, validation in the constructor and the IsValid method is, of course, a good approach, but in my code the actual state of a person often depends on the context and can vary from method to method. This, of course, could be a sign of poor design.

This code is just an example to describe the problem.

+3
12

person.Name person.BirthDate - Person. , , , .

, , Person .

, , . Person, .

+10

, Person , . , , , .

+2

:

void AddPerson(Person person)
{  // Validate person  
   if(person.IsValid)
   {
     DB.AddPersonToDatabase(person);
   }
}

, , . , , .

+2

( ), API . Person, . , Nickname, , API, , .

+1

, , . , :

person.SetBirthDate(Person person)
person.ResetPassword(Person person)

, , , () - .

, (DRY - Do not Repeat Yourself):

void AddPerson(Person person)
{
  if(person.Name != null && IsValidDate(person.BirthDate)
    DB.AddPersonToDatabase(person);
}

void AddPerson(string name, DateTime birthDate)
{
  Person p = new Person(name, birthDate);
  this.AddPerson(p);
}
+1

Person , . :


public static void Withdrawal(Account account, decimal amount)
{
    DB.UpdateBalance(account.AccountNumber, amount);
}

public static void Withdraw(int accountNumber, decimal amount)
{
    DB.UpdateBalance(accountNumber, amount);
}

, - . Int , , :

private void CloseTransaction(Transaction tran)
{
    BankAccounts.Withdrawal(tran.Account.RoutingNumber, tran.Amount);
        // logic error: meant to pass Account.AccountNumber instead of Account.RoutingNumber
}

, . , , , .

, , ​​. , , GL 100 , . , - ​​ .

+1

.

Person

0

.

Person, .

, , Person, .

0

. , .

0

, Person. , , (Person) imo. . , . .

- , .

, .

0

, . Person , .

, Person ( AddPerson ),

http://en.wikipedia.org/wiki/GRASP_%28Object_Oriented_Design%29#Creator

. , AddPerson DB, . , Person . , , , AddPerson, , , Person.,

0

Encapsulation is better if you use objects; what are they needed for. I think people get in trouble when using primitives too much.

Unable to create an invalid Face. The constructor should check the valid parameters and throw an IllegalArgumentException or not give an approval if they are invalid. This is what contract programming is about.

0
source

All Articles