6 Efficient Things You Can Do to Refactor a C++ Project by Bartlomiej Filipek (Bartek)

Bartek posted an article today as part of a series of his work modernizing/refactoring a legacy C++ project. His series of articles takes an old C++ application and brings it up-to-date.

In the article, Bartek covers the following techniques:

  1. Having the latest Compiler and correct C++ Standard version
  2. Fix Deprecated or Removed C++ Features
  3. Unit Tests
  4. Decouple or Extract Classes
  5. Extract Non-member Functions
  6. Reduce the Global State

Read the article on Bartek’s Blog

Note: portions of this article text and images are © Bartlomiej Filipek, 2020.

About Bartek


Bartlomiej Filipek (Bartek) is a software developer in Krakow Poland. He works at Xara as a C++ developer. Bartek is a Microsoft MVP and author of two C++ books:

C++17 in Detail: Learn the Exciting Features of The New C++ Standard! (paperback version available on Amazon)

C++ Lambda Story: Everything you need to know about Lambda Expressions in Modern C++! (Kindle version available on Amazon)

Twitter: @fenbf
LinkedIn: https://www.linkedin.com/in/bartlomiejfilipek/ 
Blog: https://www.bfilipek.com/
Email: bartlomiej DOT filipek AT gmail DOT com


Building a C++Builder RSS Feeds VCL Application with XMLDocument, NetHTTPClient, NetHTTPRequest and WebBrowser Components

I have many favorite prebuilt components that are included with C++Builder 10.4 Sydney. In this blog post I’ll show you how to create an RSS Feeds VCL (you can also use the same approach for a FireMonkey FMX) application using the XMLDocument, NetHTTPClient, NetHTTPRequest and WebBrowser components.

Start by creating a C++Builder VCL application. Set the form’s WindowState property to wsMaximized. Add a Panel, Button, ListBox (used to hold the list of RSS feed URLs to process) and a few labels and align them to the top of the form. Add Memo (to display the Feed XML), ListBox (to contain the title and URL for each article found in the feeds) and WebBrowser (to display the web page when you click on an item in the articles list box) components to the rest of the form.

Main Form
The RSS Feed application’s main form.

To populate the Panel’s listbox, I use a text file, “FeedsList.txt”, which contains a number of RSS feed URLs. The panel listbox is populated in the Form’s OnShow event handler.

Clicking on the button will process all of the RSS feed URLs and add each article and URL item found into the list box of articles found.

The XMLDocument component has a DOMVendor property to select the DOM implementation to use for parsing and manipulating the XML document.

DOMVendor choices

Clicking on an item in the articles list box uses the OnClick event handler to call the WebBrowser Navigate method  for the selected article URL. In C++Builder 10.4 Sydney there is a new property added to the WebBrowser component that lets you choose which browser engine will be used on Windows. I’ve chosen the EdgeIfAvailable engine.


Here is the contents of the FeedsList.txt file:


Here is a bitmap of the running application:

Finally here is the source code for the application:


#include <vcl.h>
#include <fstream>
#pragma hdrstop

#include "MainFeedUnit.h"
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2 *Form2;
__fastcall TForm2::TForm2(TComponent* Owner)
	: TForm(Owner)
void __fastcall TForm2::ArticlesFoundListBoxClick(TObject *Sender)
	// for the ListBox item clicked - get the URL and Browse to the article
	LabelStatus->Caption = ArticlesFoundListBox->Items->Names[ArticlesFoundListBox->ItemIndex];
