Where to put common functions in OOP?

For illustration purposes, let's say that I am creating a simple blog application and have a Blog class:

Class Blog(){
   __constructor(){
       connectToDatabase();
   }
}

Class BlogPost($id) extends Blog {
    public $title;
    public $body;
    etc.
}

The blogpost class can be created as an object that represents a specific blog post. But when I want to list all the records in the database, I have to place this function somewhere else.

I could put it in the Blog class, but suggested that I have a lot of functions that don't apply to a particular object, where should it be placed?

Or maybe I'm writing a line to a log file. It seems silly to have a "logfile" class containing one function that writes the passed string to a text file.

Utility(), , util_commenting(), util_archives()? ?

+3
4

. (DAO) , .

, . .

Java, :

public class Blog
{
    private Long id;
    private String title;
    private String body;
    private String author;
    private Date publishDate;
    // Other attributes and functions here.   
}

public interface BlogDao
{
    Blog find(Long id);
    List<Blog> find();
    List<Blog> find(Date begDate, Date endDate);
    List<Blog> find(String author);
    void saveOrUpdate(Blog blog);
    void delete(Blog);
}

, BlogDao, , (JDBC, Hibernate ..).

0

" " - , .

// , , .

, , , .

- ", ". .

+1

BlogPostRepository Database, BlogPost.

0

. ++, std (, ). , (blog:: blog), , , .

They do not need to enter any class, and this is certainly NOT the best experience for a plain style.

0
source

Source: https://habr.com/ru/post/1763060/


All Articles