Reputation: 65
For illustration purposes let us say I'm building a simple blog application and have a class called Blog:
Class Blog(){
__constructor(){
connectToDatabase();
}
}
Class BlogPost($id) extends Blog {
public $title;
public $body;
etc.
}
The blogpost class can be instantiated as an object representing a particular blog post. But when I want to list all the records in the database I have to put that function somewhere else.
I could put it in the Blog class, but assuming I have many, many such functions that don't apply to a particular object, where should I put them?
Or maybe I'm writing a line to a log file. It seems silly to have a 'logfile' class containing a single function that writes a passed string to the text file.
Is it best practice to lump them all in some Utility() class, or should I create several classes such as util_commenting(), util_archives()? Just where should I store all those little stand-alone functions?
Upvotes: 4
Views: 292
Reputation: 17971
"Classes for Concepts" is a good aphorism to remember.
Try writing some stories/scenarios/use cases to describe how the system works.
You will likely find that the free functions fall end up in groups that are required to satisfy some of the stories.
I recommend Rebecca Wirfs-Brock's "Responsibility-Driven Design". There's a nice overview paper on her publications page.
Upvotes: 1
Reputation: 146968
Most of the time, free functions should just be put in a well-named namespace. If you look at the C++ standard libraries, there are a number of free functions in std (like sort, for example). You could create a blog namespace, with a blog class contained within (blog::blog) and then have other utility free functions to do with blogs in that namespace.
They don't need to go into any class and it's definitely NOT best practices to go for a singleton style.
Upvotes: 0
Reputation: 308928
That's a persistence layer object. Usually it's a data access object (DAO) or repository, not a utility or general function.
I would take that function connecting to a database out of your constructor. It does not belong there.
If I were writing this in Java, it might look like this:
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);
}
There'd a class that implemented the BlogDao interface using whatever technology I wanted (JDBC, Hibernate, etc.)
Upvotes: 0
Reputation: 75629
You could have a BlogPostRepository or a Database object, which can return all BlogPosts.
Upvotes: 0