void __fastcall TForm2::Button1Click(TObject *Sender)
	// Find and save Title and URL for items found
	std::ofstream fs (AnsiString(FormatDateTime("yyyy-mm-dd-hhnnss",Now())+"_RSSFound.txt").c_str());
	fs << AnsiString("RSS Feed for: "+ NetHTTPRequest1->URL).c_str() << std::endl;
	fs << AnsiString(FormatDateTime("dddd mmmm dd, yyyy @ hh:nn:ss",Now())).c_str() << std::endl;
	fs << std::endl;

	// Clear the Articles Found List Box to prepare for the title and URL of articles
	FeedsItemsCountLabel->Caption = "Items Found = 0";

	// get all articles and URLs in all feeds
	for (int i = 0; i < FeedsListBox->Count; i++) {
		// Get the RSS feed URL string from the ListBox
		NetHTTPRequest1->URL = FeedsListBox->Items->Strings[i];

		UrlLabel->Caption = "Feed URL: "+NetHTTPRequest1->URL;

		// Use NetHTTPRequest Execute method to get the RSS Feed XML
		UnicodeString FeedString = NetHTTPRequest1->Execute()->ContentAsString();

		// copy the XML string to the Memo
		MemoFeedXML->Lines->Text = FeedString;

		// load the RSS Feed XML into the XMLDocument
		XMLDocument1->Active = True;

		LabelStatus->Caption = "Processing RSS for "+NetHTTPRequest1->URL;

		// find the RSS feed channel node
		_di_IXMLNode ChannelNode = XMLDocument1->DocumentElement->ChildNodes->FindNode ("channel");
		// test to make sure the ChannelNote is found
		if (ChannelNode != NULL) {
			for (int I=0;I<ChannelNode->ChildNodes->Count;I++) {
				// iterate through child nodes
				_di_IXMLNode ItemNode = ChannelNode->ChildNodes->Get(I);
				// if child node is an item then get the title, pubDate and URL
				if (ItemNode->NodeName == "item") {
					LabelStatus->Caption = "Processing Node " + IntToStr(I);
					UnicodeString title = ItemNode->ChildValues ["title"];
					UnicodeString pubDate = ItemNode->ChildValues ["pubDate"];
					// author := ItemNode.ChildValues ['author'];    // could be nil
					UnicodeString url = ItemNode->ChildValues ["link"];

					// populate the articles found ListBox with the pair of title and URL
					FeedsItemsCountLabel->Caption = "Items Found = "+IntToStr(ArticlesFoundListBox->Count);

					// write the Title, pubDate and URL to the text file
					fs << AnsiString(title).c_str() << std::endl;
					fs << AnsiString(pubDate).c_str() << std::endl;
					fs << AnsiString(url).c_str() << std::endl;
					fs << std::endl;


	fs << std::endl;
	fs << AnsiString("Items Found = "+IntToStr(ArticlesFoundListBox->Count)).c_str() << std::endl;
	fs << "end of file" << std::endl;
	fs.close();   // close the text file
	LabelStatus->Caption = "RSS Processing Done!";
    UrlLabel->Caption = "";
void __fastcall TForm2::FormShow(TObject *Sender)
	// load RSS Feeds ListBox with the "FeedsList.txt" text file
    // I put the text file in the same folder as the app .EXE file
	LabelStatus->Caption = "RSS Feed Urls Loaded = "+IntToStr(FeedsListBox->Count);



Using TXMLDocument

Using the Document Object Model

Using an HTTP Client



Using TEdgeBrowser Component and Changes to the TWebBrowser Component

RSS 2.0 Specification

Download Source Code ZipFile for RSSFeedListsUsingTextFileVCLCpp

C++Builder Product Information

C++Builder Product Page – Native Apps that Perform. Build Windows C++ Apps 10x Faster with Less Code
C++Builder Product Editions – C++Builder is available in four editions – Professional, Enterprise, Architect and Community (free). C++Builder is also available as part of the RAD Studio development suite.

Technology News Worth Reading

Here are a few technology news stories that I’ve read in the past week or so.

News Headlines

Code Partners Acquires SmartInspect from Idera/Gurock

SmartInspect is an advanced .NET logging, Java logging, and Delphi logging tool for debugging and monitoring software applications. It helps customers identify bugs, find solutions to user-reported issues, and gives a precise picture of how software performs in different environments. Read the article by Code Partners. Read the official announcement by Idera/Gurock.

Bill Gates says tech companies ‘deserve rude, unfair, tough questions’

Bill Gates believes tech firms “deserve” the kind of scrutiny they got during Congressional hearings last month. “If you’re as successful as I am or any of those people are, you deserve rude, unfair, tough questions,” the Microsoft founder told host Dax Shepard. “The government deserves to have shots at you,” Gates said. “That type of grilling comes with the super successful territory. It’s fine.” Read the Verge Article.

Scientists use artificial intelligence in new way to strengthen power grid resiliency

At the U.S. Department of Energy’s (DOE) Argonne National Laboratory a research team has developed a novel approach to help system operators understand how to better control power systems with the help of artificial intelligence. Their new approach could help operators control power systems in a more effective way, which could enhance the resilience of America’s power grid, according to a recent article in IEEE Transactions on Power Systems. Read the TechXplore Article.

FBI, CISA Echo Warnings on ‘Vishing’ Threat

“The COVID-19 pandemic has resulted in a mass shift to working from home, resulting in increased use of corporate virtual private networks (VPNs) and elimination of in-person verification,” the alert reads. “In mid-July 2020, cybercriminals started a vishing campaign—gaining access to employee tools at multiple companies with indiscriminate targeting — with the end goal of monetizing the access.” Read the Krebs on Security Article.

How Shopify Reduced Storefront Response Times with a Rewrite

In January 2019, Shopify set out to rewrite the critical software that powers all online storefronts on Shopify’s platform to offer the fastest online shopping experience possible, entirely from scratch and without downtime. Read the Shopify Engineering Blog Article.

Blockchain pet adoptions

Blockchain technology is not limited to cryptocurrencies. There are many other applications that might benefit from such as secure information system. Writing in the International Journal of Blockchains and Cryptocurrencies, a team from India explain how a blockchain might be used in pet adoption. Read the TechXplore Article.

Open source has a people problem

Open source sustainability is really a people problem. Or, as Langel highlights, “In open source, the maintainers working on the source code are the scarce resource that needs to be protected and nurtured.” Read the InfoWorld Article.

Fortnite battle escalates: Apple to terminate developer program membership, Epic files injunction

Epic attempted to lure users to use the new payment system by offering discounts of up to 20% on virtual purchases including the in-game currency V-Bucks on both iOS and Android. Both Google and Apple demand a 30% cut, and once the bypass was introduced, Fornite was removed from both Google Play and Apple’s App Store. Lawsuits have been launched against both tech giants. Epic deems the commission rate as “oppressive” and despite trying to use the massive Fortnite customer base as leverage — alongside some rather intense public mockery — the row now has the potential to severely impact iOS developers. Read the ZDNet Article.

How to disagree with your boss without losing your cool… or job

It doesn’t have to be this way though. You can totally express your opinion to your boss or manager without losing your cool. This post contains some of the scenarios where speaking up would be justified. Read the TNW Article.

Engineers set new world record internet speed

Working with two companies, Xtera and KDDI Research, the research team led by Dr. Lidia Galdino (UCL Electronic & Electrical Engineering), achieved a data transmission rate of 178 terabits a second (178,000,000 megabits a second) – a speed at which it would be possible to download the entire Netflix library in less than a second. Read the TechXplore Article.

Roberto V. Zicari interviews Bjarne Stroustrup, the inventor of C++ programming language

Roberto V. Zicari interviewed Bjarne Stroustrup, the inventor of C++ programming language, back in 2007. Roberto again interviews Bjarne 13 years later.

In the interview, Bjarne talks about notable computer scientists that influenced his career and work. Bjarne also talks about why he designed the C++ language and why he started with the C language. Bjarne also talks about three guiding principles for the design of the C++ language: “Make the language simpler! Add these two essential features now!! Don’t break (any of) my code!!!”

Read the interview on the Roberto’s ODBMS.ORG site.

My Conversations with Bjarne Stroustrup

I’ve also had two opportunities to talk live online with Bjarne about the C++ language during past Embarcadero CodeRage online conferences:

A Conversation with the C++ language designer, Bjarne Stroustrup
Monday, December 10, 2012
C++ Language Conversation with Bjarne Stroustrup and David Intersimone
Tuesday, December 4, 2018


ODBMS.ORG is designed to meet the fast-growing need for resources focusing on AI, Big Data, Data Science, Analytical Data Platforms, Scalable Cloud platforms, NewSQL databases, NoSQL datastores, In-Memory Databases, and new approaches to concurrency control.

About Roberto Zicari

Roberto is Full Professor of Database and Information Systems at Frankfurt University. He was for over 15 years the representative of the OMG in Europe. Previously, Roberto served as associate professor at Politecnico di Milano, Italy; Visiting scientist at IBM Almaden Research Center, USA, the University of California at Berkeley, USA; Visiting professor at EPFL in Lausanne, Switzerland, the National University of Mexico City, Mexico and the Copenhagen Business School, Danemark.

About Bjarne Stroustrup

Bjarne is a Technical Fellow and a Managing Director in the technology division of Morgan Stanley in New York City and a Visiting Professor in Computer Science at Columbia University. Bjarne designed and implemented the C++ programming language. To make C++ a stable and up-to-date base for real-world software development, Bjarne says “I have stuck with its ISO standards effort for almost 30 years (so far).”

Bjarne Stroustrup’s homepage

Using C++Builder to list all available VCL styles in a ComboBox and apply a selected style using the ComboBoxChange event

Back in June a developer asked a C++Builder question on StackOverflow. The question was “How can I list all the available VCL styles in a combo box and in the ComboBoxChange event, apply that style in C++ Builder?” I answered the question and gave the example code.

One of my favorite RTL features for the VCL and FMX frameworks is the ability to customize the look and feel of your applications using Styles. The first step is to create a C++Builder VCL project and select a few of the VCL Styles in the Project | Options | Application | Appearance settings. The C++Builder 10.4 Sydney DocWiki explains that “the VCL Styles architecture has been significantly extended to support High-DPI graphics and 4K monitors. In 10.4 Sydney all graphical elements are automatically scaled for the proper resolution of the monitor the element is displayed on. This means that the scaling depends on the DPI resolution of the target computer or the current monitor, in case of multi-monitor systems.”

The C++ Application User Interface

For the application user interface I have a TButton (has code to populate the ComboBox with selected application styles) and a TComboBox (to display and allow selection of a style).

The C++ code


#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
#include <Vcl.Themes.hpp>
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
void __fastcall TForm1::Button1Click(TObject *Sender)
	// populate the ComboBox with VCL styles that are selected
	//    in Project | Options | Application | Appearance

		DynamicArray<String> styleNames = Vcl::Themes::TStyleManager::StyleNames;

        for(int i = 0; i < styleNames.Length; ++i)
            String styleName = styleNames[i];
void __fastcall TForm1::ComboBox1Change(TObject *Sender)
	// set the style for the selected combobox item


The Application in Action

TComboBox populated with VCL styles selected
Application Style Changed by TComboBox selection


VCL Styles Overview

Project Options Application Appearance

VCL Styles Support for High-DPI Graphics

C++Builder Product Information

C++Builder Product Page – Native Apps that Perform. Build Windows C++ Apps 10x Faster with Less Code
C++Builder Product Editions – C++Builder is available in four editions – Professional, Enterprise, Architect and Community (free). C++Builder is also available as part of the RAD Studio development suite.

Multithreaded Sorting with C++Builder and the Parallel Programming Library (PPL)

The Parallel Programming Library (PPL) is one of my favorite features in C++Builder runtime library. PPL allows developers to create tasks that run in parallel to take advantage of multi-core processors.

Using the PPL, you can: 1) speed up loops with a Parallel For, 2) run multiple tasks in parallel using TTask, and 3) use Future Objects to allow a process run with your program focused on other work until the future value is set.

To showcase the TTask feature of the PPL, I’ve created a C++Builder VCL application (build and tested using the C++Builder 10.4 Sydney release) that runs three sort algorithms in separate tasks – Bubble Sort, Shell Sort and the ISO C++ standard Sort (which implements the Quicksort algorithm).

The User Interface

The VCL user interface for my application includes a TButton, two TMemos, and four TLabels. The TButton onClick event handler creates a vector of integers, creates three TTasks (for the sort algorithms) and waits for the sort tasks to complete using the TTask::WaitForAll method.

The Code


#ifndef MainUnitH
#define MainUnitH
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.ExtCtrls.hpp>
class TForm1 : public TForm
__published:	// IDE-managed Components
	TButton *Button1;
	TLabel *SortingStatusLabel;
	TLabel *BubbleSortLabel;
	TMemo *Data_Memo;
	TMemo *SortResult_Memo;
	TLabel *ShellSortLabel;
	TLabel *STDSortLabel;
	void __fastcall Button1Click(TObject *Sender);
private:	// User declarations
public:		// User declarations
	__fastcall TForm1(TComponent* Owner);
extern PACKAGE TForm1 *Form1;



#include <vcl.h>
#include <System.Threading.hpp>
#include <vector>
#include <algorithm>
#pragma hdrstop

#include "MainUnit.h"
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
void __fastcall TForm1::Button1Click(TObject *Sender)

	_di_ITask My_Tasks[3];
	const int max_data = 15000;   // number of random numbers to create

	int LoopValue = 0;

	Button1->Enabled = false;
	BubbleSortLabel->Caption = "Bubble Sort";
	ShellSortLabel->Caption = "Shell Sort";
	STDSortLabel->Caption = "std::sort";

	SortingStatusLabel->Caption = "Sorting "+IntToStr(max_data)+" integers!";

	// Windows GetTicks() start and stop for each sort method
	int StartBubble,StopBubble;
	int StartShell,StopShell;
	int StartSTD,StopSTD;


	// create a vector of data that all sort algorithms will use
	std::vector<int> my_data;

	// populate the vector with integers
	for (int i = 1; i <= max_data; i++) {
		int random_value = Random(max_data);
		// Data_Memo->Lines->Add(IntToStr(random_value));

	// copy data vector to sort vectors
	std::vector<int> bubble_data = my_data;
	std::vector<int> shell_data = my_data;
	std::vector<int> std_data = my_data;

	// First Task - Bubble Sort
	My_Tasks[0] = TTask::Create([&](){
		// Set Bubble Sort Windows GetTickCount()
		StartBubble = GetTickCount();
		// body of Bubble Sort
		bool swapp = true;
			swapp = false;
			for (size_t i = 0; i < bubble_data.size()-1; i++) {
				if (bubble_data[i]>bubble_data[i+1] ){
					bubble_data[i] += bubble_data[i+1];
					bubble_data[i+1] = bubble_data[i] - bubble_data[i+1];
					bubble_data[i] -=bubble_data[i+1];
					swapp = true;
		// Set the Bubble Sort Stop GetTicks()
		StopBubble = GetTickCount();
	// Start the Bubble Sort Task

	// Second Task - Shell Sort
	My_Tasks[1] = TTask::Create([&](){
		// Set Shell Sort Windows GetTickCount()
		StartShell = GetTickCount();
		// body of the Shell Sort
		for (int gapSize = shell_data.size() / 2; gapSize > 0; gapSize /= 2) {
			for (int currentIndex = gapSize; currentIndex < shell_data.size(); currentIndex++) {
				// save the currentIndex
				int currentIndexCopy = currentIndex;
				// save the value of the currentIndex
				int item = shell_data[currentIndex];
				while (currentIndexCopy >= gapSize && shell_data[currentIndexCopy - gapSize] > item) {
					shell_data[currentIndexCopy] = shell_data[currentIndexCopy - gapSize];
					currentIndexCopy -= gapSize;
				shell_data[currentIndexCopy] = item;
		// Set the Shell Sort Stop GetTicks()
		StopShell = GetTickCount();
	// Start the Shell Sort

	// Third Task - std::sort
	My_Tasks[2] = TTask::Create([&](){
		// Set std::sort Windows GetTickCount()
		StartSTD = GetTickCount();
		// Body of the std::sort
		// Set the std::sort Stop GetTicks()
		StopSTD = GetTickCount();
	// Start the Shell Sort

	// wait until all of the sorting tasks complete
	TTask::WaitForAll(My_Tasks, sizeof(My_Tasks)/sizeof(My_Tasks[0])-1);

	SortingStatusLabel->Caption = "Sorting All done!";

	BubbleSortLabel->Caption = "Bubble Sort Time: "
		+ IntToStr(StopBubble - StartBubble)
		+ " ms";

	ShellSortLabel->Caption = "Shell Sort Time: "
		+ IntToStr(StopShell - StartShell)
		+ " ms";

	STDSortLabel->Caption = "std::sort: "
		+ IntToStr(StopSTD - StartSTD)
		+ " ms";

	// if you want to see the sort results un-comment
	// one of the for loops and the sort result memo statement
	// for(int n : std_data) {
	// for(int n : bubble_data) {
	// for(int n : shell_data) {
		// SortResult_Memo->Lines->Add(IntToStr(n));
	// }

	// clear the vectors

	Button1->Enabled = true;

The form after sorting 15,000 integers


PPL – Parallel Programming Library – http://docwiki.embarcadero.com/RADStudio/Sydney/en/Using_the_Parallel_Programming_Library

Using TTask – http://docwiki.embarcadero.com/RADStudio/Sydney/en/Using_TTask_from_the_Parallel_Programming_Library

Using TParallel::For – http://docwiki.embarcadero.com/RADStudio/Sydney/en/Using_TParallel.For_from_the_Parallel_Programming_Library

Using TTask::IFuture – http://docwiki.embarcadero.com/RADStudio/Sydney/en/Using_TTask.IFuture_from_the_Parallel_Programming_Library

Algorithms Library – https://en.cppreference.com/w/cpp/algorithm

std::sort – https://en.cppreference.com/w/cpp/algorithm/sort

C++Builder Product Information

C++Builder Product Page – Native Apps that Perform. Build Windows C++ Apps 10x Faster with Less Code
C++Builder Product Editions – C++Builder is available in four editions – Professional, Enterprise, Architect and Community (free). C++Builder is also available as part of the RAD Studio development suite.