This question came to my mind because I was working on a project, and I created the following method:
private void GoToFirstPage() {
CurrentPage = 0;
}
which I use in a few methods related to pagination.
Is it a good idea? Or should I be calling CurrentPage = 0; instead in all the method calls?
First, how likely is it that you’d ever change the implementation of
GoToFirstPage? For example, if this is, say, a PDF viewer, might the next version have a continuous scrolling mode as well as a page-by-page mode, so you’ll keep a CurrentTopLine instead of a CurrentPage? In that case, if you’ve gotCurrentPage = 0;in 15 different places, and you have to change all 15 of them toif (PageMode) CurrentPage = 0; else CurrentTopLine = 0;, that’s a perfect opportunity for stupid bugs to creep into your code because you forgot about 1 of them and only changed 14. If you’ve got it in a method, you only need to change things in one place.In some cases, having a name for the method gives you some extra documentation (and unlike a comment, it won’t get stale as things change, because you have to keep it up to date or things won’t compile). In this case, I don’t think that’s relevant, because
CurrentPage = 0;is just as readable and meaningful asGoToFirstPage();, but in many cases, it is.Occasionally, performance is a concern. Function calls aren’t free, after all. But in this case, it’s hard to imagine it could ever matter. It’s not like you’re going to call
GoToFirstPagemillions of times in a tight loop, right?So, if none of these are relevant, how do you decide? The most important factor is probably what’s more idiomatic for your language, codebase, etc. In a typical Java program, a function like
GoToFirstPage();would fit in perfectly, and it might even be implemented asSetCurrentPage(0);for another layer of encapsulation. In a typical Python program, thecurrent_pageproperty would be part of even the public API of the class. Neither one is necessarily bad or good, and consistency of style is important in keeping your code readable.