I have an object that represents a PDF file. In the constructor, I pull out various information about the file name and make it available via properties:
public class Invoice
{
//public properties
public string FullPath {get { return this.fullPath;} }
public string FileNameWithoutExtension { get { return this.fileNameWithoutExtension;} }
public string FileName { get { return this.fileName; } }
public string BatchSequenceNumber { get { return this.batchSequenceNumber; } }
//private fields
private string fullPath;
private string fileNameWithoutExtension;
private string fileName;
private string batchSequenceNumber;
//Default construtor
public Invoice(string filePath)
{
this.fullPath = filePath;
this.fileName = Path.GetFileName(filePath);
this.fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
this.batchSequenceNumber = Path.GetFileNameWithoutExtension(filePath).Split('_').LastOrDefault();
}
}
One of the attributes I would like to get is the number of pages in the PDF.
I am using iTextSharp
and I have a PageCount
method in the above Invoice
class that looks like this:
public int PageCount()
{
PdfReader reader = null;
int pageCount;
try
{
reader = new PdfReader(this.FullPath);
pageCount = reader.NumberOfPages;
}
catch (Exception ex)
{
throw new Exception("Error reading pdf! " + ex.Message);
}
finally
{
if (reader != null) { reader.Close(); }
}
return pageCount;
}
This works fine, except now I need to get the count of pages at several times during the object lifetime. I do not want to keep opening the PDF each time to get the count so these are my ideas:
Rename method
PageCount
toCountPages
and store the result in field/propertyPageCount
.Count the pages in the constructor and store the result in a field/propertry
PageCount
and don't expose aCountPages
method.
Number 1 seems preferable to me, but what if someone tries to read PageCount
before running method CountPages
? How best to handle this situation, set PageCount
to 0 in the constructor?
Number 2 seems bad because it feels wrong to open the PDF file in the constructor, is it? (I have been reading this)