Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a new object and calling the method at the same time

I have simple code (iTextShar library) who generate PdfCell with Phrase:

//I create new Phrase
Phrase p = new("Lorem ipsum", myFont);

//I set leading for Phrase
p.setFixedLeading(10f);

//I create new Table Cell end insert Phrase
PdfPCell cell = new(p);

Why can’t I generate Phrase directly on PdfPCell and simultaneously run method .setFixedLeading. Somethink like this?

PdfPCell cell = new(Phrase p("Lorem ipsum", myFont).setFixedLeading(10f));

Is there any way to set Leading using the .setFixedLeading method when creating a new Phrase object?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could write your own method:

private Phrase CreatePhraseWithFixedLeading(string text, Font font, float fixedLeading)
{
   Phrase p = new(text, font);
   p.setFixedLeading(fixedLeading);
   return p;
}

Usage is

Phrase p = CreatePhraseWithFixedLeading("lorem ipsum", myFont, 10f);
PdfPCell cell = new(p);

or, if you don’t need the phrase after creating the cell

PdfPCell cell = new(CreatePhraseWithFixedLeading("lorem ipsum", myFont, 10f));

If you have more methods to call after you created your phrase, you could take a look at the builder pattern.

But on the other hand, you should ask what you gain by this. The code you presented was perfectly fine. Don’t try to put as much into one line as possible.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading