Reusable VS clean code - where's the balance?

Posted by Radek Šimko on Programmers See other posts from Programmers or by Radek Šimko
Published on 2012-10-11T08:06:10Z Indexed on 2012/10/11 15:48 UTC
Read the original article Hit count: 980

Let's say I have a data model for a blog posts and have two use-cases of that model - getting all blogposts and getting only blogposts which were written by specific author.

There are basically two ways how I can realize that.

1st model

class Articles {

    public function getPosts() {
        return $this->connection->find()
            ->sort(array('creation_time' => -1));
    }

    public function getPostsByAuthor( $authorUid ) {
        return $this->connection->find(array('author_uid' => $authorUid))
            ->sort(array('creation_time' => -1));
    }
}

1st usage (presenter/controller)

if ( $GET['author_uid'] ) {
    $posts = $articles->getPostsByAuthor($GET['author_uid']);
} else {
    $posts = $articles->getPosts();
}

2nd one

class Articles {

    public function getPosts( $authorUid = NULL ) {
        $query = array();

        if( $authorUid !== NULL ) {
            $query = array('author_uid' => $authorUid);
        }

        return $this->connection->find($query)
            ->sort(array('creation_time' => -1));
    }

}

2nd usage (presenter/controller)

$posts = $articles->getPosts( $_GET['author_uid'] );

To sum up (dis)advantages:

1) cleaner code

2) more reusable code

Which one do you think is better and why? Is there any kind of compromise between those two?

© Programmers or respective owner

Related posts about php

Related posts about code-quality