Jimmyt1988
Jimmyt1988

Reputation: 21126

What's the best approach for two functions that use same code

I have 2 functions, they currently are doing the same thing.. In the future, it's quite possible that I need to add more functionality to one, but at the moment they act the same.

private function GetAnswerId( $value, $fieldId )
{
    // Code goes here, returns something      
}

private function GetQuestionId( $value, $fieldId ); // Currently same code as GetAnswerId... But might change later!

Is there some clever way of communicating to future developers that okay this function is currently the same implementation but in the future it won't be.. I don't want to just copy the code in GetAnswerId because that's drydicoulous. but I also don't want to use the same function because that's not forward thinking.

Virtual? Abstract? something like that :S

Upvotes: 0

Views: 82

Answers (3)

Alexander Yancharuk
Alexander Yancharuk

Reputation: 14501

Move your duplicate functionality to base class:

class BaseClass
{
    protected function getId($value, $fieldId) {
        ...
    }
}

Use one method getId() instead of GetAnswerId() and GetQuestionId(). Later, if you will decide change functionality for question ID, just add new method to current class:

class CurrentClass extend BaseClass
{
    protected function GetQuestionId($value, $fieldId) {
        ...
    }
}

Upvotes: 1

Savv
Savv

Reputation: 431

Call your first function in your second function and expand from there:

private function GetQuestionId( $value, $fieldId )
{
     GetAnswerId( $value, $fieldId );

     // extra code
}

Upvotes: 1

Guilherme Sehn
Guilherme Sehn

Reputation: 6787

In your case, I'd add some documentation to your function explaining that it is planned to change its behavior soon and make this function call and return GetAnswerId's value.

private function GetQuestionId($value, $fieldId)
{
    return $this->GetAnswerId($value, $fieldId);
}

Upvotes: 0

Related Questions