text stringlengths 1 2.12k | source dict |
|---|---|
c#
Title: Console application that can find and run certain exe
Question: I want to make small console application that can find and run certain exe. This works, however it is extremely slow in given situations. Any Idea how can i improve this?
string[] drives = Directory.GetLogicalDrives();
string pathToExecutable = String.Empty;
foreach (string drive in drives)
{
pathToExecutable =
Directory.EnumerateFiles(drive, "vlc.exe",
new EnumerationOptions
{
IgnoreInaccessible = true,
RecurseSubdirectories = true
}
)
.FirstOrDefault();
if (!String.IsNullOrEmpty(pathToExecutable))
{
break;
}
}
if (String.IsNullOrEmpty(pathToExecutable))
{
// We did not find the executable.
Console.WriteLine("We did not find the executable!");
}
else
{
// We found the executable. Now we can start it.
Console.WriteLine("We found the executable. Now we can start it");
var proc = new Process();
proc.StartInfo.FileName = pathToExecutable;
proc.Start();
proc.WaitForExit();
var exitCode = proc.ExitCode;
proc.Close();
}
Answer: Let's get the code review out of the way. Your style, casing, and object naming are decent. I take some small issue with some indentation, but that's a matter of style.
However, your Comments are utterly useless.
// We did not find the executable.
Console.WriteLine("We did not find the executable!"); | {
"domain": "codereview.stackexchange",
"id": 44114,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
Clean code can tell us what you are doing so a comment that does the same is repetitive. Comments should be for why you are doing something. Even here, the why is implicitly known from the code.
You may consider using string.IsNullOrWhiteSpace instead of String.IsNullOrEmpty.
On to what you really are looking for ...
How can performance be improved?
First of all, let's acknowledge that you are performing a crawl over a logical drive that either ends when you find what you or looking for, or else the entire drive has been crawled over. Do not expect performance to be great.
As mentioned in the comments, parallelizing the drive searches can maybe speed things up, as long as the logical drives exist on different physical drives. There is a way to check for this, but I am not going into that.
One alternative for better performance the 2nd time around would be to persist the path the first time you find it. For completeness, you would need to save this per user per host. Maybe on your home PC, you would think the drives are common for everyone in the home, but for a work computer, the attached network shares mapped as logical drives can vary per user per host. The notion of a persisted appsetting is that you would first check the last known path, and if it is found, you have no need to crawl over anything.
Another alternative is to assign the path once it is found to the PATH Environment variable. Note: PATH itself is set automatically per user per host. You would then search on each directory in PATH but do not recurse subdirectories.
A similar alternative would be to create a new Environment variable, e.g. PathToVlcExe. One the path has been found with a sluggish crawl and this setting has been saved, the next execution you would first check to see if that path is
still valid, in which case you skip the crawl. | {
"domain": "codereview.stackexchange",
"id": 44114,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
still valid, in which case you skip the crawl.
Each alternative is dependent upon performing a very sluggish crawl the first time. Unless you think that vlc.exe should be somewhere along a known Environment PATH, in which case you should limit the search to Environment PATH, again without recursing subdirectories.
Yet another alternative would be to somehow narrow down the path to vlc.exe. If you knew it was going to be either in "?:\Program Files (x86)?????" or "?:\Program Files?????", then you could greatly speed up the search. As we know, an executable does not have to be installed into any of the Program Files folders, but the downside is what you are now experiencing: horrically slow search times as you crawl over a logical drive. | {
"domain": "codereview.stackexchange",
"id": 44114,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
bash, linux, shell, ksh
Title: Archive, compress, remove old archive file then remove source file if below set size
Question: I'm working on a script that will archive, compress, clear old archive files, then remove the source file if it is below a set size. The output when I tested it worked, but I just wanted a second look to make sure I'm not missing any issues.
#!/usr/bin/ksh
# Script Name: archiving.ksh
# Purpose : To copy and Archive the files
# $1 = Source file name pattern with fully qualified path
#-------------------------------------------------------------------------------------------------
#set -xv
sourcedir=$1
filename_pattern=$2
arcdir=/busdata/data/archive
filename=`ls $sourcedir/$filename_pattern*`
file_basename=`basename $filename`
echo $sourcedir
echo $arcdir
echo $filename_pattern
echo $filename
echo $file_basename
echo "Copying $filename to ${arcdir}"
cp $filename ${arcdir}/${file_basename}_$(date +%Y%m%d%H%M%S)
compress ${arcdir}/$file_basename*
echo "Removing files that are more than 30 days old from ${arcdir}"
find ${arcdir} -mtime +15 -type f -exec rm -f {} \;
echo "Remove empty file"
find ${sourcedir} . -name "858_file_*.exp" -type 'f' -size -160k -exec rm -f {} \;
Answer: I would make the following changes to the script for clarity and ease of use by others:
#!/usr/bin/ksh
# Script Name: archiving.ksh
# Purpose : To copy and archive the specified files
# $1 = Fully qualified source directory for the script to run from
# $2 = Source file name pattern
#-------------------------------------------------------------------------------------------------
# set -xv
if [ "$#" -ne 2 ]; then
echo >&2 "Illegal number of parameters passed to the script!"
exit 1
fi
sourcedir="$1"
filename_pattern="$2"
arcdir="/busdata/data/archive"
filename=`ls $sourcedir/$filename_pattern*`
file_basename=`basename $filename`
echo "$sourcedir"
echo "$arcdir"
echo "$filename_pattern"
echo "$filename"
echo "$file_basename" | {
"domain": "codereview.stackexchange",
"id": 44115,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, linux, shell, ksh",
"url": null
} |
bash, linux, shell, ksh
echo "$sourcedir"
echo "$arcdir"
echo "$filename_pattern"
echo "$filename"
echo "$file_basename"
echo "Copying $filename to ${arcdir}..."
cp "$filename" "${arcdir}/${file_basename}_$(date +%Y%m%d%H%M%S)"
compress "${arcdir}/$file_basename"*
echo "Removing files that are more than 30 days old from ${arcdir}..."
find "${arcdir}" -mtime +15 -type f -exec rm -f {} \;
echo "Removing empty files..."
find "${sourcedir}" . -name "858_file_*.exp" -type 'f' -size -160k -exec rm -f {} \;
The first change is enforcing the expected number of script parameters, so the code doesn't behave unexpectedly if fewer parameters are given. The syntax is explained here if you are unfamiliar.
The next step is quoting all shell variables wherever possible for type safety, it's considered a best practice when you aren't sure what values will be passed. More information about this can be found in this thread.
Outside of these changes I don't see anything that throws up any red flags in your code, it looks like it will do what is expected from it and nothing more/less. | {
"domain": "codereview.stackexchange",
"id": 44115,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, linux, shell, ksh",
"url": null
} |
php, datetime, formatting
Title: Formatting date difference in human-friendly terms
Question: I've written a function to take the difference between two dates and display it in a particular format. I've used a lot of if-else statements, which seems a little messy. Is there a way to shorten this up? Would using the ternary operator make sense?
$date1 = '2018-04-30 10:36:29';
$date2 = '2018-04-30 10:35:29';
echo dateDiff($date1, $date2);
function dateDiff($date1, $date2)
{
$date_1 = new DateTime($date1);
$date_2 = new DateTime($date2);
$diff = $date_1->diff($date_2);
if($diff->days > 365){
return $date_1->format('Y-m-d');
}
elseif($diff->days < 366 AND $diff->days > 7){
return $date_1->format('M d');
}
elseif($diff->days > 2 AND $diff->days < 8){
return $date_1->format('L - H:i');
}
elseif($diff->days == 2) return "Yesterday ".$date_1->format('H:i');
elseif($diff->days < 2 AND $diff->days > 0 OR $diff->days == 0 AND $diff->h > 1) return $date_1->format('H:i');
elseif($diff->days == 0 AND $diff->h < 1 AND $diff->i >= 1) return $diff->i." min ago";
elseif($diff->days == 0 AND $diff->h < 1 AND $diff->i < 1) return "just now";
else return $error = "Error!";
}
Answer: Chained ternary expressions in PHP are a major pain in the ass — don't use them!
You have a lot of tests that are redundant, since earlier tests will have already eliminated longer periods. The error case at the end also seems pointless.
Use consistent indentation and braces for readability and safety — please don't skimp.
function dateDiff($date1, $date2)
{
$date_1 = new DateTime($date1);
$date_2 = new DateTime($date2);
$diff = $date_1->diff($date_2); | {
"domain": "codereview.stackexchange",
"id": 44116,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, datetime, formatting",
"url": null
} |
php, datetime, formatting
if ($diff->days > 365) {
return $date_1->format('Y-m-d');
} elseif ($diff->days > 7) {
return $date_1->format('M d');
} elseif ($diff->days > 2) {
return $date_1->format('L - H:i');
} elseif ($diff->days == 2) {
return "Yesterday ".$date_1->format('H:i');
} elseif ($diff->days > 0 OR $diff->h > 1) {
return $date_1->format('H:i');
} elseif ($diff->i >= 1) {
return $diff->i." min ago";
} else {
return "Just now";
}
}
Be sure to use consistent capitalization for "yesterday" and "just now". | {
"domain": "codereview.stackexchange",
"id": 44116,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, datetime, formatting",
"url": null
} |
php, strings
Title: Formatting Credit card names from API response
Question: I have an API that returns the brand of a credit card. I want to make them look nice for my user (e.g. correct case and spacing). The possible options are amex, diners, discover, jcb, mastercard, unionpay, visa, or unknown. Here's how I am currently doing it:
if ($x == "jcb") {
$x = strtoupper($x);
} elseif ($x == "amex"){
$x = "American Express";
} elseif ($x == "diners"){
$x = "Diners Club";
} elseif ($x == "unionpay"){
$x = "UnionPay";
} else {
$x = ucfirst($x);
}
Is there a more efficient way of doing this?
Answer: the code looks a bit messy. Personally I would make it either an array lookup,
$card_trans = [
"jcb" => "JCB",
"amex" => "American Express",
"diners" => "Diners Club",
"unionpay" => "UnionPay",
];
$card = $card_trans[$card] ?? ucfirst($card);
or a match expression available with PHP 8+:
$card = match ($card) {
"jcb" => "JCB",
"amex" => "American Express",
"diners" => "Diners Club",
"unionpay" => "UnionPay",
default => ucfirst($card),
}; | {
"domain": "codereview.stackexchange",
"id": 44117,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, strings",
"url": null
} |
python, django
Title: Filter based on different criteria until a match is found
Question: We get the most relevant feedback about a doctor depending on the speciality, intervention_type and sub_intervention_type a patient is going to use.
The ordering is important here, we match feedback on speciality and sub_intervention_type first. If that's not available, try less specific matches.
I wonder if there is a better/prettier way to do this.
I thought about having each condition (e.g. feedback.intervention_type == intervention_type) as a method of a class.
def get_feedback_condition_method_names(self):
return [method_name for method_name in dir(self) if method_name.startswith("feedback_condition")]
We could then loop through get_feedback_condition_method_names() and execute the methods in a loop. This way it's easy to add additional conditions, but we probably won't need to add additional conditions, so the below "functional" would be OK and the above would be overkill. Feedback welcome.
Code for review:
def get_doctor_feedback(*, doctor, speciality, intervention_type, sub_intervention_type):
feedbacks = DoctorFeedback.objects.filter(doctor=doctor)
result = [
feedback for feedback in feedbacks
if feedback.speciality == speciality and feedback.sub_intervention_type == sub_intervention_type
]
if not result:
result = [
feedback for feedback in feedbacks
if feedback.sub_intervention_type == sub_intervention_type
]
if not result:
result = [
feedback for feedback in feedbacks
if feedback.intervention_type == intervention_type
]
if not result:
result = [
feedback for feedback in feedbacks
if feedback.speciality == speciality
]
if not result:
result = feedbacks
if not result:
return doctor.default_feedback
return result.sort(key=lambda feedback: feedback.rating) | {
"domain": "codereview.stackexchange",
"id": 44118,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, django",
"url": null
} |
python, django
Answer: You can use Python's or operator to chain the feedback result candidates and return the first non-empty list:
def get_doctor_feedback(*, doctor, speciality, intervention_type, sub_intervention_type):
feedbacks = DoctorFeedback.objects.filter(doctor=doctor)
result = get_feedback_by_priority(
feedbacks,
speciality=speciality,
intervention_type=intervention_type,
sub_intervention_type=sub_intervention_type
)
if not result:
return doctor.default_feedback
return sorted(result, key=lambda feedback: feedback.rating)
def get_feedback_by_priority(
feedbacks,
*,
speciality,
intervention_type,
sub_intervention_type
):
"""Return first matching feedback list."""
return [
feedback for feedback in feedbacks
if feedback.speciality == speciality
and feedback.sub_intervention_type == sub_intervention_type
] or [
feedback for feedback in feedbacks
if feedback.sub_intervention_type == sub_intervention_type
] or [
feedback for feedback in feedbacks
if feedback.intervention_type == intervention_type
] or [
feedback for feedback in feedbacks
if feedback.speciality == speciality
] or feedbacks
And since the list comprehensions only differ by their condition, we can simplify this to:
def get_feedback_by_priority(
feedbacks,
*,
speciality,
intervention_type,
sub_intervention_type
):
"""Return first matching feedback list.""" | {
"domain": "codereview.stackexchange",
"id": 44118,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, django",
"url": null
} |
python, django
for condition in [
lambda feedback: (
feedback.speciality == speciality
and feedback.sub_intervention_type == sub_intervention_type
),
lambda feedback: feedback.sub_intervention_type == sub_intervention_type,
lambda feedback: feedback.intervention_type == intervention_type,
lambda feedback: feedback.speciality == speciality
]:
if candidate := [
feedback for feedback in feedbacks
if condition(feedback)
]:
return candidate
return feedbacks | {
"domain": "codereview.stackexchange",
"id": 44118,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, django",
"url": null
} |
java, algorithm
Title: Get objects from list based on object's field
Question: I have a method which takes List<Document> documents as parameters.
I created unit test for it:
@Test
public void getDocumentsWithHighestVersion(){
List<Document> docs = new ArrayList<>();
Type type1 = new Type(PDF, ENGLISH);
docType1.setDocumentTypeId(37);
Type type2 = new Type(PDF, ENGLISH);
type2.setDocumentTypeId(31);
Document doc1 = new Document(1, "name", type1, 7);
Document doc2 = new Document(2, "name", type2, 7);
Document doc3 = new Document(5, "name", type1, 4);
Document doc4 = new Document(6, "name", type2, 4);
Document doc5 = new Document(8, "name", type1, 1);
Document doc6 = new Document(9, "name", type2, 1);
docs.add(doc1);
docs.add(doc2);
docs.add(doc3);
docs.add(doc4);
docs.add(doc5);
docs.add(doc6);
List<Document> docsWithHighestVersion = underTest.getDocsWithHighestVersion(docs);
assertTrue(docsWithHighestVersion.contains(doc1));
assertTrue(docsWithHighestVersion.contains(doc2));
assertTrue(!docsWithHighestVersion.contains(doc3));
assertTrue(!docsWithHighestVersion.contains(doc4));
assertTrue(!docsWithHighestVersion.contains(doc5));
assertTrue(!docsWithHighestVersion.contains(doc6));
}
so here we have documents with types 31 and 34. The task is to find the document with highest version for every type. So correct answer is doc1 and doc2 because they have version 7.
I created method which seems to work but it looks awful:
protected List<Document> getDocsWithHighestVersion(List<Document> documents) {
Map<Integer, Document> docsWithHigherVersion = new HashMap<>();
int numOfDocs = documents.size(); | {
"domain": "codereview.stackexchange",
"id": 44119,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm",
"url": null
} |
java, algorithm
for (int i = 0; i < numOfDocs - 1; i++) {
for (int j = i + 1; j < numOfDocs; j++) {
if (documents.get(i).getType().equals(documents.get(j).getType())) {
Document docWithHigherVersion = documents.get(i).getVersion() > documents.get(j).getVersion() ? documents.get(i) : documents.get(j);
if (docsWithHigherVersion.containsKey(docWithHigherVersion.getType().getTypeId())) {
if(docsWithHigherVersion.get(docWithHigherVersion.getType().getTypeId()).getVersion() < docWithHigherVersion.getVersion()){
docsWithHigherVersion.put(docWithHigherVersion.getType().getTypeId(), docWithHigherVersion);
}
} else {
docsWithHigherVersion.put(docWithHigherVersion.getType().getTypeId(), docWithHigherVersion);
}
}
}
}
return new ArrayList<>(docsWithHigherVersion.values());
}
How can I make it readable? I am sure there must exists some prettier solution even without streams. I would like to see streams solution also but for above problem I am not allowed to use it.
Answer: I don't quite understand why you have two loops there. One would do just fine.
protected List<Document> getDocsWithHighestVersion(List<Document> documents) {
Map<Integer, Document> highestVersionDocumentsByTypeId = new HashMap<>();
int documentsCount = documents.size(); | {
"domain": "codereview.stackexchange",
"id": 44119,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm",
"url": null
} |
java, algorithm
for (int i = 0; i < documentsCount; i++) {
Document document = documents.get(i);
Integer documentTypeId = document.getType().getTypeId();
if (highestVersionDocumentsByTypeId.containsKey(documentTypeId)) {
if (document.getVersion() < highestVersionDocumentsByTypeId.get(documentTypeId).getVersion(){
continue;
}
}
highestVersionDocumentsByTypeId.put(documentTypeId, document);
}
return new ArrayList<>(highestVersionDocumentsByTypeId.values());
}
```` | {
"domain": "codereview.stackexchange",
"id": 44119,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm",
"url": null
} |
python
Title: Check if a function can take a certain argument, positional or keyword, in Python
Question: from inspect import signature, Parameter
def check_can_take_positional_arg(fun, arg_ix):
params = signature(fun).parameters.values()
return len(params) >= arg_ix + 1 or any(
param.kind == Parameter.VAR_POSITIONAL for param in params
)
def check_can_take_keyword_arg(fun, arg_key):
params = signature(fun).parameters.values()
return any(
param.kind == Parameter.VAR_KEYWORD
or (
param.kind in [Parameter.KEYWORD_ONLY, Parameter.POSITIONAL_OR_KEYWORD]
and param.name == arg_key
)
for param in params
)
Can something be improved about this code?
Answer: One thing that would hugely improve it is a comprehensive test suite. Maybe you have that and just haven't shown it, but if not this is exactly the sort of fiddly code which rewards systematic automated testing.
In particular in writing such tests, you'd want to check
def foo(): Functions with no parameters
def foo(a, b, /): Functions with positional only arguments
def foo(a, *, b): Functions with keyword only arguments and no *args.
def foo(self, a, b): Methods
Combinations of the above.
I think that third case (keyword only) may fail at the moment, in the direction of falsely promising to accept a positional parameter for b.
Based on your comment about the purpose, it may also be necessary to test the interaction of multiple calls. For example, What happens if you try to curry out parameter 1 and 2, but after the first step there aren't two positions left open? What happens if the same parameter is picked out by position and by keyword? How does that change if there is also a **kwargs parameter ready to grab any excess?
Beyond prodding at edge cases, I'd have a few minor thoughts which are very much stylistic. | {
"domain": "codereview.stackexchange",
"id": 44120,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
It feels odd to see >= paired with a + 1, instead of just using >.
What happens if someone gives a negative arg_ix value?
Parameter.VAR_POSITIONAL and friends are enums. Although the examples in the docs don't bother with this, there are some advantages to using is rather than == for comparing Enums and the docs say that "Enum members are compared by identity".
For code devoted to checking whether parameters are legal, it may be worthwhile (or at least poetically appropriate!) to add type annotations.
Overall, this seems like quite clean code taken in a sensible sort of direction. | {
"domain": "codereview.stackexchange",
"id": 44120,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
c++, performance, reinventing-the-wheel
Title: Find the modal value of a sample of numbers
Question: I am currently interested in implementing statistical measures. Other measures like mean, variance, and covariance are easy, but the mode feels harder than I thought. Is this good enough?
Note: float is used because I don't really intend to use it on big enough numbers. The size can be changed if needed.
Note 2: We cannot use vectors, any statistical related functions, and any other tool that can impact the performance of the code. What we can use though, are basic data types (int, float, double, bool, char, and the long, short, and unsigned versions) and simple conditional and looping structures. To add, the auto keyword is not allowed.
Probably unrelated, but still relevant: Why did I use "we" instead of "I" in the second note?
I'm still learning C++ in school, so I am limiting myself to what we can do in school even though it can really improve the performance.
#include <iostream>
using std::cout;
using std::cin;
int main () {
int N, uniques = 0, j = 0;
// N: number of elements; uniques: unique elements in list; j: list index
cin >> N;
float list[N], counters[N][2];
// list[N]: the list of elements
// counters[N][2]: the list of unique elements and the number of appearances
bool found = false;
for (int i = 0; i < N; i++) {
cin >> list[i];
found = false;
for (j = 0; j < uniques; j++) {
if (counters[j][0] == list[i]) {
counters[j][1]++;
found = true;
break;
}
}
if (!found) {
counters[uniques][0] = list[i];
counters[uniques][1] = 1;
uniques++;
}
}
int max = counters[0][1], ind = 0, reps = 0; | {
"domain": "codereview.stackexchange",
"id": 44121,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel",
"url": null
} |
c++, performance, reinventing-the-wheel
for (int k = 0; k < uniques; k++) {
if (max == counters[k][1]) {
reps++;
} else if (max < counters[k][1]) {
ind = k, max = counters[k][1];
reps = 1;
}
}
if (reps == 1) {
cout << "The mode of the data set is " << counters[ind][0] << " appearing " << max << " times";
} else {
cout << "undetermined " << reps;
}
return 0;
}
I added comments about the variable names.
Answer: Here are some ideas to help you improve your code, and perhaps inspire you to learn more.
Reconsider using
The code currently contains these two lines:
using std::cout;
using std::cin;
That's not too terrible, but there are at least two ways to make it better. First would be to put those inside main to limit any possible conflicts there instead of globally. Better, in my view, would be to simply omit them and use std::cin and std::cout since they're only used in three lines in your entire program. That way readers will instantly see that you're using the std:: versions and not some other version.
Decompose your program into functions
All of the logic here is in main in one dense chunk of code. It would be better to decompose this into a separate function or functions.
Avoid non-standard features
Others have mentioned this, but declaring an array with anything other than a compile-time number is not in standard C++ and so that should be avoided. I hope your teacher isn't writing C++ code like this!
Use modern C++ features
It is very likely you haven't learned about std::ranges or various other algorithms and data structures yet, but just to whet your appetite, here's a rewrite of your program using C++20 and all of the tools in the toolbox:
#include <iostream>
#include <map>
#include <ranges>
#include <algorithm> | {
"domain": "codereview.stackexchange",
"id": 44121,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel",
"url": null
} |
c++, performance, reinventing-the-wheel
int main () {
using myDataType = float;
using myMapType = std::map<myDataType, unsigned>;
myDataType value;
myMapType counts;
int N;
for (std::cin >> N; N && std::cin >> value; --N) {
++counts[value];
}
auto mode = std::ranges::max_element(counts,{},&myMapType::value_type::second);
std::cout << "The mode of the data set is " << mode->first
<< " appearing " << mode->second << " times\n";
}
Use a more efficient algorithm
It's good to learn how to write your own code, but given your restrictions, your options are somewhat limited. Here's a suggestion for an alternative implementation that is somewhat more efficient, expressed in psuedo-code:
create "big enough" arrays for data and count
initialize overall item count and max element index to 0
for each read value:
linearly search the data array for a matching value
if it's new, add it to the array and set the count to 1 and increment the overall unique item count
otherwise, it's not new so increment the count and compare to current max element index (updating the latter as appropriate)
At the end of this, the max element index will point to the index of the mode value and its associated count. | {
"domain": "codereview.stackexchange",
"id": 44121,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel",
"url": null
} |
c++, object-oriented, matrix, iterator, lambda
Title: 2D Matrix in C++
Question: I wanted to play with a two-dimensional generic data container in C++ and explore different methods of traversals: using closures and iterators. I'd like a review of it.
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>
template <typename T>
class Matrix {
using array = std::vector<T>;
using size = std::size_t;
array data;
size rows_;
size cols_;
public:
Matrix(size rows, size cols)
: data(cols * rows), rows_{rows}, cols_{cols} {}
T &operator()(size row, size col) { return data[row * cols_ + col]; }
const T &operator()(size row, size col) const {
return data[row * cols_ + col];
}
int rows() const { return rows_; }
int cols() const { return cols_; }
void traverse(std::function<void(T &)> f) {
for (auto &el : data) f(el);
}
void traverse(std::function<void(T &)> f, size row, size col) {
for (auto &[rd, cd] : neighbours_delta) {
int r = row + rd, c = col + cd;
if (r >= 0 && r < rows_ && c >= 0 && c < cols_) f((*this)(r, c));
}
}
typename array::iterator begin() { return data.begin(); }
typename array::iterator end() { return data.end(); }
auto neighbours(size row, size col) {
return NeighbourIterator(row, col, *this);
}
friend std::ostream &operator<<(std::ostream &os, const Matrix &m) {
for (int row = 0; row < m.rows_; ++row) {
for (int col = 0; col < m.cols_; ++col) {
os << m(row, col) << " ";
}
os << std::endl;
}
return os;
}
protected:
std::pair<int, int> neighbours_delta[8] = {
{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; | {
"domain": "codereview.stackexchange",
"id": 44122,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, matrix, iterator, lambda",
"url": null
} |
c++, object-oriented, matrix, iterator, lambda
struct NeighbourIterator {
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T *;
using reference = T &;
NeighbourIterator(size row, size col, Matrix<T> &m, int neighbor = 0)
: row{row}, col{col}, m{m}, neighbor{neighbor} {}
auto get_delta() const { return m.neighbours_delta[neighbor]; }
bool exists() {
auto [rd, cd] = get_delta();
int r = row + rd, c = col + cd;
return r >= 0 && r < m.rows_ && c >= 0 && c < m.cols_;
}
T &get_neighbor() const {
auto [rd, cd] = get_delta();
return m(row + rd, col + cd);
}
reference operator*() const { return get_neighbor(); }
pointer operator->() { return get_neighbor(); }
NeighbourIterator &operator++() {
do {
neighbor++;
} while (neighbor < 8 && !exists());
return *this;
}
NeighbourIterator operator++(int) {
NeighbourIterator tmp = *this;
++(*this);
return tmp;
}
auto begin() { return NeighbourIterator(row, col, m, 0); }
auto end() { return NeighbourIterator(row, col, m, 8); }
friend bool operator==(const NeighbourIterator &a,
const NeighbourIterator &b) {
return a.neighbor == b.neighbor;
};
friend bool operator!=(const NeighbourIterator &a,
const NeighbourIterator &b) {
return a.neighbor != b.neighbor;
};
private:
Matrix<T> &m;
size row, col;
int neighbor;
};
};
int main() {
Matrix<int> m(10, 10);
// Can use STL algorithms
std::fill(m.begin(), m.end(), 0);
// Can use range-based for
for (auto &el : m) el += 1; | {
"domain": "codereview.stackexchange",
"id": 44122,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, matrix, iterator, lambda",
"url": null
} |
c++, object-oriented, matrix, iterator, lambda
// Can use range-based for
for (auto &el : m) el += 1;
// Can use lambdas
int sum = 0;
m.traverse([&sum](int &el) { sum += el; });
// Can use lambdas over neighbours
m.traverse([](int &el) { el = 0; }, 5, 5);
// Can use range-based for over neighbours
for (auto &el : m.neighbours(8, 8)) el = 8;
// Can display on cout
std::cout << m << std::endl;
}
Answer: Enable compiler warnings and fix all warnings
When developing code, make it a habit of enabling strict compiler warnings, and fix all the warnings the compiler finds. My compiler complains about several issues:
Comparison between signed and unsigned integers, because you use int for some variables and size for others. Be consistent, and always use the size type for indices and sizes. Of course you will have a problem then with relative offsets (like neighbours_delta). You might have to use std::ptrdiff_t here, and maybe cast appropriately at the right times. Be careful that the range of a signed type is different than that of an unsigned one.
In NeighbourIterator, member variables appear to be initialized in a different order in the constructor than they are declared. | {
"domain": "codereview.stackexchange",
"id": 44122,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, matrix, iterator, lambda",
"url": null
} |
c++, object-oriented, matrix, iterator, lambda
Naming things
Be consistent when spelling things. I see you use both "neighbors" and "neighbours". It doesn't matter much which one you choose, as long as you are consistent. If you don't know which spelling to use, go for the American one.
Be careful with type aliases
The words "array" and "vector" mean two different things in C++. By using the alias array for std::vector<T>, you might confuse C++ programmers. I would call it container_type, this follows the naming convention of the standard library.
Try to mimick the standard library as much as possible. Every STL container defines size_type. By doing the same, generic algorithms that want to access size_type will be able to work on your class as well. Have a look at how std::vector and std::queue do this. It seems you did do this for your iterator type.
You can make type aliases public as well.
Try to make it work like STL containers as much as possible
To really make it a generic data container, it has to act as much as possible as other data containers. Have a look at other STL containers, and implement all their details where possible. Consider member functions like at() and swap(), constant iterators via cbegin() and cend(), add a copy and move constructors and assignment operators. Add an Allocator template parameter and pass it on to the underlying std::vector.
Remove traverse()
Yes, it makes applying a lambda to the matrix slightly easier, but consider that you already have iterators, so you can use a range-for loops or use algorithms like std::for_each(). This means this didn't add any new functionality, and instead just adds a burden on you to maintain this feature.
Add more ways to iterate over the matrix
Contrary to traverse(), neighbours() is very useful. Consider that you also might want to iterate over rows and columns, and perhaps iterate over a submatrix.
Also note that you didn't provide const versions of traverse().
Use '\n' instead of std::endl | {
"domain": "codereview.stackexchange",
"id": 44122,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, matrix, iterator, lambda",
"url": null
} |
c++, object-oriented, matrix, iterator, lambda
Also note that you didn't provide const versions of traverse().
Use '\n' instead of std::endl
Use '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary, and might impact performance.
C++23 is coming
C++ has historically been a bit annoying when it comes to multi-dimensional arrays. However, C++23 will offer significant improvements in this area. First is that it will allow for a multi-dimensional subscript operator, so your operator() can be turned into an operator[]. Second, std::mdspan will provide a multi-dimensional view of vectors and arrays. This would simplify your class a lot. | {
"domain": "codereview.stackexchange",
"id": 44122,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, matrix, iterator, lambda",
"url": null
} |
c#, algorithm, array, jagged-array
Title: C# Get All Diagonals Jagged Array
Question: How can I improve this?
The idea is to store every left to right diagonals in a list
Not looking for a more efficient algorithm instead something readable, LINQ perhaps?
input:
3, 1
2, 5, 7
1, 5, 8, 3, 1, 4
6, 8, 7, 1
4
6
6, 2, 5
output:
1, 7, 3,
3, 5, 8, 1,
7, 3,
5, 8, 1,
2, 5, 7,
8, 1,
5, 7,
1, 8,
6, 2,
--
var arr = new[]
{
new[]{3,1},
new[]{2,5,7},
new[]{1,5,8,3,1,4},
new[]{6,8,7,1},
new[]{4},
new[]{6},
new[]{6,2,5}
};
GetAllDiagonals(arr);
Console.ReadKey();
static void GetAllDiagonals(int[][] array)
{
var e = new List<List<int>>();
for (var i = 0; i < array.Length; i++)
{
for (var j = array[i].Length - 1; j >= 0; j--)
{
var n = i;
var x = j;
var next = i + 1 <= array.Length - 1 && j < array[n + 1].Length - 1;
var index = 0;
if (next)
{
e.Add(new List<int>());
index = e.Count - 1;
}
while (next)
{
e[index].Add(array[n][x]);
next = n + 1 <= array.Length - 1 && x < array[n + 1].Length - 1;
n++; x++;
}
}
}
for (var i = 0; i < e.Count; i++)
{
for (var j = 0; j < e[i].Count; j++)
{
Console.Write(e[i][j] + ", ");
}
Console.WriteLine();
}
}
Answer: Disclaimer: Apologise for my poor visualisation. I've used Excel to draw the bellow diagrams.
Finding the diagonal step-by-step
Let's play a little bit with your example
As you have said it in your question you want to find all left to right diagonals.
I've used the following informal definition for the left to right diagonal:
A descending line which starts either from the left or from the top side of the matrix until there is a number in the way of it
The minimum length of the line is two | {
"domain": "codereview.stackexchange",
"id": 44123,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, array, jagged-array",
"url": null
} |
c#, algorithm, array, jagged-array
I haven't read any requirements regarding the ordering so, lets suppose you want to find them from left to right
Algorithm
I hope you have noticed the following part (highlighted with bold) in my informal definition:
A descending line which starts either from the left or from the top side of the matrix until there is a number in the way of it
That means you have to have two top level iterations
On the 1st column from bottom to the top
On the 1st row from left to right
To find a diagonal you need the following steps:
Increment both column and row indices
Check whether there is a number under the new indices
If yes repeat step 1 and 2
If not then check line's length
If it is greater than one then you have found a diagonal
If it is 1 then you continue the iteration on the top-level
Implementation
Now let's see how do we implement the above algorithm.
Let's start with the diagonals search which starts from left
static List<List<int>> FindDiagonalsWhichStartsFromLeft(int[][] input)
{
var diagonals = new List<List<int>>();
//Bottom top iteration on first column
for (int row = input.Length - 1; row > 0; row--)
{
int rowIndex = row, columnIndex = 0;
var diagonal = new List<int>()
{
input[rowIndex][columnIndex]
};
//#2.1 If yes repeat step 1 and 2
while (true)
{
//#1 Increment both column and row indices
rowIndex++; columnIndex++;
//#2 Check whether there is a number under the new indices
if (rowIndex >= input.Length ||
columnIndex >= input[rowIndex].Length)
{
break;
}
diagonal.Add(input[rowIndex][columnIndex]);
}
//#2.2.1 If it is greater than one then you have found a diagonal
if (diagonal.Count > 1)
{
diagonals.Add(diagonal);
}
//#2.2.2 If it is 1 then you continue the iteration on the top-level
} | {
"domain": "codereview.stackexchange",
"id": 44123,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, array, jagged-array",
"url": null
} |
c#, algorithm, array, jagged-array
//#2.2.2 If it is 1 then you continue the iteration on the top-level
}
return diagonals;
}
Please note that we have done a reverse loop here from the last row till the 2nd row. We skipped the 1st row because otherwise the main diagonal will be found twice
Of course you can avoid this duplicate in another way like starting from the 2nd column whenever you are searching for diagonals which is starting from the top. (Where to put the prevention logic is up to you.)
Now let's see the other iteration
static List<List<int>> FindDiagonalsWhichStartsFromTop(int[][] input)
{
var diagonals = new List<List<int>>();
//Left to Right iteration on first row
for (int column = 0; column < input[0].Length; column++)
{
int rowIndex = 0, columnIndex = column;
var diagonal = new List<int>()
{
input[rowIndex][columnIndex]
};
//#2.1 If yes repeat step 1 and 2
while (true)
{
//#1 Increment both column and row indices
rowIndex++; columnIndex++;
//#2 Check whether there is a number under the new indices
if (rowIndex >= input.Length ||
columnIndex >= input[rowIndex].Length)
{
break;
}
diagonal.Add(input[rowIndex][columnIndex]);
}
//#2.2.1 If it is greater than one then you have found a diagonal
if (diagonal.Count > 1)
{
diagonals.Add(diagonal);
}
//#2.2.2 If it is 1 then you continue the iteration on the top-level
}
return diagonals;
}
As you can see the only difference here is the outer loop. So, the "core logic" is untouched which means we can extract that into its own method
static void GetDiagonal(int[][] input, List<int> diagonal, int rowIndex, int columnIndex)
{
//#2.1 If yes repeat step 1 and 2
while (true)
{
//#1 Increment both column and row indices
rowIndex++; columnIndex++; | {
"domain": "codereview.stackexchange",
"id": 44123,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, array, jagged-array",
"url": null
} |
c#, algorithm, array, jagged-array
//#2 Check whether there is a number under the new indices
if (rowIndex >= input.Length ||
columnIndex >= input[rowIndex].Length)
{
break;
}
diagonal.Add(input[rowIndex][columnIndex]);
}
}
For the sake of completeness let me share with you the full source code (without comments for the sake of brevity)
static void Main()
{
var arr = new[]
{
new[]{3,1},
new[]{2,5,7},
new[]{1,5,8,3,1,4},
new[]{6,8,7,1},
new[]{4},
new[]{6},
new[]{6,2,5}
};
FindAndPrintDiagonals(arr);
}
static void FindAndPrintDiagonals(int[][] input)
{
var diagonalsFromLeft = FindDiagonalsWhichStartsFromLeft(input);
var diagonalsFromTop = FindDiagonalsWhichStartsFromTop(input);
foreach (var diagonal in diagonalsFromLeft.Union(diagonalsFromTop))
{
Console.WriteLine(string.Join(" ", diagonal));
}
}
static List<List<int>> FindDiagonalsWhichStartsFromLeft(int[][] input)
{
var diagonals = new List<List<int>>();
for (int row = input.Length - 1; row > 0; row--)
{
int rowIndex = row, columnIndex = 0;
var diagonal = new List<int>()
{
input[rowIndex][columnIndex]
};
GetDiagonal(input, diagonal, rowIndex, columnIndex);
if (diagonal.Count > 1)
diagonals.Add(diagonal);
}
return diagonals;
}
static List<List<int>> FindDiagonalsWhichStartsFromTop(int[][] input)
{
var diagonals = new List<List<int>>();
for (int column = 0; column < input[0].Length; column++)
{
int rowIndex = 0, columnIndex = column;
var diagonal = new List<int>()
{
input[rowIndex][columnIndex]
};
GetDiagonal(input, diagonal, rowIndex, columnIndex);
if (diagonal.Count > 1)
diagonals.Add(diagonal);
}
return diagonals;
} | {
"domain": "codereview.stackexchange",
"id": 44123,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, array, jagged-array",
"url": null
} |
c#, algorithm, array, jagged-array
static void GetDiagonal(int[][] input, List<int> diagonal, int rowIndex, int columnIndex)
{
while (true)
{
rowIndex++; columnIndex++;
if (rowIndex >= input.Length || columnIndex >= input[rowIndex].Length)
break;
diagonal.Add(input[rowIndex][columnIndex]);
}
}
Here is a working dotnetfiddle link.
You should see the following output on the console:
6 2
1 8
2 5 7
3 5 8 1
1 7 3 | {
"domain": "codereview.stackexchange",
"id": 44123,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, algorithm, array, jagged-array",
"url": null
} |
clojure
Title: Get city weather and notify an endpoint
Question: I'd like some help to improve this cli program. It queries a city's weather and pushes a weather report.
It takes two arguments: the city to query and the apikey for OpenWeatherMap. For example lein run glasgow abcde12345.
How to make it more idiomatic clojure? How can I avoid having to pass the apikey multiple times?
(ns sunshine.core
(:gen-class)
(:require [clj-http.client :as http])
(:require [clojure.data.json :as json])
)
(defn _get
[url]
(http/get url)
)
(defn _post
[url payload]
(http/post url payload)
)
(defn as_json
[text]
(json/read-str text :key-fn keyword)
)
(defn query_weather
[apikey coords]
(as_json
(:body (_get (str "https://api.openweathermap.org/data/2.5/weather?lat=" (:lat coords) "&lon=" (:lon coords) "&appid=" apikey "&units=metric")))
)
)
(defn get_city_coords
[apikey city]
(let [{:keys [lon lat]} (first (as_json
(:body (_get (str "http://api.openweathermap.org/geo/1.0/direct?q=" city "&appid=" apikey)))
))]
{:lon lon :lat lat})
)
(defn unpack
[raw_message]
{:desc (:description (first (:weather raw_message))) :temperature (:temp (:main raw_message))})
(defn get_weather
[apikey coords]
(unpack (query_weather apikey coords) )
)
(defn as_weather_report
[city weather]
(str "Current weather in " city ": " (:temperature weather) "ºC with " (:desc weather))
)
(defn notify
[message]
(if (:deleted (as_json (:body (_post, "https://api.keen.io/dev/null" {:message message}))))
(println message)
)
)
(defn -main
"Query weather and notify"
[& args]
(let [city (first args) apikey (second args)]
(notify (as_weather_report city (get_weather apikey (get_city_coords apikey city))))
)
)
```
Answer: Some general things: | {
"domain": "codereview.stackexchange",
"id": 44124,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "clojure",
"url": null
} |
clojure
```
Answer: Some general things:
ending parentheses belong to the same line
use a single empty line between definitions
Clojure uses kebab-case (so as_json should be as-json, query_weather becomes query-weather and so on), this applies to names of arguments as well
ns declaration:
:gen-class should be the last reference (order of references is: (:refer-clojure ...) (:require ...) (:use ...) (:import ...) (:load ...) (:gen-class))
you don't have to use :require twice, just use two (or more) vectors inside one :require
(ns sunshine.core
(:require [clj-http.client :as http]
[clojure.data.json :as json])
(:gen-class))
Next three functions (Clojure usually doesn't use underscores, so I just renamed them and used kebab-case)
(defn url-get
[url]
(http/get url))
(defn url-post
[url payload]
(http/post url payload))
(defn as-json
[text]
(json/read-str text :key-fn keyword))
query-weather: you can use destructuring here, as well as -> (thread-first macro) to increase readability
(defn query-weather
[apikey {:keys [lat lon]}]
(-> (str "https://api.openweathermap.org/data/2.5/weather?lat=" lat "&lon=" lon "&appid=" apikey "&units=metric")
url-get
:body
as-json))
get-city-coords: again, you can use -> (thread-first macro). When you compare this function with the previous one, you can note the same sequence of str, url-get, :body, as-json- maybe you can also avoid this repetition somehow
(defn get-city-coords
[apikey city]
(let [{:keys [lon lat]} (-> (str "http://api.openweathermap.org/geo/1.0/direct?q=" city "&appid=" apikey)
url-get
:body
as-json
first)]
{:lon lon :lat lat}))
unpack: you can destructure again
(defn unpack
[{:keys [main weather]}]
{:desc (:description (first weather))
:temperature (:temp main)}) | {
"domain": "codereview.stackexchange",
"id": 44124,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "clojure",
"url": null
} |
clojure
get-weather: without change
(defn get-weather
[apikey coords]
(unpack (query-weather apikey coords)))
as-weather-report: destructure
(defn as-weather-report
[city {:keys [temperature desc]}]
(str "Current weather in " city ": " temperature "°C with " desc))
notify: if with only one branch is when, and you can use -> again
(defn notify
[message]
(when (-> (url-post "https://api.keen.io/dev/null" {:message message})
:body
as-json
:deleted)
(println message)))
-main: destructure, and this time, you can use ->> (thread-last) macro
(defn -main
"Query weather and notify"
[& [city apikey]]
(->> (get-city-coords apikey city)
(get-weather apikey)
(as-weather-report city)
notify)) | {
"domain": "codereview.stackexchange",
"id": 44124,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "clojure",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
Title: Portable Object-Oriented WC (Linux Utility word Count) C++ 20, Counts Lines, Words Bytes
Question: This question Code lines counter prompted me to write my own line counting program. I program on both Windows and Linux and I know about the Linux utility wc.
The command line and output format are based on the wc program, as are the methods for getting the byte count, word count and line count. My comparison is based on the Cygwin wc implementation, since I have Cygwin installed on my Windows 10 computer.
I implemented 7 of the command line switches that Cygwin wc provides:
-c, --bytes print the byte counts
-m, --chars print the character counts
-l, --lines print the newline counts
-w, --words print the word counts
-L, --max-line-length print the length of the longest line
--help display this help and exit
--version output version information and exit
The value -L, --max-line-length from Cygwin wc differs by about 2 percent from this implementation, Cygwin wc calculates the size of tabs slightly differently than this implementation does. The source code of Cygwin wc was examined.
I also added 2 command line switches:
-R, --subdirectories all files in the directory as well as sub directories
-t, --time-execution print the execution time of the program | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
Execution time is calculated separately for command line parsing with file name expansion and the execution of the analysis of the text files that are input.
The code compiles with the C++17 version of g++ in Cygwin and on my Raspberry Pi 4. I have not tested the g++ versions generated. At the time I tried to build them I didn’t know that std::filesystem requires an additional library to be linked in. I will create a make file for this.
Development Environment:
The code was developed in Visual Studio 2022 on Windows 10, Dell Precision 7740
Processor Intel(R) Core(TM) i7-9850H CPU @ 2.60GHz 2.59 GHz
Installed RAM 64.0 GB (63.8 GB usable)
System type 64-bit operating system, x64-based processor
Pen and touch No pen or touch input is available for this display
Edition Windows 10 Pro
Version 21H2
OS build 19044.2251
Experience Windows Feature Experience Pack 120.2212.4180.0
Program Output:
All test cases were run in PowerShell
In the directory where the code for this program is the command line wc -Llcw *.h *.cpp that uses Cygwin wc reports:
30 152 1130 87 CmdLineFileExtractor.h
46 143 1456 75 CommandLineParser.h
26 86 778 75 Executionctrlvalues.h
28 60 711 93 FileProcessor.h
63 275 2515 86 FileStatistics.h
53 129 1120 72 ProgramOptions.h
35 115 1100 79 ReportWriter.h
27 50 470 68 SpecialExceptions.h
24 44 611 72 StatisticsCollector.h
38 100 992 103 UtilityTimer.h
294 846 7587 101 CmdLineFileExtractor.cpp
256 761 7126 101 CommandLineParser.cpp
14 14 231 56 Executionctrlvalues.cpp
104 224 2586 98 FileProcessor.cpp
44 100 1071 62 FileStatistics.cpp
26 61 827 67 ProgramOptions.cpp
196 384 3992 87 ReportWriter.cpp
100 207 2448 93 StatisticsCollector.cpp
67 137 1628 82 main.cpp
1471 3888 38379 103 total | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
The output from the commandline wcfast.exe -tLlcw *.h *.cpp which uses this implementation is:
finished command line parsing at Tue Nov 15 13:13:40 2022
elapsed time in seconds: 0.0001482
Lines Words Bytes Length of
of Text Longest Line
294 846 7587 105 CmdLineFileExtractor.cpp
30 152 1130 89 CmdLineFileExtractor.h
256 761 7126 104 CommandLineParser.cpp
46 143 1456 77 CommandLineParser.h
14 14 231 57 Executionctrlvalues.cpp
26 86 778 76 Executionctrlvalues.h
104 224 2586 99 FileProcessor.cpp
28 60 711 95 FileProcessor.h
44 100 1071 64 FileStatistics.cpp
63 275 2515 88 FileStatistics.h
67 137 1628 88 main.cpp
26 61 827 69 ProgramOptions.cpp
53 129 1120 73 ProgramOptions.h
196 384 3992 91 ReportWriter.cpp
35 115 1100 81 ReportWriter.h
27 50 470 69 SpecialExceptions.h
100 207 2448 95 StatisticsCollector.cpp
24 44 611 74 StatisticsCollector.h
38 100 992 107 UtilityTimer.h
Lines Words Bytes Length of
of Text Longest Line
1471 3888 38379 107
finished processing and reporting input files Tue Nov 15 13:13:40 2022
elapsed time in seconds: 0.0030075
Note that this implementation provides column headings and Cygwin wc doesn't. The order of the files is different, Cygwin wc processes by file extention while this implementation returns the output in a form similar to ls or dir.
Deep Search:
On Windows 10, Cygwin wc can’t do this.
In the high-level directory where all my non-work projects are (each project is a sub directory of this directory and contains many sub directories) the command line:
wcfast.exe -RtLwcml *.h *.c *.cpp *.cs | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
found 565 source code files with 50,146 lines of code and comments, 129,418 words, 1,836,720 bytes with the longest line length being 374 (this last number is shameful). This is the non-work code I’ve written in the last 7 years.
It took 1.03 second to parse the command line and find all the files, it took 0.094 seconds to process the 565 files.
I tried testing from the top level of the boost library on my computer and the program aborted during the search for *.hpp and *.cpp. The search did work in the boost/libs directory. I attempted to correct this from changing from a recursive search for sub directories to an iterative search for directories. While the change improved performance and delayed the abort, the program still aborted which makes me think there is a memory issue involved.
Questions:
Are there any memory leaks? Where?
Are there any C++ or STL functions I could have used to decrease the amount of code I wrote?
Are there any C++20 features I should have used that I didn’t?
How can I improve performance?
Can I improve the method declarations in the header files?
Level of complexity, is any of the code too complex?
Modularity, is there too much coupling between classes?
Should any of the classes be combined?
Are there too many or too few comments?
Is the code self documenting?
What do you think of the class and method names? | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
Future
I do plan on expanding the functionality to include lines of code versus lines of comments. I may also add cyclic complexity to the analysis.
Code:
The code on GitHub as posted in the review..
The updated code on GitHub based on the reviews here. This is a work in progress.
Note, I am no longer the only contributor to this project, 2 of the people that posted reviews are now contributing to the project, Toby Speight and Edward, thank you for your contributions. Obviously I won't be posting a followup review because I am no longer the sole author of the code.
If you want to limit your review to C++20 or the most complex code, focus on CommandLineParser.cpp and CommandLineParser.h.
CommandLineParser.cpp
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include "CommandLineParser.h"
#include "CmdLineFileExtractor.h"
#include "Executionctrlvalues.h"
#include "UtilityTimer.h"
#ifdef _WIN32
static const size_t MinimumCommandLineCount = 1;
#else
// On Linux and Unix argv[0] is the program name so a minimum of 2 arguments
static const size_t MinimumCommandLineCount = 2;
#endif
CommandLineParser::CommandLineParser(int argc, char* argv[],
std::string progVersion)
: argCount{ argc }, args{ argv }, useDefaultFlags{ true }
{
version = progVersion;
initHelpMessage();
initDashMaps();
}
void CommandLineParser::findAllFilesToProcess(ExecutionCtrlValues& execVars)
{
bool searchSubDirs = options.recurseSubDirectories;
CmdLineFileExtractor fileExtractor(NotFlagsArgs, searchSubDirs);
fileExtractor.findAllRequiredFiles();
execVars.filesToProcess = fileExtractor.getFileList();
execVars.fileSpecTypes = fileExtractor.getFileTypeList();
}
unsigned int CommandLineParser::extractAllArguments()
{
unsigned int flagCount = 0; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
unsigned int CommandLineParser::extractAllArguments()
{
unsigned int flagCount = 0;
for (size_t i = 0; i < argCount; i++)
{
if (args[i][0] == '-')
{
if (args[i][1] == '-')
{
processDoubleDashOptions(args[i]);
flagCount++;
}
else
{
processSingleDashOptions(args[i]);
flagCount++;
}
}
else
{
NotFlagsArgs.push_back(args[i]);
}
}
return flagCount;
}
bool CommandLineParser::parse(ExecutionCtrlValues& execVars)
{
UtilityTimer stopWatch;
// There is no way to determine if -t has been used at this point
// so start the timer anyway.
stopWatch.startTimer();
bool hasFiles = false;
if (argCount < MinimumCommandLineCount)
{
ShowHelpMessage doHelp("Call printHelpMessage");
throw doHelp;
}
unsigned int flagCount = extractAllArguments();
if (useDefaultFlags)
{
SetDefaultOptionsWhenNoFlags();
}
findAllFilesToProcess(execVars);
execVars.options = options;
if (options.enableExecutionTime)
{
stopWatch.stopTimerAndReport("command line parsing at ");
}
return hasFiles = execVars.filesToProcess.size() != 0;
}
void CommandLineParser::printHelpMessage()
{
std::cerr << "\n" << messageProgramName();
for (auto line : helpMessage)
{
std::cerr << line;
}
// flush the buffer to make sure the entire message is visible
std::cerr << std::endl;
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
void CommandLineParser::printVersion()
{
std::cout << messageProgramName() << ": version: " << version << "\n";
std::cout << "Packaged by Chernick Consulting\n";
std::cout << "License GPLv3+: GNU GPL version 3 or later"
" <http://gnu.org/licenses/gpl.html>.\n";
std::cout << "This is free software : you are free to change and redistribute it.\n";
std::cout << "\tThere is NO WARRANTY, to the extent permitted by law.\n";
std::cout << "\nWritten by Paul A. Chernick\n";
}
/*
* Flags starting with -- are full strings that need to be processed
* as strings.
*/
void CommandLineParser::processDoubleDashOptions(char* currentArg)
{
auto flag = doubleDashArgs.find(currentArg);
if (flag != doubleDashArgs.end())
{
(*flag).second = true;
useDefaultFlags = false;
return;
}
// The following switches require alternate handling
if (strncmp(currentArg, "--subdirectories", strlen("--subdirectories")) == 0)
{
// Since this is not a column switch it does not affect the default
options.recurseSubDirectories = true;
return;
}
if (strncmp(currentArg, "--time-execution", strlen("--time-execution")) == 0)
{
// Since this is not a column switch it does not affect the default
options.enableExecutionTime = true;
return;
}
if (strncmp(currentArg, "--help", strlen("--help")) == 0)
{
ShowHelpMessage doHelp("Call printHelpMessage");
throw doHelp;
}
if (strncmp(currentArg, "--version", strlen("--version")) == 0)
{
showVersions sv("Call printVersion");
throw sv;
}
std::cerr << "Unknown flag: " << currentArg << "\n";
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
std::cerr << "Unknown flag: " << currentArg << "\n";
}
/*
* Each character needs to be processed independently.
*/
void CommandLineParser::processSingleDashOptions(char* currentArg)
{
for (size_t i = 1; i < std::strlen(currentArg); i++)
{
auto thisOption = singleDashArgs.find(currentArg[i]);
if (thisOption != singleDashArgs.end())
{
(*thisOption).second = true;
useDefaultFlags = false;
}
else
{
switch (currentArg[i])
{
case 'R':
// Since this is not a column switch it does not affect the
// default
options.recurseSubDirectories = true;
continue;
case 't':
// Since this is not a column switch it does not affect the
// default
options.enableExecutionTime = true;
continue;
default:
std::cerr << "Unknown flag: " << currentArg[i] << "\n";
continue;
}
}
}
}
void CommandLineParser::SetDefaultOptionsWhenNoFlags()
{
// Based on the default functionality of the wc program.
options.byteCount = true;
options.wordCount = true;
options.lineCount = true;
}
void CommandLineParser::initDashMaps()
{
doubleDashArgs.insert({ "--bytes", options.byteCount });
doubleDashArgs.insert({ "--chars", options.charCount });
doubleDashArgs.insert({ "--lines", options.lineCount });
doubleDashArgs.insert({ "--max-line-length", options.maxLineWidth });
doubleDashArgs.insert({ "--words", options.wordCount });
singleDashArgs.insert({ 'c', options.byteCount });
singleDashArgs.insert({ 'm', options.charCount });
singleDashArgs.insert({ 'l', options.lineCount });
singleDashArgs.insert({ 'L', options.maxLineWidth });
singleDashArgs.insert({ 'w', options.wordCount });
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
void CommandLineParser::initHelpMessage()
{
std::string veryLongLine;
helpMessage.push_back(" file name or file type specification (*.ext)\n");
helpMessage.push_back("Otions:\n");
helpMessage.push_back("\t-c, --bytes print the byte counts\n");
helpMessage.push_back("\t-m, --chars print the character counts\n");
helpMessage.push_back("\t-l, --lines print the newline counts\n");
helpMessage.push_back(
"\t-t, --time-execution print the execution time of the program\n");
helpMessage.push_back(
"\t-L, --max-line-length print the length of the longest line\n");
helpMessage.push_back("\t-w, --words print the word counts\n");
helpMessage.push_back("\t--help display this help and exit\n");
helpMessage.push_back("\t--version output version information and exit\n");
veryLongLine = "\t-R, --subdirectories all files in the"
" directory as well as sub directories\n";
helpMessage.push_back(veryLongLine);
veryLongLine = "\tBy default the -c -l and -w flags are set, setting any"
" flag requires all flags you want to be set.\n";
helpMessage.push_back(veryLongLine);
}
std::string CommandLineParser::messageProgramName()
{
std::string programName =
#ifdef _WIN32
"wconsteriods"
#else
// On Linux and Unix argv[0] is the program name;
(argCount != 0) ? args[0] : "wconsteriods"
#endif
;
return programName;
}
CommandLineParser.h
#ifndef COMMAND_lINE_PARSER_H
#define COMMAND_lINE_PARSER_H | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
CommandLineParser.h
#ifndef COMMAND_lINE_PARSER_H
#define COMMAND_lINE_PARSER_H
/*
* Generic class to parse command lines. The public interface should not
* require modifications for different programs. The help message will
* need to change on a per program basis. The help message definition may
* need to move to the ProgramOptions class.
*
* This class should be portable to Windows, Linux and Unix operating
* systems. There are ifdefs in the implementation for this purpose.
*/
#include <unordered_map>
#include "Executionctrlvalues.h"
#include "SpecialExceptions.h"
class CommandLineParser
{
public:
CommandLineParser(int argc, char* argv[], std::string progVersion);
bool parse(ExecutionCtrlValues& execVars);
void printHelpMessage();
void printVersion();
protected:
void processSingleDashOptions(char *currentArg);
void processDoubleDashOptions(char* currentArg);
void SetDefaultOptionsWhenNoFlags();
void initDashMaps();
void initHelpMessage();
void findAllFilesToProcess(ExecutionCtrlValues& execVars);
unsigned int extractAllArguments();
std::string messageProgramName();
private:
char** args;
int argCount;
std::string version;
ProgramOptions options;
std::unordered_map<std::string, bool&> doubleDashArgs;
std::unordered_map<char, bool&> singleDashArgs;
std::vector<std::string> helpMessage;
std::vector<std::string> NotFlagsArgs;
bool useDefaultFlags;
};
#endif // COMMAND_lINE_PARSER_H
Executionctrlvalues.cpp
#include <vector>
#include <string>
#include "Executionctrlvalues.h"
ExecutionCtrlValues::ExecutionCtrlValues()
{
}
void ExecutionCtrlValues::initFromEnvironmentVariables()
{
options.initFromEnvironmentVars();
}
Executionctrlvalues.h
#ifndef EXECUTION_CONTROL_VARIABLES_H
#define EXECUTION_CONTROL_VARIABLES_H | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
Executionctrlvalues.h
#ifndef EXECUTION_CONTROL_VARIABLES_H
#define EXECUTION_CONTROL_VARIABLES_H
/*
* Storage for environment and commandline argument variables, also stores
* list of files to process. This class contains all the information to
* execute the program after the command line has been processed.
*
* This class is fairly generic and can be reused by multiple programs that
* process command line arguments.
*/
#include <vector>
#include <string>
#include "ProgramOptions.h"
class ExecutionCtrlValues
{
public:
ExecutionCtrlValues();
~ExecutionCtrlValues() = default;
void initFromEnvironmentVariables();
ProgramOptions options;
std::vector<std::string> fileSpecTypes;
std::vector<std::string> filesToProcess;
};
#endif // EXECUTION_CONTROL_VARIABLES_H
CmdLineFileExtractor.cpp
#include <algorithm>
#include <iostream>
#include <filesystem>
#include <string>
#include <vector>
#include "CmdLineFileExtractor.h"
namespace fsys = std::filesystem; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
namespace fsys = std::filesystem;
/*
* The code here expands wild card file specifications such as "*.cpp" and
* "*.h" into lists of file names to process. If the -R or --subdirectories
* command line flag is true then it searches through the current file
* hierarchy for matching files as well.
*
* Originally the file search was implemented as a recursive algorithm, this
* crashed on Windows 10 when searching for *.hpp in the boost library as a
* test case. The code has been rewritten as an iterative solution, first
* find all the sub directories in the current directory and add them to the
* sub directory list. Then for each sub directory in the sub directory list
* search for more sub directories. When all the sub directories have been
* searched for sub directories find the applicable files in each sub
* directory.
*
* The booleans in this class indicate the phase of processing completed.
* The discovered value indicates whether the sub directory has been searched
* for more sub directories.
* The searchedFiles flag indicates if the files in the directory have been
* added to the fileList vector.
*/
class SubDirNode
{
public:
fsys::path fileSpec;
bool discovered;
bool searchedFiles;
SubDirNode(fsys::path path)
: discovered{ false }, searchedFiles{ false }
{
fileSpec = path;
}
bool operator==(const SubDirNode& other)
{
return fileSpec == other.fileSpec;
}
~SubDirNode() = default;
};
/*
* Internal variables and functions so that #include <fileSystem> does
* not occur every where. It is only needed in this implementation file.
* Normally I put the public interface functions first, but the static
* code needs to be defined before that.
*/
static bool SearchSubDirs;
static std::vector<std::string> fileList;
static std::vector<std::string> fileExtentions;
static std::vector<std::string> nonFlagArgs;
static std::vector<SubDirNode> subDirectories; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
/*
* Search the current directory for sub directories.
*/
static std::vector<SubDirNode> findSubDirs(SubDirNode currentDir)
{
bool hasSubDirs = false;
std::vector<SubDirNode> newSubDirs;
fsys::path cwd = currentDir.fileSpec;
for (auto it = fsys::directory_iterator(cwd);
it != fsys::directory_iterator(); ++it)
{
if (it->is_directory())
{
SubDirNode branch(it->path());
auto found = std::find(subDirectories.begin(), subDirectories.end(), branch);
if (found == subDirectories.end())
{
// Possible nasty side affects here by adding additional
// contents to subDirectories
newSubDirs.push_back(branch);
}
}
}
return newSubDirs;
}
/*
* A recursive algorithm can apparently cause a stack overflow on Windows 10
* so this is an iterative solution.
*/
static bool discoverSubDirs()
{
bool discoveredPhaseCompleted = true;
std::vector<SubDirNode> newSubDirs;
for (size_t i = 0; i < subDirectories.size(); i++)
{
if (!subDirectories[i].discovered)
{
std::vector<SubDirNode> tempNewDirs = findSubDirs(subDirectories[i]);
if (tempNewDirs.size())
{
discoveredPhaseCompleted = false;
newSubDirs.insert(newSubDirs.end(), tempNewDirs.begin(),
tempNewDirs.end());
}
subDirectories[i].discovered = true;
}
}
// We are done searching the current level, append the new sub directories
// to the old.
subDirectories.insert(subDirectories.end(), newSubDirs.begin(), newSubDirs.end());
return discoveredPhaseCompleted;
}
static void discoverAllSubDirs()
{
bool discoveryPhaseCompleted = false;
while (!discoveryPhaseCompleted)
{
discoveryPhaseCompleted = discoverSubDirs();
}
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
static bool containsWildCard(std::string fileSpec)
{
return fileSpec.find('*') != std::string::npos;
}
static std::string getFileExtention(std::string fname)
{
std::string fileExtention = "";
size_t lastDotLocation = fname.find_last_of('.');
if (lastDotLocation != std::string::npos)
{
fileExtention = fname.substr(lastDotLocation);
}
return fileExtention;
}
static bool isASpecifiedFileType(std::string notAFlag) noexcept
{
// Exclude file type specifications since they are not actual file names
if (containsWildCard(notAFlag))
{
return false;
}
std::string fileExtension = getFileExtention(notAFlag);
if (fileExtension.empty())
{
return false;
}
return std::find(fileExtentions.begin(),
fileExtentions.end(), fileExtension) != fileExtentions.end();
}
static void searchDirectoryForFiles(SubDirNode currentDir)
{
for (auto it = fsys::directory_iterator(currentDir.fileSpec);
it != fsys::directory_iterator(); ++it)
{
if (it->is_regular_file() || it->is_character_file())
{
std::string fileName{ it->path().generic_string() };
if (isASpecifiedFileType(fileName))
{
fileList.push_back(fileName);
}
}
}
}
static void searchAllDirectoriesForFiles()
{
for (auto currentDir : subDirectories)
{
if (currentDir.discovered && !currentDir.searchedFiles)
{
searchDirectoryForFiles(currentDir);
currentDir.searchedFiles = true;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
static std::vector<std::string> findAllFileTypeSpecs()
{
std::vector<std::string> fileSpecTypes;
// Get all the file specifications and store them in the
// vector of file specifications. Remove the file specification
// so that it isn't added to the list of files.
for (auto notAFlag : nonFlagArgs)
{
if (containsWildCard(notAFlag))
{
fileSpecTypes.push_back(notAFlag);
}
}
return fileSpecTypes;
}
static std::vector<std::string> getFileTypes()
{
std::vector<std::string> fileTypes;
std::vector<std::string> fileSpecTypes = findAllFileTypeSpecs();
for (auto fileTypeSpec : fileSpecTypes)
{
std::string fileExtention = getFileExtention(fileTypeSpec);
if (!fileExtention.empty())
{
fileTypes.push_back(fileExtention);
}
}
return fileTypes;
}
static void addListedFilesToFileList()
{
for (auto fileSpec : nonFlagArgs)
{
if (isASpecifiedFileType(fileSpec))
{
fileList.push_back(fileSpec);
}
}
}
static void findAllInputFiles()
{
// if there is nothing to search for quit.
if (!SearchSubDirs && fileExtentions.size() == 0)
{
return;
}
// Start in the current working directory (cwd for non Linux users).
std::filesystem::path cwd = fsys::current_path();
if (subDirectories.empty())
{
SubDirNode root(cwd);
root.discovered = (SearchSubDirs) ? false: true;
subDirectories.push_back(root);
}
if (SearchSubDirs)
{
discoverAllSubDirs();
}
searchAllDirectoriesForFiles();
}
/*
* Begin public interfaces
*/ | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
/*
* Begin public interfaces
*/
CmdLineFileExtractor::CmdLineFileExtractor(
std::vector<std::string> NonFlagArgs,
bool searchSubDirs)
{
// copy is ok, we are not worried about performance here.
// This class should be instantiated only once per program
// run. It is only needed by the command line parser.
nonFlagArgs = NonFlagArgs;
SearchSubDirs = searchSubDirs;
}
void CmdLineFileExtractor::findAllRequiredFiles() noexcept
{
fileExtentions = getFileTypes();
addListedFilesToFileList();
findAllInputFiles();
}
std::vector<std::string> CmdLineFileExtractor::getFileList() const noexcept
{
return fileList;
}
std::vector<std::string> CmdLineFileExtractor::getFileTypeList() const noexcept
{
return fileExtentions;
}
CmdLineFileExtractor.h
#ifndef COMMAND_LINE_FILE_EXTRACTOR_H
#define COMMAND_LINE_FILE_EXTRACTOR_H
/*
* This class has one purpose, to build a list of files to process for
* the calling program. It expands wild card strings. It searches the
* current working directory for files of the specified types. If the
* search subdirs bool is set it will also search the sub directories
* of the current working directory. The list of files to process will
* be full file specifications so that all the proper files are read
* only once.
*
* What would be protected or private functions and variables are
* implemented as static functions and variables within the
* implementation .cpp file to limit the access to the file system to
* only this class/module.
*/
#include <string>
#include <vector>
class CmdLineFileExtractor
{
public:
CmdLineFileExtractor(std::vector<std::string> NonFlagArgs, bool searchSubDirs);
void findAllRequiredFiles() noexcept;
std::vector<std::string> getFileList() const noexcept;
std::vector<std::string> getFileTypeList() const noexcept;
};
#endif // COMMAND_LINE_FILE_EXTRACTOR_H
ProgramOptions.cpp
#include <iostream>
#include "ProgramOptions.h" | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
ProgramOptions.cpp
#include <iostream>
#include "ProgramOptions.h"
#ifdef _DEBUG
void ProgramOptions::singleLine(std::string flag, bool flagValue)
{
std::cout << "Flag " << flag << ": Flag value " <<
((flagValue) ? "True" : "False") << "\n";
}
void ProgramOptions::debugPrint()
{
singleLine("blankLineCount", blankLineCount);
singleLine("byteCount", byteCount);
singleLine("charCount", charCount);
singleLine("codeCount", codeCount);
singleLine("commentCount", commentCount);
singleLine("lineCount", lineCount);
singleLine("maxLineWidth", maxLineWidth);
singleLine("percentages", percentages);
singleLine("whitespaceCount", whitespaceCount);
singleLine("wordCount", wordCount);
singleLine("recurseSubDirectories", recurseSubDirectories);
singleLine("enableExecutionTime", enableExecutionTime);
}
#endif
ProgramOptions.h
#ifndef PROGRAM_OPTIONS_STRUCT_H
#define PROGRAM_OPTIONS_STRUCT_H
/*
* This class is not generic except for the public functions. It is used
* to contain the the values of the switches/flags on the command line.
*/
class ProgramOptions {
public:
// Output control variables
bool blankLineCount;
bool byteCount;
bool charCount;
bool codeCount;
bool commentCount;
bool lineCount;
bool maxLineWidth;
bool percentages;
bool whitespaceCount;
bool wordCount;
bool enableExecutionTime;
// input control variables
bool recurseSubDirectories;
ProgramOptions()
: blankLineCount{ false },
byteCount{ false },
charCount{ false },
codeCount{ false },
commentCount{ false },
lineCount{ false },
maxLineWidth{ false },
percentages{ false },
whitespaceCount{ false },
wordCount{ false },
enableExecutionTime{ false },
recurseSubDirectories{ false }
{
}
void initFromEnvironmentVars()
{
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
}
void initFromEnvironmentVars()
{
}
#ifdef _DEBUG
void singleLine(std::string flag, bool flagValue);
void debugPrint();
#endif // _DEBUG
};
#endif // PROGRAM_oPTIONS_STRUCT_H
SpecialExceptions.h
#ifndef SPECIAL_EXCEPTIONS_H
#define SPECIAL_EXCEPTIONS_H
/*
* Implements special exceptions for the --help and --version flags.
*/
#include <stdexcept>
class ShowHelpMessage: public std::runtime_error
{
public:
ShowHelpMessage(const char* msg) : std::runtime_error(msg)
{
}
};
class showVersions : public std::runtime_error
{
public:
showVersions(const char* msg) : std::runtime_error(msg)
{
}
};
#endif // SPECIAL_EXCEPTIONS_H
FileProcessor.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include "StatisticsCollector.h"
#include "FileProcessor.h"
#include "FileStatistics.h"
#include "ReportWriter.h"
static constexpr size_t InputBufferSize = 8 * 1024;
FileProcessor::FileProcessor(std::vector<std::string>& filesToProess, ProgramOptions& progOptions)
: options{ progOptions }
{
fileNames = filesToProess;
}
std::string FileProcessor::processAllFiles() noexcept
{
ReportWriter TotalsReporter(options);
FileStatistics allFiles;
std::string resultsToDisplay(TotalsReporter.getColumnHeadingAsOneString());
for (auto currentFile : fileNames)
{
try
{
std::string fileResults = processFile(currentFile, allFiles);
if (!fileResults.empty())
{
resultsToDisplay += fileResults;
}
}
catch (std::runtime_error re)
{
std::cerr << re.what() << "\n";
}
}
resultsToDisplay += TotalsReporter.getColumnHeadingAsOneString();
resultsToDisplay += TotalsReporter.getResultText(allFiles);
return resultsToDisplay;
}
void FileProcessor::processLoop(std::ifstream& inStream,
FileStatistics& statistics) noexcept
{
StatisticsCollector fileAnalyzer(statistics); | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
std::stringstream inputBuffer;
std::streambuf* inBuf = inStream.rdbuf();
inputBuffer << inStream.rdbuf();
fileAnalyzer.analyzeBuffer(inputBuffer.str());
}
/*
* Processing a file includes reading the file, analyzing the input to collect
* the statistics and then pringing the statistics.
*/
std::string FileProcessor::processFile(std::string fileName,
FileStatistics& totalStats)
{
std::string fileResults;
try {
if (fileName.empty())
{
std::string eMsg(
"Programmer Error: File name is empty in "
"FileProcessor Constructor!");
std::runtime_error programmerError(eMsg);
throw programmerError;
}
std::ifstream inStream(fileName);
if (!inStream.is_open())
{
std::string eMsg("Runtime error: Can't open file " + fileName +
" for input.");
std::runtime_error FileInputError(eMsg);
throw FileInputError;
}
FileStatistics statistics(fileName);
processLoop(inStream, statistics);
inStream.close();
ReportWriter ReportFileStatistics(options);
fileResults = ReportFileStatistics.getResultText(statistics);
statistics.addTotals(totalStats);
}
catch (std::exception ex)
{
std::cerr <<
"Error: unable to complete processing file statistics for "
<< fileName << " Error: " << ex.what() << std::endl;
fileResults.clear();
}
return fileResults;
}
FileProcessor.h
#ifndef FILE_PROCESSOR_H
#define FILE_PROCESSOR_H
#include <string>
#include <vector>
#include <fstream>
#include "FileStatistics.h"
#include "ProgramOptions.h"
class FileProcessor
{
public:
FileProcessor(std::vector<std::string>& filesToProcess, ProgramOptions& progOptions);
~FileProcessor() = default;
std::string processAllFiles() noexcept; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
protected:
void processLoop(std::ifstream& inStream, FileStatistics& statistics) noexcept;
std::string processFile(std::string fileName, FileStatistics& totalStats);
private:
std::vector<std::string> fileNames;
// The program options are necessary to know what to outout.
ProgramOptions& options;
};
#endif // FILE_PROCESSOR_H
FileStatistics.cpp
#include "FileStatistics.h"
#include <string>
FileStatistics::FileStatistics()
: totalLineCount{ 0 },
codeLineCount{ 0 },
commentLineCount{ 0 },
whiteSpaceCount{ 0 },
wordCount{ 0 },
characterCount{ 0 },
codeWithCommentCount{ 0 },
blankLineCount{ 0 },
widestLine{ 0 }
{
}
FileStatistics::FileStatistics(std::string inFileName)
: totalLineCount{ 0 },
codeLineCount{ 0 },
commentLineCount{ 0 },
whiteSpaceCount{ 0 },
wordCount{ 0 },
characterCount{ 0 },
codeWithCommentCount{ 0 },
blankLineCount{ 0 },
widestLine{ 0 },
fileName{ inFileName }
{
}
void FileStatistics::addTotals(FileStatistics &allFiles)
{
allFiles.totalLineCount += totalLineCount;
allFiles.codeLineCount += codeLineCount;
allFiles.commentLineCount += commentLineCount;
allFiles.whiteSpaceCount += whiteSpaceCount;
allFiles.wordCount += wordCount;
allFiles.characterCount += characterCount;
allFiles.codeWithCommentCount += codeWithCommentCount;
allFiles.blankLineCount += blankLineCount;
allFiles.updateWidestLine(widestLine);
}
FileStatistics.h
#ifndef FILE_STATISTICS_H
#define FILE_STATISTICS_H
/*
* Class to collect all the statistics about the code in a file.
*
*/
#include <string>
class FileStatistics
{
private:
size_t totalLineCount;
size_t codeLineCount;
size_t commentLineCount;
size_t whiteSpaceCount;
size_t characterCount;
size_t wordCount;
size_t codeWithCommentCount;
size_t widestLine;
size_t blankLineCount;
std::string fileName; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
public:
FileStatistics();
FileStatistics(std::string inFileName);
void setFileName(std::string inFileName) { fileName = inFileName; }
std::string getFileName() { return fileName; }
void addTotals(FileStatistics &allFiles);
void addToLineCount(size_t lineCount) { totalLineCount += lineCount; }
void setToLineCount(size_t lineCount) { totalLineCount = lineCount; }
void addToCharCount(size_t charCount) { characterCount += charCount; }
void setCharCount(size_t charCount) { characterCount = charCount; }
void addToWordCount(size_t wordCountUpdate) { wordCount += wordCountUpdate; }
void setWordCount(size_t wordCountUpdate) { wordCount = wordCountUpdate; }
void addToWhitespace(size_t wsUpdate) { whiteSpaceCount += wsUpdate; }
// While the inline key word is only a recommendation, hopefully the increment
// functions can be inline.
inline void incrementTotalLines() { totalLineCount++; }
size_t getTotalLines() const { return totalLineCount; }
inline void incrementCodeLines() { codeLineCount++; }
size_t getCodeLines() const { return codeLineCount; }
inline void incrementCommentsLines() { commentLineCount++; }
size_t getCommentLines() const { return commentLineCount; }
inline void incrementWhitespace() { whiteSpaceCount++; }
size_t getWhitespace() const { return whiteSpaceCount; }
inline void incrementCharacter() { characterCount++; }
size_t getCharacters() const { return characterCount; }
inline void incrementWords() { wordCount++; }
size_t getWords() const { return wordCount; }
inline void incrementCodeWithComment() { codeWithCommentCount++; }
size_t getCodeWithComment() const { return codeWithCommentCount; }
inline void incrementBlankLines() { blankLineCount++; }
size_t getBlankLines() { return blankLineCount; }
void updateWidestLine(size_t width) {
widestLine = (width > widestLine)? width : widestLine;
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
widestLine = (width > widestLine)? width : widestLine;
}
size_t getWidestLine() { return widestLine; }
float getPerecentageOfCode() {
return static_cast<float>(codeLineCount / totalLineCount);
}
}; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
#endif // FILE_STATISTICS_H
StatisticsCollector.cpp
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <iostream>
#include <iterator>
#include <vector>
#include <string>
#include "StatisticsCollector.h"
#include "FileStatistics.h"
static constexpr size_t tabSize = 8;
StatisticsCollector::StatisticsCollector(FileStatistics& fileStats)
: fileStatistics{ fileStats }
{
}
void StatisticsCollector::analyzeBuffer(std::string inputBuffer) noexcept
{
std::string::iterator endBuffer = inputBuffer.end();
std::string::iterator startBuffer = inputBuffer.begin();
std::uintmax_t bufferSize = std::filesystem::file_size(fileStatistics.getFileName());
fileStatistics.setCharCount(bufferSize);
size_t lineCount = std::count(startBuffer, endBuffer, '\n');
fileStatistics.setToLineCount(lineCount);
countWordsAndWhiteSpace(inputBuffer);
std::string::iterator currentChar = startBuffer;
while (currentChar != endBuffer)
{
updateWidestLine(currentChar, endBuffer);
}
}
void StatisticsCollector::countWordsAndWhiteSpace(std::string& inputBuffer) noexcept
{
size_t wordCount = 0;
size_t whiteSpaceCount = 0;
std::string::iterator currentChar = inputBuffer.begin();
std::string::iterator endOfInput = inputBuffer.end();
bool inWord = false;
for ( ; currentChar != endOfInput; )
{
while (isspace(*currentChar))
{
whiteSpaceCount++;
currentChar++;
if (currentChar == endOfInput)
{
break;
}
}
while (!(currentChar == endOfInput) && !isspace(*currentChar))
{
inWord = true;
currentChar++;
if (currentChar == endOfInput)
{
wordCount++;
inWord = false;
break;
}
}
if (inWord)
{
wordCount++;
inWord = false;
}
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
if (inWord)
{
wordCount++;
inWord = false;
}
}
fileStatistics.addToWhitespace(whiteSpaceCount);
fileStatistics.setWordCount(wordCount);
}
void StatisticsCollector::updateWidestLine(std::string::iterator& currentChar,
std::string::iterator end) noexcept
{
std::string::iterator endOfLine = std::find(currentChar, end, '\n');
if (endOfLine != end)
{
endOfLine++;
}
size_t lineWidth = endOfLine - currentChar;
// See https://github.com/coreutils/coreutils/blob/master/src/wc.c to
// observe how tabs are counted.
size_t tabCount = std::count(currentChar, endOfLine, '\t');
lineWidth += tabCount * tabSize;
fileStatistics.updateWidestLine(lineWidth);
std::string line(currentChar, endOfLine);
currentChar = endOfLine;
}
StatisticsCollector.h
#ifndef STATISTICS_COLLECTOR_H
#define STATISTICS_COLLECTOR_H
#include <iterator>
#include <string>
#include <vector>
#include "FileStatistics.h"
class StatisticsCollector
{
public:
StatisticsCollector(FileStatistics& fileStats);
void analyzeBuffer(std::string inputbuffer) noexcept;
protected:
void updateWidestLine(std::string::iterator& currentChar,
std::string::iterator end) noexcept;
void lineWidth(std::string line) noexcept;
void countWordsAndWhiteSpace(std::string& inputBuffer) noexcept;
private:
FileStatistics& fileStatistics;
};
#endif // STATISTICS_COLLECTOR_H
ReportWriter.cpp
#include <iostream>
#include <string>
#include <vector>
#include "ReportWriter.h"
void ReportWriter::printResult(FileStatistics& resultsForOutput) noexcept
{
std::cout << getResultText(resultsForOutput) << "\n";
}
/*
* Maintain the order between this function and getColumneHeadingsText().
*/
std::string ReportWriter::getResultText(FileStatistics& resultsForOutput) noexcept
{
std::string outString; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
if (options->lineCount)
{
outString += std::to_string(resultsForOutput.getTotalLines()) + "\t";
}
if (options->wordCount)
{
outString += std::to_string(resultsForOutput.getWords()) + "\t";
}
if (options->byteCount)
{
outString += std::to_string(resultsForOutput.getCharacters()) + "\t";
}
if (options->charCount)
{
outString += std::to_string(resultsForOutput.getCharacters()) + "\t\t";
}
if (options->maxLineWidth)
{
outString += std::to_string(resultsForOutput.getWidestLine()) + "\t";
}
// End of backwards compatability with wc utility.
if (options->codeCount)
{
outString += std::to_string(resultsForOutput.getCodeLines()) + "\t";
}
if (options->commentCount)
{
outString += std::to_string(resultsForOutput.getCommentLines()) + "\t";
}
if (options->percentages)
{
outString +=
std::to_string(resultsForOutput.getPerecentageOfCode()) + "\t";
}
if (options->whitespaceCount)
{
outString += std::to_string(resultsForOutput.getWhitespace()) + "\t";
}
if (options->blankLineCount)
{
outString += std::to_string(resultsForOutput.getBlankLines()) + "\t";
}
std::string fileName = correctFileSpec(resultsForOutput.getFileName());
outString += "\t" + fileName + "\n";
return outString;
}
/*
* Maintain the order between this function and getResultText().
*/
std::vector<std::string> ReportWriter::getColumneHeadingsText() noexcept
{
std::string firstLine;
std::string secondline;
if (options->lineCount)
{
firstLine += "Lines\t";
secondline += "of Text\t";
}
if (options->wordCount)
{
firstLine += "Words\t";
secondline += "\t";
}
if (options->byteCount)
{
firstLine += "Bytes\t";
secondline += "\t";
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
if (options->byteCount)
{
firstLine += "Bytes\t";
secondline += "\t";
}
if (options->charCount)
{
firstLine += "Characters\t";
secondline += "\t\t";
}
if (options->maxLineWidth)
{
firstLine += "Length of\t";
secondline += "Longest Line\t";
}
// End of backwards compatability with wc utility.
if (options->codeCount)
{
firstLine += "Lines\t";
secondline += "of Code\t";
}
if (options->commentCount)
{
firstLine += "Lines of\t";
secondline += "Comments\t";
}
if (options->percentages)
{
firstLine += "Percentage of\t";
secondline += "Lines of Code\t";
}
if (options->whitespaceCount)
{
firstLine += "Whitespace\t";
secondline += "Characters\t";
}
if (options->blankLineCount)
{
firstLine += "Blank\t";
secondline += "Lines\t";
}
std::vector<std::string> headerRows = { firstLine, secondline };
return headerRows;
}
std::string ReportWriter::getColumnHeadingAsOneString() noexcept
{
std::string twolines;
std::vector<std::string> headingLines = getColumneHeadingsText();
FileStatistics allFiles;
std::string twoLines;
for (auto headingLine : headingLines)
{
twoLines += headingLine + "\n";
}
return twoLines;
}
void ReportWriter::printColumnHeadings() noexcept
{
std::vector<std::string> headerRows = getColumneHeadingsText();
for (auto line : headerRows)
{
std::cout << line << "\n";
}
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
std::string ReportWriter::correctFileSpec(std::string fileSpec) noexcept
{
if (options->recurseSubDirectories)
{
return fileSpec;
}
else
{
auto newStart = fileSpec.find_last_of('/');
if (!newStart)
{
newStart = fileSpec.find_last_of('\\');
if (!newStart)
{
return fileSpec;
}
}
std::string fileName = fileSpec.substr(newStart + 1);
return fileName;
}
}
ReportWriter.h
#ifndef REPORT_WRITER_H
#define REPORT_WRITER_H
/*
* This class prints the output about the file statistics. It can also
* return a formated string of the output.
*/
#include <memory>
#include <string> // std::vector included by string
#include "ProgramOptions.h"
#include "FileStatistics.h"
class ReportWriter
{
public:
// ExecutionCrtlValues is passed in so that the report writer know what
// output to generate.
ReportWriter(ProgramOptions& progOptions)
{
options = std::make_shared<ProgramOptions>(progOptions);
}
void printResult(FileStatistics& resultsForOutput) noexcept;
std::string getResultText(FileStatistics& resultsForOutput) noexcept;
void printColumnHeadings() noexcept;
// Returns 2 lines of properly formated text
std::vector<std::string> getColumneHeadingsText() noexcept;
std::string getColumnHeadingAsOneString() noexcept;
private:
// The program options are necessary to know what to outout.
std::shared_ptr <ProgramOptions> options;
std::string correctFileSpec(std::string fileSpec) noexcept;
};
#endif // REPORT_WRITER_H
UtilityTimer.h
#ifndef CC_UTITLTY_TIMER_H
#define CC_UTITLTY_TIMER_H
/*
* Chernick Consulting Utility timer class.
* Encapsulates execution timing for all or parts of a program.
*/
#include <chrono>
#include <iostream>
#include <string> | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
#include <chrono>
#include <iostream>
#include <string>
class UtilityTimer
{
public:
UtilityTimer() = default;
~UtilityTimer() = default;
void startTimer() noexcept
{
start = std::chrono::system_clock::now();
}
void stopTimerAndReport(std::string whatIsBeingTimed) noexcept
{
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
double ElapsedTimeForOutPut = elapsed_seconds.count();
std::cout << "finished " << whatIsBeingTimed << std::ctime(&end_time)
<< "elapsed time in seconds: " << ElapsedTimeForOutPut << "\n" << "\n" << "\n";
}
private:
std::chrono::time_point<std::chrono::system_clock> start, end;
};
#endif // CC_UTITLTY_TIMER_H
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Executionctrlvalues.h"
#include "CommandLineParser.h"
#include "FileProcessor.h"
#include "ProgramOptions.h"
#include "UtilityTimer.h"
static void mainLoop(ExecutionCtrlValues& executionCtrl)
{
std::string resultsToDisplay;
ProgramOptions& options = executionCtrl.options;
std::vector<std::string> filesToProcess = executionCtrl.filesToProcess;
FileProcessor fileProcessor(filesToProcess, options);
resultsToDisplay = fileProcessor.processAllFiles();
// Yes we want to flush the standard output. All possible output has been
// collected.
std::cout << resultsToDisplay << std::endl;
}
int main(int argc, char* argv[])
{
int exit_status = EXIT_SUCCESS;
ExecutionCtrlValues executionCtrl;
std::string versionString("1.0.0");
CommandLineParser cmdLineParser(argc, argv, versionString); | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
CommandLineParser cmdLineParser(argc, argv, versionString);
try
{
executionCtrl.initFromEnvironmentVariables();
if (cmdLineParser.parse(executionCtrl))
{
UtilityTimer stopWatch;
if (executionCtrl.options.enableExecutionTime)
{
stopWatch.startTimer();
}
mainLoop(executionCtrl);
if (executionCtrl.options.enableExecutionTime)
{
stopWatch.stopTimerAndReport(
" processing and reporting input files ");
}
}
}
catch (ShowHelpMessage sh)
{
cmdLineParser.printHelpMessage();
cmdLineParser.printVersion();
}
catch (showVersions sv)
{
cmdLineParser.printVersion();
}
catch (std::exception ex)
{
std::cerr << "Error: " << ex.what() << "\n";
exit_status = EXIT_FAILURE;
}
return exit_status;
}
Answer: Usability
Sorting the files in output is surprising, given that commonly-used implementations produce output in the same order that the files were specified. Scripts likely depend on the order matching the arguments
Producing the output header lines should be optional, given that the POSIX spec for wc doesn't appear to allow this. That's important, given how often we see a command substitution such as $(wc -l <"$file") in shell scripts.
POSIX also specifies that the summary line should have (possibly-translated) total in place of the filename, rather than blank.
Columns of numbers are easier to read if right-aligned, like the Cygwin output you show.
It only seems to work with files, rather than using standard input when no filenames are specified. | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
Compiler warnings
Some automated review from GCC:
g++-12 -std=c++20 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast -c -o CmdLineFileExtractor.o CmdLineFileExtractor.cpp
CmdLineFileExtractor.cpp: In constructor ‘SubDirNode::SubDirNode(std::filesystem::__cxx11::path)’:
CmdLineFileExtractor.cpp:37:9: warning: ‘SubDirNode::fileSpec’ should be initialized in the member initialization list [-Weffc++]
37 | SubDirNode(fsys::path path)
| ^~~~~~~~~~
CmdLineFileExtractor.cpp: In function ‘std::vector<SubDirNode> findSubDirs(SubDirNode)’:
CmdLineFileExtractor.cpp:66:14: warning: unused variable ‘hasSubDirs’ [-Wunused-variable]
66 | bool hasSubDirs = false;
| ^~~~~~~~~~
g++-12 -std=c++20 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast -c -o CommandLineParser.o CommandLineParser.cpp
In file included from CommandLineParser.cpp:7:
CommandLineParser.h:17:7: warning: ‘class CommandLineParser’ has pointer data members [-Weffc++]
17 | class CommandLineParser
| ^~~~~~~~~~~~~~~~~
CommandLineParser.h:17:7: warning: but does not declare ‘CommandLineParser(const CommandLineParser&)’ [-Weffc++]
CommandLineParser.h:17:7: warning: or ‘operator=(const CommandLineParser&)’ [-Weffc++]
CommandLineParser.h:36:16: note: pointer member ‘CommandLineParser::args’ declared here
36 | char** args;
| ^~~~
CommandLineParser.h: In constructor ‘CommandLineParser::CommandLineParser(int, char**, std::string)’:
CommandLineParser.h:37:13: warning: ‘CommandLineParser::argCount’ will be initialized after [-Wreorder]
37 | int argCount;
| ^~~~~~~~
CommandLineParser.h:36:16: warning: ‘char** CommandLineParser::args’ [-Wreorder]
36 | char** args;
| ^~~~
CommandLineParser.cpp:19:1: warning: when initialized here [-Wreorder] | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
| ^~~~
CommandLineParser.cpp:19:1: warning: when initialized here [-Wreorder]
19 | CommandLineParser::CommandLineParser(int argc, char* argv[],
| ^~~~~~~~~~~~~~~~~
CommandLineParser.cpp:19:1: warning: ‘CommandLineParser::version’ should be initialized in the member initialization list [-Weffc++]
CommandLineParser.cpp:19:1: warning: ‘CommandLineParser::options’ should be initialized in the member initialization list [-Weffc++]
CommandLineParser.cpp:19:1: warning: ‘CommandLineParser::doubleDashArgs’ should be initialized in the member initialization list [-Weffc++]
CommandLineParser.cpp:19:1: warning: ‘CommandLineParser::singleDashArgs’ should be initialized in the member initialization list [-Weffc++]
CommandLineParser.cpp:19:1: warning: ‘CommandLineParser::helpMessage’ should be initialized in the member initialization list [-Weffc++]
CommandLineParser.cpp:19:1: warning: ‘CommandLineParser::NotFlagsArgs’ should be initialized in the member initialization list [-Weffc++]
CommandLineParser.cpp: In member function ‘unsigned int CommandLineParser::extractAllArguments()’:
CommandLineParser.cpp:41:30: warning: comparison of integer expressions of different signedness: ‘size_t’ {aka ‘long unsigned int’} and ‘int’ [-Wsign-compare]
41 | for (size_t i = 0; i < argCount; i++)
| ~~^~~~~~~~~~
In file included from CommandLineParser.cpp:10:
UtilityTimer.h: In constructor ‘constexpr UtilityTimer::UtilityTimer()’:
UtilityTimer.h:16:9: warning: ‘UtilityTimer::start’ should be initialized in the member initialization list [-Weffc++]
16 | UtilityTimer() = default;
| ^~~~~~~~~~~~
UtilityTimer.h:16:9: warning: ‘UtilityTimer::end’ should be initialized in the member initialization list [-Weffc++]
CommandLineParser.cpp: In member function ‘bool CommandLineParser::parse(ExecutionCtrlValues&)’: | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
CommandLineParser.cpp: In member function ‘bool CommandLineParser::parse(ExecutionCtrlValues&)’:
CommandLineParser.cpp:74:22: warning: comparison of integer expressions of different signedness: ‘int’ and ‘const size_t’ {aka ‘const long unsigned int’} [-Wsign-compare]
74 | if (argCount < MinimumCommandLineCount)
| ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
CommandLineParser.cpp:80:22: warning: unused variable ‘flagCount’ [-Wunused-variable]
80 | unsigned int flagCount = extractAllArguments();
| ^~~~~~~~~
g++-12 -std=c++20 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast -c -o Executionctrlvalues.o Executionctrlvalues.cpp
Executionctrlvalues.cpp: In constructor ‘ExecutionCtrlValues::ExecutionCtrlValues()’:
Executionctrlvalues.cpp:5:1: warning: ‘ExecutionCtrlValues::options’ should be initialized in the member initialization list [-Weffc++]
5 | ExecutionCtrlValues::ExecutionCtrlValues()
| ^~~~~~~~~~~~~~~~~~~
Executionctrlvalues.cpp:5:1: warning: ‘ExecutionCtrlValues::fileSpecTypes’ should be initialized in the member initialization list [-Weffc++]
Executionctrlvalues.cpp:5:1: warning: ‘ExecutionCtrlValues::filesToProcess’ should be initialized in the member initialization list [-Weffc++]
g++-12 -std=c++20 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast -c -o FileProcessor.o FileProcessor.cpp
In file included from FileProcessor.cpp:7:
ReportWriter.h: In constructor ‘ReportWriter::ReportWriter(ProgramOptions&)’:
ReportWriter.h:18:9: warning: ‘ReportWriter::options’ should be initialized in the member initialization list [-Weffc++]
18 | ReportWriter(ProgramOptions& progOptions)
| ^~~~~~~~~~~~
FileProcessor.cpp: In constructor ‘FileProcessor::FileProcessor(std::vector<std::__cxx11::basic_string<char> >&, ProgramOptions&)’: | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
FileProcessor.cpp:11:1: warning: ‘FileProcessor::fileNames’ should be initialized in the member initialization list [-Weffc++]
11 | FileProcessor::FileProcessor(std::vector<std::string>& filesToProess, ProgramOptions& progOptions)
| ^~~~~~~~~~~~~
FileProcessor.cpp: In member function ‘std::string FileProcessor::processAllFiles()’:
FileProcessor.cpp:34:43: warning: catching polymorphic type ‘class std::runtime_error’ by value [-Wcatch-value=]
34 | catch (std::runtime_error re)
| ^~
FileProcessor.cpp: In member function ‘void FileProcessor::processLoop(std::ifstream&, FileStatistics&)’:
FileProcessor.cpp:52:25: warning: unused variable ‘inBuf’ [-Wunused-variable]
52 | std::streambuf* inBuf = inStream.rdbuf();
| ^~~~~
FileProcessor.cpp: In member function ‘std::string FileProcessor::processFile(std::string, FileStatistics&)’:
FileProcessor.cpp:95:31: warning: catching polymorphic type ‘class std::exception’ by value [-Wcatch-value=]
95 | catch (std::exception ex)
| ^~
g++-12 -std=c++20 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast -c -o FileStatistics.o FileStatistics.cpp
In file included from FileStatistics.cpp:1:
FileStatistics.h: In constructor ‘FileStatistics::FileStatistics()’:
FileStatistics.h:18:16: warning: ‘FileStatistics::wordCount’ will be initialized after [-Wreorder]
18 | size_t wordCount;
| ^~~~~~~~~
FileStatistics.h:17:16: warning: ‘size_t FileStatistics::characterCount’ [-Wreorder]
17 | size_t characterCount;
| ^~~~~~~~~~~~~~
FileStatistics.cpp:4:1: warning: when initialized here [-Wreorder]
4 | FileStatistics::FileStatistics()
| ^~~~~~~~~~~~~~
FileStatistics.h:21:16: warning: ‘FileStatistics::blankLineCount’ will be initialized after [-Wreorder] | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
21 | size_t blankLineCount;
| ^~~~~~~~~~~~~~
FileStatistics.h:20:16: warning: ‘size_t FileStatistics::widestLine’ [-Wreorder]
20 | size_t widestLine;
| ^~~~~~~~~~
FileStatistics.cpp:4:1: warning: when initialized here [-Wreorder]
4 | FileStatistics::FileStatistics()
| ^~~~~~~~~~~~~~
FileStatistics.cpp:4:1: warning: ‘FileStatistics::fileName’ should be initialized in the member initialization list [-Weffc++]
FileStatistics.h: In constructor ‘FileStatistics::FileStatistics(std::string)’:
FileStatistics.h:18:16: warning: ‘FileStatistics::wordCount’ will be initialized after [-Wreorder]
18 | size_t wordCount;
| ^~~~~~~~~
FileStatistics.h:17:16: warning: ‘size_t FileStatistics::characterCount’ [-Wreorder]
17 | size_t characterCount;
| ^~~~~~~~~~~~~~
FileStatistics.cpp:18:1: warning: when initialized here [-Wreorder]
18 | FileStatistics::FileStatistics(std::string inFileName)
| ^~~~~~~~~~~~~~
FileStatistics.h:21:16: warning: ‘FileStatistics::blankLineCount’ will be initialized after [-Wreorder]
21 | size_t blankLineCount;
| ^~~~~~~~~~~~~~
FileStatistics.h:20:16: warning: ‘size_t FileStatistics::widestLine’ [-Wreorder]
20 | size_t widestLine;
| ^~~~~~~~~~
FileStatistics.cpp:18:1: warning: when initialized here [-Wreorder]
18 | FileStatistics::FileStatistics(std::string inFileName)
| ^~~~~~~~~~~~~~
g++-12 -std=c++20 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast -c -o main.o main.cpp
In file included from main.cpp:5:
CommandLineParser.h:17:7: warning: ‘class CommandLineParser’ has pointer data members [-Weffc++]
17 | class CommandLineParser
| ^~~~~~~~~~~~~~~~~ | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
17 | class CommandLineParser
| ^~~~~~~~~~~~~~~~~
CommandLineParser.h:17:7: warning: but does not declare ‘CommandLineParser(const CommandLineParser&)’ [-Weffc++]
CommandLineParser.h:17:7: warning: or ‘operator=(const CommandLineParser&)’ [-Weffc++]
CommandLineParser.h:36:16: note: pointer member ‘CommandLineParser::args’ declared here
36 | char** args;
| ^~~~
In file included from main.cpp:8:
UtilityTimer.h: In constructor ‘constexpr UtilityTimer::UtilityTimer()’:
UtilityTimer.h:16:9: warning: ‘UtilityTimer::start’ should be initialized in the member initialization list [-Weffc++]
16 | UtilityTimer() = default;
| ^~~~~~~~~~~~
UtilityTimer.h:16:9: warning: ‘UtilityTimer::end’ should be initialized in the member initialization list [-Weffc++]
main.cpp: In function ‘int main(int, char**)’:
main.cpp:51:32: warning: catching polymorphic type ‘class ShowHelpMessage’ by value [-Wcatch-value=]
51 | catch (ShowHelpMessage sh)
| ^~
main.cpp:56:29: warning: catching polymorphic type ‘class showVersions’ by value [-Wcatch-value=]
56 | catch (showVersions sv)
| ^~
main.cpp:60:31: warning: catching polymorphic type ‘class std::exception’ by value [-Wcatch-value=]
60 | catch (std::exception ex)
| ^~
g++-12 -std=c++20 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast -c -o ProgramOptions.o ProgramOptions.cpp
g++-12 -std=c++20 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast -c -o ReportWriter.o ReportWriter.cpp
In file included from ReportWriter.cpp:4:
ReportWriter.h: In constructor ‘ReportWriter::ReportWriter(ProgramOptions&)’:
ReportWriter.h:18:9: warning: ‘ReportWriter::options’ should be initialized in the member initialization list [-Weffc++] | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
18 | ReportWriter(ProgramOptions& progOptions)
| ^~~~~~~~~~~~
g++-12 -std=c++20 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast -c -o StatisticsCollector.o StatisticsCollector.cpp | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
CmdLineFileExtractor
Inconsistent file naming - why Cmd here, but Command elsewhere?
Inconsistent spelling - extension is written as "extention" in several places.
Class SubDirNode is all public, so should probably be a struct instead.
Move-initialise the path member:
fsys::path fileSpec;
bool discovered = false;
bool searchedFiles = false;
SubDirNode(fsys::path path)
: fileSpec{ std::move(path) }
{
}
Class SubDirNode has operator ==, which ought to bind constant this; we should also provide !=:
bool operator!=(const SubDirNode& other) const = default;
Consider providing operator <=> instead, so all comparisons are supported. (Beware: many compilers don't fully support <=> yet).
I don't like the global variables that are shared by all instances of CmdLineFileExtractor (though it's good that they are restricted to file scope). It makes testing harder (even though there's no test suite as yet, that should probably be your next project!). Consider using a pimpl structure as member (that alleviates your concern about transitive includes).
findSubDirs() can be clearer if we express it as a filtered range:
static auto findSubDirs(SubDirNode currentDir)
{
auto is_missing = [](const SubDirNode& branch){
return std::ranges::find(subDirectories, branch) == subDirectories.end();
};
fsys::path cwd = currentDir.fileSpec;
auto subdirs = fsys::directory_iterator{cwd}
| std::views::filter([](auto& f){ return f.is_directory(); })
| std::views::transform([](auto& f)->SubDirNode { return f.path(); })
| std::views::filter(is_missing);
// TODO (C++23): return subdirs | std::ranges::to<std::vector>();
auto newSubDirs = std::vector<SubDirNode>{};
std::ranges::copy(subdirs, std::back_inserter(newSubDirs));
return newSubDirs;
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
(Look, no explicit loops!)
Since we're sorting directory entries, perhaps use a std::set for subDirectories, which would make is_missing() scale much better - or allow set subtraction (std::set_difference) instead.
Obvious simplification here:
root.discovered = (SearchSubDirs) ? false: true;
That can be simply
root.discovered = !SearchSubDirs;
CommandLineParser
This looks like something you might want to reuse in other projects, but it currently has all the arguments hard-coded, meaning it's only suitable for reuse-by-copying. It would be better to have a configurable option parser as a library - look at Python's argparse module for an example in a different language. Obviously, only implement the parts you need, as you need them - and write good unit-tests for the library.
Again, std::move() in the initializer list.
I'm not sure why extractAllArguments() returns the number of flag arguments - the information is never used.
Misleading comment:
// flush the buffer to make sure the entire message is visible
std::cerr << std::endl; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
// flush the buffer to make sure the entire message is visible
std::cerr << std::endl;
Thet should be std::cerr << std::flush, I think, since the help string already ends with a newline.
printHelpMessage() looks over-complicated. Why not just store the help message as a string literal? Then initHelpMessage() could be replaced by
return
" file name or file type specification (*.ext)\n"
"Otions:\n"
"\t-c, --bytes print the byte counts\n"
"\t-m, --chars print the character counts\n"
"\t-l, --lines print the newline counts\n"
"\t-t, --time-execution print the execution time of the program\n"
"\t-L, --max-line-length print the length of the longest line\n"
"\t-w, --words print the word counts\n"
"\t--help display this help and exit\n"
"\t--version output version information and exit\n"
"\t-R, --subdirectories all files in the directory as well as sub directories\n"
"By default the -c -l and -w flags are set; setting any flag"
" requires all flags you want to be set.\n";
and the result used as initializer.
Then printHelpMessage can be replaced by a simple << (and now we don't need a function for that, we can implement -h/--help option, to print the used to std::cout).
Similarly, singleDashArgs and doubleDashArgs could be value-initialised in the constructor's initializer-list (and perhaps all three could be const).
ExecutionCtrlValues
This one is all public, so should be a struct. We can inline it all into the header:
struct ExecutionCtrlValues
{
ProgramOptions options = {};
std::vector<std::string> fileSpecTypes = {};
std::vector<std::string> filesToProcess = {};
void initFromEnvironmentVariables()
{
options.initFromEnvironmentVars();
}
}; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
void initFromEnvironmentVariables()
{
options.initFromEnvironmentVars();
}
};
FileProcessor
Misspelt std::size_t InputBufferSize. Implementations are permitted, but not required, to declare size_t in the global namespace as well as in std. Programs intended to be portable (especially to future compilers!) should always use the qualified version (assuming that none of the deprecated C headers are included (such as <stdlib.h> instead of <cstdlib>)).
Does this class really need a mutable reference to the program options? I don't believe it does, given that ReportWriter can easily accept a const reference.
It certainly doesn't require a mutable for filesToProcess; since it's copying, better to pass by value and then move-construct the member:
FileProcessor::FileProcessor(std::vector<std::string> filesToProcess,
const ProgramOptions& progOptions)
: fileNames { std::move(filesToProcess) },
options{ progOptions }
{
}
processLoop() buffers the entire file in memory:
std::stringstream inputBuffer;
inputBuffer << inStream.rdbuf();
fileAnalyzer.analyzeBuffer(inputBuffer.str());
That seems wasteful for large files. A word-count utility shouldn't even need to buffer complete lines, never mind whole files. That said, for inputs that you can mmap() (and Boost provides an abstraction for this), then that's more efficient than streaming.
FileStatistics
Misspelt std::size_t throughout.
If we provide in-class initializers:
private:
std::size_t totalLineCount = 0;
std::size_t codeLineCount = 0;
std::size_t commentLineCount = 0;
std::size_t whiteSpaceCount = 0;
std::size_t characterCount = 0;
std::size_t wordCount = 0;
std::size_t codeWithCommentCount = 0;
std::size_t widestLine = 0;
std::size_t blankLineCount = 0;
std::string fileName = {};
then we can simplify the constructors:
FileStatistics::FileStatistics() = default; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
then we can simplify the constructors:
FileStatistics::FileStatistics() = default;
FileStatistics::FileStatistics(std::string inFileName)
: fileName{ std::move(inFileName) }
{
}
(I added a move-construction there, too).
This looks very wrong:
float getPerecentageOfCode() {
return static_cast<float>(codeLineCount / totalLineCount);
}
I'm not just talking about the misspelling of "percentage"! If we integer divide, we'll get an integer (probably zero), and then cast that to float. I think that static_cast<float>(codeLineCount) / totalLineCount is what's intended. Of course that's still not a percentage, until we multiply by 100. And double is the natural type for floating-point in C++.
However, if we assume that whole-number precision is enough, then we can work in integers:
std::size_t getPerecentageOfCode() const {
// 100 * codeLineCount / totalLineCount, plus ½ to round to nearest
return (codeLineCount * 200 + totalLineCount) / totalLineCount / 2;
}
Making the signature consistent with the other member functions has advantages when reducing duplication in ReportWriter, too.
main
We need to set locale from the environment, so that the user's expectation of what is whitespace and how bytes map to characters are respected, and so that printing times uses the correct formatting.
This is the way to set user local for both C and C++ functions in the standard library:
std::locale::global(std::locale(""));
ProgramOptions
Use in-class initialisers here, too - always better than constant values in the constructor's initializer-list.
initFromEnvironmentVars() is misleading at best!
We should probably accept a std::string_view here, rather than forcing a conversion:
void ProgramOptions::singleLine(std::string flag, bool flagValue)
{
std::cout << "Flag " << flag << ": Flag value " <<
((flagValue) ? "True" : "False") << "\n";
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
Consider using the std::boolalpha i/o manipulator instead of hand-converting booleans.
The final "\n" is a single character string, so consider '\n' instead (yes, that's a pointless micro-optimisation, but it shows attention to details!).
ReportWriter
This comment may be true on your platform, but it's not required by C++:
// std::vector included by string
Standard library headers are allowed transitively include other headers, but relying on one platforms inclusions is not portable.
Why do we have a shared pointer to our options, when we never share the ownership? We could just have a plain const ProgramOptions member, or perhaps even a reference if we can depend on users.
Instead of always constructing and appending to a string just to write to an output stream, I would do it the other way around:
std::ostream& ReportWriter::printResult(FileStatistics& resultsForOutput, std::ostream& os)
{
if (options->lineCount) {
os << resultsForOutput.getTotalLines() << '\t';
}
if (options->wordCount) {
os << resultsForOutput.getWords() << '\t';
}
if (options->byteCount) {
os << resultsForOutput.getCharacters() << '\t';
}
if (options->charCount) {
os << resultsForOutput.getCharacters() << "\t\t";
}
if (options->maxLineWidth) {
os << resultsForOutput.getWidestLine() << '\t';
}
// End of backwards compatability with wc utility.
if (options->codeCount) {
os << resultsForOutput.getCodeLines() << '\t';
}
if (options->commentCount) {
os << resultsForOutput.getCommentLines() << '\t';
}
if (options->percentages) {
os << resultsForOutput.getPerecentageOfCode() << '\t';
}
if (options->whitespaceCount) {
os << resultsForOutput.getWhitespace() << '\t';
}
if (options->blankLineCount) {
os << resultsForOutput.getBlankLines() << '\t';
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
os << '\t'
<< correctFileSpec(resultsForOutput.getFileName())
<< '\n';
return os;
}
std::string ReportWriter::getResultText(FileStatistics& resultsForOutput) noexcept
{
std::ostringstream os;
printResult(resultsForOutput, os);
return os.str();
}
I'm not sure why there are two tabs after character count, nor why we output getCharacters() for the byte count (are we pretending that all files are in a single-byte character set, perhaps?).
In getColumneHeadingsText() (shouldn't that be "Column", not "Columne"?), we assume that tabs are at standard 8-char intervals, but some terminals can be set to other tab stops. It's safer to use space characters where we need to match the text headers:
firstLine += "Characters\t";
secondline += " \t";
We probably should be using std::setw manipulator when writing values, to be consistent with these. And that's how we get the values right-aligned, to improve usability.
In either case, this is all quite tricky for localisation. We probably want to have a structure for each column containing its header lines (without the tabs), use the max length of the two lines to determine the necessary column width (perhaps taking into account a reasonable max value to accommodate), and use that width for printing both header lines and the values. That's probably worth defining a simple structure for (private to the implementation file, of course).
correctFileSpec() looks like it splits names on \ regardless of whether or not that is a directory separator. We don't want that - and std::filesystem::path provides a filename member that looks like what's wanted here.
To get consistent columns and headers, it's worth defining a structure that represents each column:
struct Column {
bool ProgramOptions::* flag;
std::size_t (FileStatistics::*count)() const;
std::string header[2];
int width; | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
Column(bool ProgramOptions::* flag,
std::size_t (FileStatistics::* count)() const,
std::string first, std::string second, std::size_t width = 0)
: flag { flag },
count { count },
header { std::move(first), std::move(second) },
width { static_cast<int>(std::max({header[0].size(), header[1].size(), width})) }
{}
};
static const Column columns[] =
{
{ &ProgramOptions::lineCount,
&FileStatistics::getTotalLines,
"Lines", "of Text", 6 },
{ &ProgramOptions::wordCount,
&FileStatistics::getWords,
"Words", "", 7 },
{ &ProgramOptions::byteCount,
&FileStatistics::getCharacters,
"Bytes", "", 8 },
{ &ProgramOptions::charCount,
&FileStatistics::getCharacters,
"Characters", "", 8 },
{ &ProgramOptions::maxLineWidth,
&FileStatistics::getWidestLine,
"Length of", "Longest Line", 5 },
{ &ProgramOptions::codeCount,
&FileStatistics::getCodeLines,
"Lines", "of Code", 6 },
{ &ProgramOptions::commentCount,
&FileStatistics::getCommentLines,
"Lines of", "Comments", 6 },
{ &ProgramOptions::percentages,
&FileStatistics::getPerecentageOfCode,
"Percentage of", "Lines of Code", 2 },
{ &ProgramOptions::whitespaceCount,
&FileStatistics::getWhitespace,
"Whitespace", "Characters", 8 },
{ &ProgramOptions::blankLineCount,
&FileStatistics::getBlankLines,
"Blank", "Lines", 6 },
};
Then use the same structure for producing the headers and the content:
std::ostream& ReportWriter::printResult(FileStatistics& resultsForOutput, std::ostream& os)
{
for (auto const& col: columns) {
if (options.*(col.flag)) {
os << std::setw(col.width)
<< (resultsForOutput.*col.count)()
<< '\t';
}
}
os << correctFileSpec(resultsForOutput.getFileName())
<< '\n';
return os;
} | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
os << correctFileSpec(resultsForOutput.getFileName())
<< '\n';
return os;
}
std::string ReportWriter::getResultText(FileStatistics& resultsForOutput) noexcept
{
std::ostringstream os;
printResult(resultsForOutput, os);
return os.str();
}
std::string ReportWriter::getColumnHeadingAsOneString() noexcept
{
std::ostringstream os;
printColumnHeadings(os);
return os.str();
}
std::ostream& ReportWriter::printColumnHeadings(std::ostream& os) noexcept
{
for (int i = 0; i <= 1; ++i) {
for (auto const& col: columns) {
if (options.*(col.flag)) {
os << std::setw(col.width)
<< (col.header[i])
<< '\t';
}
}
os << '\n';
}
return os;
}
StatisticsCollector
This uses std::uintmax_t without including <cstdint> (this is quite pedantic: although <filesystem> declares a function returning this type, it doesn't have to provide this name).
It misspells std::size_t throughout.
I don't think that we should be passing strings by value or by mutable reference in any of these functions. Just pass by const& (there's only a couple of arguments to change to const_iterator if we use auto for all the locals), or pass std::string_view instead.
This code looks like it counts file bytes, not how many characters they represent:
std::uintmax_t bufferSize = std::filesystem::file_size(fileStatistics.getFileName());
fileStatistics.setCharCount(bufferSize);
You've hit the <cctype> trap here:
while (isspace(*currentChar))
std::isspace() (another misspelling) requires positive values, so you need to convert to unsigned char before the promotion to int:
while (std::isspace(static_cast<unsigned char>(*currentChar))) | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
Counting words seems to be based on whitespace/non-whitespace transitions, but I'm not sure that's a useful measure. Personally, I would discount any "word" not containing at least one alphanumeric character. And I'd consider adding some extra rules to allow & and similar as exceptions (but I probably wouldn't consider it very seriously!).
updateWidestLine() doesn't use the std::string line variable that it creates. And I think I'd prefer it to return the new currentChar rather than modifying through the reference.
UtilityTimer
Missing include of <ctime>, needed by std::ctime(). Though I'd advise against that function, as it always produces American output, regardless of locale.
end doesn't need to be a member, since it's set and used only in stopTimerAndReport.
We should probably be using the steady (or perhaps the high-precision) clock for accurate measurement. I'd use an alias:
public:
using clock = std::chrono::steady_clock;
We'll still need the system clock for printing the time of day, if we really think that's valuable.
It probably makes sense to initialise start to the present time, which will save users needing to explicitly start the timer if it's constructed at the right time.
private:
clock::time_point start = clock::now();
stopTimerAndReport() shouldn't be taking its string argument by copy - use a string-view here. I'd use the standard log stream for this, and combine the multiple separate strings:
void stopTimerAndReport(std::string_view whatIsBeingTimed)
{
clock::time_point end = clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
double ElapsedTimeForOutPut = elapsed_seconds.count(); | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
c++, performance, reinventing-the-wheel, c++20
using std::chrono::system_clock;
auto const now = system_clock::to_time_t(system_clock::now());
std::clog << "finished " << whatIsBeingTimed << std::put_time(std::localtime(&now), "%c")
<< "\nelapsed time in seconds: " << ElapsedTimeForOutPut << "\n\n\n";
}
It certainly shouldn't be noexcept, since any of those << can throw. | {
"domain": "codereview.stackexchange",
"id": 44125,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, reinventing-the-wheel, c++20",
"url": null
} |
validation, vb.net
Title: Validate 10 digits on a few conditions
Question: I want to write a function that validates the German tax identification number (Steuer-ID).
The identification number consists of eleven digits. The last digit is only for checking. This is not what this question is about.
The first ten digits of the identification number contain one digit exactly twice and another digit not at all (as of 2016, a triple occurring digit is also possible, correspondingly then two digits not at all; in case of three equal digits, only two may be in immediate succession, but not all three), the other eight (as of 2016: also seven) digits each exactly once. The first digit must not be 0.
My thought process:
With a length of 10 digits, one digit must occur twice anyway. But it may occur three times. So I check if the groupList.Count property is 8 or 9. Probably the Boolean "double_or_triple_occurrence" is unnecessary then...
But there must not be a double occurrence of another digit.
there must not be 3 of the same digits directly behind each other, only 2 of them.
For Germans among the readers, this is the Wikipedia site.
This is how I implemented it:
Public NotInheritable Class FormMain
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = ""
End Sub
Private Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click
Validate_SteuerId(TextBox1.Text)
End Sub
Private Sub Validate_SteuerId(StringToCheck As String)
Label1.Text = ""
If String.IsNullOrEmpty(StringToCheck) Then
Label1.Text = "Leer" ' Empty
Return
End If
If StringToCheck.StartsWith("0") Then
Label1.Text = "Die erste Ziffer darf nicht 0 sein." ' The first digit must not be zero.
Return
End If | {
"domain": "codereview.stackexchange",
"id": 44126,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "validation, vb.net",
"url": null
} |
validation, vb.net
If StringToCheck.Length < 11 Then
Label1.Text = "Zu kurz" ' too short
Return
ElseIf StringToCheck.Length > 11 Then
Label1.Text = "Zu lang" ' too long
Return
End If
Dim myInts As New List(Of Integer)
Dim charArray As Char() = StringToCheck.ToArray()
For i As Integer = 0 To charArray.Length - 2 Step 1
Dim rslt As Integer
If Integer.TryParse(charArray(i), rslt) Then
myInts.Add(rslt)
Else
Label1.Text = "Fehler beim Parsen" ' error
Return
End If
Next
If Not Check_occurrence_of_each_digit(myInts) Then
Label1.Text = "Fehler"
End If
End Sub
Private Function Check_occurrence_of_each_digit(Ints As List(Of Integer)) As Boolean
Dim groupList As List(Of IGrouping(Of Integer, Integer)) = Ints.GroupBy(Function(x) x).Where(Function(y) y.Count <= 3).ToList()
If groupList.Count <> 8 AndAlso groupList.Count <> 9 Then
Return False
End If
Dim double_or_triple_occurrence As Boolean = False
For i As Integer = 0 To groupList.Count - 1 Step 1
Dim currentNumber As Integer = groupList(i).Key
Dim howOften As Integer = groupList(i).Count
If howOften = 2 OrElse howOften = 3 Then
double_or_triple_occurrence = True
End If
Debug.WriteLine($"Die Zahl {currentNumber} kommt {howOften} Mal vor.")
Next
If double_or_triple_occurrence Then
Dim bools As New List(Of Boolean)
For i As Integer = 0 To Ints.Count - 1 Step 1
Dim u As Integer = i
bools.Add(Ints.Any(Function(x) x = u))
Next
If bools.Where(Function(x) x = False).Count > 1 Then
Return False
End If
End If | {
"domain": "codereview.stackexchange",
"id": 44126,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "validation, vb.net",
"url": null
} |
validation, vb.net
'max 2 same digits one after the other
Dim old As Integer
Dim middle As Integer
Dim farest As Integer
For i As Integer = 0 To Ints.Count - 3 Step 1
old = Ints(i)
middle = Ints(i + 1)
farest = Ints(i + 2)
If old = Ints(i + 1) AndAlso middle = Ints(i + 1) AndAlso farest = Ints(i + 1) Then
Return False
End If
Next
Return True
End Function
End Class
I would like to ask you to shorten the amount of code lines. I appreciate.
Answer: There is no separation between interface and logic. That also makes it difficult to reuse that function in another context, for instance in a different form. Suggestion: convert your routine into a stand-alone function. All it has to do is to return a result, that can be used by the caller. It should not bother with the UI at all.
Then I assume we will want the function to return two values: one boolean value that tell us whether the check is successful, and another optional value (string) containing a description of the error, if any.
Afaik a VB.net function can return only one value unlike Python for example. To get round this problem you could use a structure or another composite data type. Or you could simply pass additional arguments to your function as ByRef and retrieve their resulting values, after they have been changed by the function.
My proposed implementation is to return a boolean value, and return the error message as a ByRef argument like this:
Private Function Validate_SteuerId(ByVal StringToCheck As String, Optional ByRef ValidationResults As String = "") As Boolean
If String.IsNullOrEmpty(StringToCheck) Then
ValidationResults = "Leer" ' Empty
Return False
End If
' more stuff goes here
Return True ' default outcome, make sure all code paths return a value
End Function | {
"domain": "codereview.stackexchange",
"id": 44126,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "validation, vb.net",
"url": null
} |
validation, vb.net
Return True ' default outcome, make sure all code paths return a value
End Function
This is pretty much like you did for Check_occurrence_of_each_digit, we just added an optional return value.
Now your function is completely independent from the form. It's easy refactoring.
And you can call the function like this when clicking on the button:
Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
Dim reason As String = ""
If Check_SteuerId(Me.TextBox1.Text, reason) Then
Label1.Text = "Validation OK"
Else
Label1.Text = "Validation failed - reason: " & reason
End If
End Sub
Alternatives: check if your version of VB.net provides the Tuple or KeyValuePair types.
These two blocks could be merged into one:
If StringToCheck.Length < 11 Then
Label1.Text = "Zu kurz" ' too short
Return
ElseIf StringToCheck.Length > 11 Then
Label1.Text = "Zu lang" ' too long
Return
End If
Just check if the length is 11, otherwise return an error message saying that 11 characters are expected, that should be enough for the developer. He/she can easily figure out if the input value is too short or too long.
But you can simplify logic a little bit: instead of checking that the length is 11 digits, that the string does not begin with zero etc, you could use a regular expression.
Add this import at the top of your code:
Imports System.Text.RegularExpressions
Then put the block inside your function:
Dim re As New Regex("^[1-9][0-9]{10}$")
If Not re.Match(StringToCheck).Success Then
ValidationResults = "Expected: a string of 11 digits that does not begin with zero"
Return False
End If | {
"domain": "codereview.stackexchange",
"id": 44126,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "validation, vb.net",
"url": null
} |
validation, vb.net
Using regular expressions and backreferences, it is also possible to verify certain patterns, for example if you wanted to check that the string contains at least one digit repeated exactly 3 times in a row you could do this:
Dim matches As MatchCollection = Regex.Matches(TextBox1.Text, "(.)\1{2}")
Console.WriteLine("matches: " & matches.Count)
' Loop over matches.
For Each m As Match In matches
' Loop over captures.
For Each c As Capture In m.Captures
' Display.
Console.WriteLine("Index={0}, Value={1}", c.Index, c.Value)
Next
Next
Thus, 12220333456 will return two matches: 222 and 333 respectively. Accordingly matches.Count will be equal to 2.
Now if you want to make sure that no digit is repeated more than twice in a row, you could write Regex.Matches(TextBox1.Text, "(\d)\1{2,}") and verify that matches.Count = 0. Notice the trailing comma after the 2 - it means two or more repetitions of the previously matched digit. 333 will match but 22 won't.
The dot in a regex means any character. \d represents a single digit. Here we are being more precise and match on digits only.
Regular expressions are very powerful but can get very complex too. For some "simple" checks they are convenient shorthand methods and could replace some of your parsing routines. | {
"domain": "codereview.stackexchange",
"id": 44126,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "validation, vb.net",
"url": null
} |
beginner, console, go, concurrency, ssl
Title: Golang HTTPS certificate expiry checking CLI tool
Question: I am a beginner at using Golang, I would like advice about the following program. It is a CLI tool that can check the expiration dates of HTTPS certificates concurrently. I have only used the standard library and would appreciate any feedback that I can learn from.
package main
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net"
"os"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const programVersion = "1.0.0"
func printHelp() {
fmt.Printf("Usage: %s [options] url\n\n", os.Args[0])
fmt.Println("This application determines when the SSL certificate will expire for the provided url.")
fmt.Println()
fmt.Println("Notes:")
fmt.Println("- File extension arguments should be provided without a protocol (e.g., \"example.com\").")
fmt.Println("- This application assumes that the the TLS connection should be made over port 443 unless a port is already provided in the URL (e.g., \"smtp.example.com:465\").")
fmt.Println("- This application does not attempt to modify the provided URL.")
fmt.Println()
fmt.Println("Program options:")
flag.PrintDefaults()
}
type JsonSuccessResponse struct {
Url string `json:"url"`
NotAfter time.Time `json:"notAfter"`
NotBefore time.Time `json:"notBefore"`
}
type JsonFailureResponse struct {
Url string `json:"url"`
Error string `json:"error"`
}
type JsonResponse struct {
Data []JsonSuccessResponse `json:"data"`
Errors []JsonFailureResponse `json:"errors"`
} | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
func buildJsonReponse(data chan JsonSuccessResponse, failures chan JsonFailureResponse) JsonResponse {
toReturn := JsonResponse{}
for jsonSuccessResponse := range data {
toReturn.Data = append(toReturn.Data, jsonSuccessResponse)
}
sort.SliceStable(toReturn.Data, func(i, j int) bool { return toReturn.Data[i].Url < toReturn.Data[j].Url })
sort.SliceStable(toReturn.Data, func(i, j int) bool { return toReturn.Data[i].NotAfter.Before(toReturn.Data[j].NotAfter) })
for jsonFailureResponse := range failures {
toReturn.Errors = append(toReturn.Errors, jsonFailureResponse)
}
sort.SliceStable(toReturn.Errors, func(i, j int) bool { return toReturn.Errors[i].Url < toReturn.Errors[j].Url })
return toReturn
}
func outputResult(jsonResponse JsonResponse, outputToJsonP bool) error {
if outputToJsonP {
mJson, err := json.Marshal(jsonResponse)
if err != nil {
return err
}
fmt.Println(string(mJson))
} else {
now := time.Now()
for _, jsonSuccessResponse := range jsonResponse.Data {
fmt.Println("Checking", jsonSuccessResponse.Url, "cert expiration dates against:", now)
startInHours := int64(now.Sub(jsonSuccessResponse.NotBefore).Hours())
if startInHours < 0 {
fmt.Println("Not valid until ", jsonSuccessResponse.NotBefore)
} | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
expiryInHours := int64(jsonSuccessResponse.NotAfter.Sub(now).Hours())
if expiryInHours <= 0 {
fmt.Println("Expired on ", jsonSuccessResponse.NotAfter)
} else {
if expiryInHours < 24 {
fmt.Println("\tWill expire on", jsonSuccessResponse.NotAfter, "which is in", expiryInHours, "hours.")
} else {
fmt.Println("\tWill expire on", jsonSuccessResponse.NotAfter, "which is in", expiryInHours/24, "days and", expiryInHours%24, "hours.")
}
}
}
for _, jsonFailureResponse := range jsonResponse.Errors {
fmt.Println("Failed to check HTTPS certification for", jsonFailureResponse.Url, "with error:", jsonFailureResponse.Error)
}
}
return nil
}
func checkHttpsCertificate(ctxt context.Context, url string, timeoutInSeconds uint64, verifySsl bool) (JsonSuccessResponse, error) {
var toReturn JsonSuccessResponse
if !strings.ContainsAny(url, ":") {
url = url + ":443"
}
toReturn.Url = url
dialer := tls.Dialer{
Config: &tls.Config{InsecureSkipVerify: !verifySsl},
}
connection, err := dialer.DialContext(ctxt, "tcp", url)
if err != nil {
if terr, ok := err.(net.Error); ok && terr.Timeout() {
return JsonSuccessResponse{}, errors.New("I/O Timeout (DF95AE47-F677-40D0-B1F3-209DA7266AAC). Failed to connect to " + url + " in " + strconv.FormatUint(timeoutInSeconds, 10) + " seconds.")
} else {
return JsonSuccessResponse{}, fmt.Errorf("SSL certificate err (%w): "+err.Error(), err)
}
}
defer connection.Close()
tlsConnection := connection.(*tls.Conn)
connectionState := tlsConnection.ConnectionState | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
tlsConnection := connection.(*tls.Conn)
connectionState := tlsConnection.ConnectionState
if len(connectionState().PeerCertificates) > 0 {
// Relies on ordering: "The first element is the leaf certificate that the connection is verified against."
firstCertificate := connectionState().PeerCertificates[0]
toReturn.NotAfter = firstCertificate.NotAfter
toReturn.NotBefore = firstCertificate.NotBefore
return toReturn, nil
} else {
return JsonSuccessResponse{}, errors.New("Encountered HTTPS certificate with no peer certificates (internal invariant broken: a9f6135d-93fc-4319-891d-c67bf5a149fc) for URL: " + url)
}
}
func processUrlsParallel(ctxt context.Context, urls []string, timeoutInSeconds uint64, verifySsl bool) (chan JsonSuccessResponse, chan JsonFailureResponse) {
wg := &sync.WaitGroup{}
data := make(chan JsonSuccessResponse, len(urls))
failures := make(chan JsonFailureResponse, len(urls))
for _, url := range flag.Args() {
wg.Add(1)
go func(ctxt context.Context, url string, w *sync.WaitGroup, data chan JsonSuccessResponse, failures chan JsonFailureResponse, timeoutInSeconds uint64, verifySsl bool) {
defer w.Done()
jsonResponse, err := checkHttpsCertificate(ctxt, url, timeoutInSeconds, verifySsl)
if err != nil {
failures <- JsonFailureResponse{
Url: url,
Error: err.Error(),
}
} else {
data <- jsonResponse
}
}(ctxt, url, wg, data, failures, timeoutInSeconds, verifySsl)
}
wg.Wait()
close(data)
close(failures)
return data, failures
}
func main() {
var (
helpNeeded, outputJson, showVersion, verifySsl bool
timeoutInSeconds uint64
) | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
flag.BoolVar(&outputJson, "json", false, "Output json to STDOUT")
flag.BoolVar(&helpNeeded, "h", false, "Show help message")
flag.BoolVar(&showVersion, "v", false, "Show program version")
flag.BoolVar(&verifySsl, "verify-ssl", false, "Verify SSL certificate")
flag.Uint64Var(&timeoutInSeconds, "timeout", 5, "Timeout in seconds")
flag.Parse()
maxThreads, convErr := strconv.ParseInt(os.Getenv("MAX_THREADS"), 10, 32)
if int(maxThreads) > 0 && convErr == nil {
runtime.GOMAXPROCS(int(maxThreads))
}
if helpNeeded {
printHelp()
return
}
if showVersion {
fmt.Println(programVersion)
return
}
if timeoutInSeconds < 1 {
log.Fatal("Provided timeout must be greater than zero.")
}
if len(flag.Args()) < 1 {
printHelp()
log.Fatal("Please provide argument for url.")
}
ctxt, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutInSeconds)*time.Second)
data, failures := processUrlsParallel(ctxt, flag.Args(), timeoutInSeconds, verifySsl)
cancel() // Cancel context as soon as processUrlsParallel returns
jsonResponse := buildJsonReponse(data, failures)
err := outputResult(jsonResponse, outputJson)
if err != nil {
log.Fatal("Internal Error (GUID: e6ad5934-0a7d-4100-9889-7274058e60db): Failed to marshall internal structure to JSON")
}
}
Answer: At first glance
Having just skimmed some of the code you posted, a couple of things jumped out right away: | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
printHelp: If I were to provide a description of what my tool does, I'd call the flag.Usage function, and I'd certainly avoid multiple calls to fmt.Println or fmt.Printf. Golang has multi-line strings (using backtick as delimiter)
runtime.GOMAXPROCS(int(maxThreads)) is something that is fairly common in code written by people relatively new to golang. There seems to be some uncertainty/confusion as to what go routines actually are, and how much of a say you get in whether a routine spawns a thread or not. The long and short of it is that you don't get too much of a say. GOMAXPROCS can still result in more threads being spawned (due to syscalls). It's useful if you want to run a process in the background without hogging too many resources, but for CLI tools that you run and wait for a result, there's really little to no point to doing this. The go runtime isn't perfect, but it handles concurrency very well, and yes, that's concurrency: not all routine is limited to its own thread, so setting GOMAXPROCS will not limit the number of routines that are concurrently running anyway.
Coding standards are important. Back in the early days a lot of people criticised golang for being "too opinionated" (the whole gofmt enforcing tabs, K&R style brackets etc...). This has proven to be a great thing, increasing readability and collaboration across the ecosystem. Aside from the gofmt stuff, it's therefore strongly advised to stick to the Go codereview comments. Most notably: initialisms (which I see scattered throughout your code) should be capitalised accordingly: Not Url or Json, but rather URL and JSON. You can see this in golang's own standard library in places like net/http with functions like ListenAndServeTLS
There are more substantial issues which I'll cover next, most notably in the rather unfortunately named processUrlsParallel. Unfortunate because Parallel should be concurrent, and the initialism should be URLs. The bigger issue there though, is what we'll tackle now | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
Use of buffered channels
The processUrlsParallel function uses buffered channels. That's great. buffered channels are awesome, and very useful. However, you're resorting to using them because, from the callers' point of view, processUrlsParallel is not a parallel call, but rather a blocking call. You're returning channels, but by the time the caller can set to work with them, they've been filled to the brim already. Why bother? Why not return 2 slices instead? Functionally, they are interchangeable in your case. Using channels here is perfectly valid, but I'd change a couple of things:
I'd return directional channels, in this case I'd return channels that can only be used to read from. This serves to write self-documenting code, and in larger projects avoids silly bugs caused by someone mistakenly writing some value onto the wrong channel.
The URL's are CLI args, so you can pass them in as a slice, but if you were to read them from a file, you might want to pass them through a channel of their own. This will allow you to start processing the URL's while reading them. The function would then look something like this:
func processURLs(ctx context.Context, uCh <-chan string, timeout time.Duration, verifySSL bool) (<-chan JSONSuccess, <-chan JSONErr) | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
Now you'll notice I've shortened the variable names. This is common in go code. I personally like it this way, because it becomes a barrier that makes it harder to write incredibly long and verbose functions. It keeps my code tidier. The timeout type likewise communicates to the caller, and more importantly reader/maintainer what this value is meant to express. The channels are all directional, which immediately tells me this function will read data from the uCh channel, and return 2 channels that I'm expected to read from. Now because I'm passing in a channel, it's impossible to do the same thing you are doing (which is to use a waitgroup, fill the channel buffers and close the channels). I have no way to know how many URL's I'm expected to process. Not to worry, we have a context, and we know we're done once our uCh is closed and empty. So let's implement that:
func processURLs(ctx context.Context, uCh <-chan string, timeout time.Duration, verifySSL bool) (<-chan JSONSuccess, <-chan JSONErr) {
sCh, eCh := make(chan JSONSuccess, 10), make(chan JSONErr) // make channels with some buffer
go func() {
defer func() {
// cleanup when this routine exists
close(sCh)
close(eCh)
}()
// read the URL's. This loop will break once the channel is both empty and closed
for URL := range uCh {
select {
case <-ctx.Done():
return // the context was cancelled, indicating we're shutting down
default:
// we have a URL, check it
resp, err := checkHTTPSCert(context.WithTimeout(ctx, timeout), URL, verifySSL)
// depending on the result, write to the appropriate channel
if err != nil {
eCh <- err
} else {
sCh <- resp
}
}
}
}()
return sCh, eCh // return channels right away
} | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
That's it. Nice and easy. To use a slice, you can just replace the argument, and the loop in the routine, but the rest works all the same. If you want to support both, you can just create a helper function that makes a channel, and pushes the slice on there.
As far as the function itself goes, I suppose the biggest difference is here:
checkHTTPSCert(context.WithTimeout(ctx, timeout), URL, verifySSL) | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
Rather than passing through the timeout value, I'm providing a context, wrapped around the context that this function is using, and configure it to have a timeout. When using the net/http package (and indeed many other packages that handle connections), a cancelled context (or a timed-out one) will result in pending requests/transactions getting cancelled. We don't really have to worry about that anymore. What's more: these contexts are wrapped. If the caller (in your case the main function) passes in a context that will be cancelled in case the application received a KILL/TERM signal, that context cancellation is propagated automatically. ongoing requests, routines, etc... can all be notified and gracefully return. For a CLI tool like this, it's not a massive deal, but again: for larger projects, this quickly becomes a necessity. Moving on to your checkHttpsCertificate function (which receives but seemingly doesn't use the timeout argument!):
Other issues
The bulk of this function could be rewritten to be a bit nicer, and I might go through in a bit more detail should I find some more spare time, but for now I'll point to this particular function to point some gripes I have looking at your code. Some of these issues are found throughout your code, like not retunring early or having pointless else clauses:
return early - only if, no else
This function in particular is rather smelly, the way it ends with:
if len(connectionState().PeerCertificates) > 0 {
// Relies on ordering: "The first element is the leaf certificate that the connection is verified against."
firstCertificate := connectionState().PeerCertificates[0]
toReturn.NotAfter = firstCertificate.NotAfter
toReturn.NotBefore = firstCertificate.NotBefore
return toReturn, nil
} else {
return JsonSuccessResponse{}, errors.New("Encountered HTTPS certificate with no peer certificates (internal invariant broken: a9f6135d-93fc-4319-891d-c67bf5a149fc) for URL: " + url)
} | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
The first if ends in a return, why have that else there? It's completely pointless!
if len(connectionState().PeerCertificates) > 0 {
// do stuff
return toReturn, nil
}
return JsonSuccessResponse{}, errors.New("Encountered HTTPS certificate with no peer certificates (internal invariant broken: a9f6135d-93fc-4319-891d-c67bf5a149fc) for URL: " + url)
Likewise, this entire function keeps calling connectionState() over and over again. Just assign the return value to a variable, avoid redundant calls like this. So instead of:
connectionState := tlsConnection.ConnectionState
just write
cState := tlsConnection.ConnectionState()
if len(cState.PeerCertificates) > 0 {
}
Further up in this same function, you have a similar bit of code smell in this bit:
if err != nil {
if terr, ok := err.(net.Error); ok && terr.Timeout() {
return JsonSuccessResponse{}, errors.New("I/O Timeout (DF95AE47-F677-40D0-B1F3-209DA7266AAC). Failed to connect to " + url + " in " + strconv.FormatUint(timeoutInSeconds, 10) + " seconds.")
} else {
return JsonSuccessResponse{}, fmt.Errorf("SSL certificate err (%w): "+err.Error(), err)
}
} | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
}
Again, the else is completely unnecessary. I also fail to see the point in wrapping an error, and at the same time concatenating its string representation to the format string. What if the error string contains %s, for example. This is not only pointless (errors can be unwrapped after all), it's also fragile. The first error here is a nightmare of concatenation, with manual formatting for things that you can have golang format for you by just using the correct type (time.Duration).
Additionally, golang errors should start with a lower-case character as per convention. Most linters will complain about this code. With that said, let's rewrite both errors:
errors.New("I/O Timeout (DF95AE47-F677-40D0-B1F3-209DA7266AAC). Failed to connect to " + url + " in " + strconv.FormatUint(timeoutInSeconds, 10) + " seconds.")
// becomes
errors.New("connection to URL %s failed (timeout limit %s)", URL, timeout) // assumes timeout is of time time.Duration, will print 10s for 10 seconds...
fmt.Errorf("SSL certificate err (%w): "+err.Error(), err)
// becomes either one of:
fmt.Errorf("certificate error (%w): ", err)
fmt.Errorf("certificate error: %s", err) // not wrapped, but err.Error() gets added
Force error checks
Now this brings me to the biggest issue I have with this function. People often complain how go forces you to check errors as return values, which leads to more verbose code. There's something to be said for this, for sure, but the way you're communicating errors is the worst of both worlds. Because, even in error cases, you're returning a valid JSONSuccessResponse object, it's very easy to picture a scenario where someone writes:
resp, _ := checkSSLCert(...)
// or even
resp := checkSSLCert(...) | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
Whether this call is successful or not, the resp variable will be set. Compare this to a version of this function which returns a pointer to JSONSuccess on success, and nil otherwise. All of your return statements look nicer:
return nil, errors.New("connection to URL %s failed (timeout limit %s)", URL, timeout)
And the caller is forced to check the error. Failing to do so will cause their code to crash on error:
resp, _ := checkSSLCert(...) // fails
resp.AccessField // runtime panic, resp is nil
URGENT CHANGE
Just because I've scrolled through your code a few times, and each time felt like somewhere, somehow, a unicorn was dying, please, please, please fix outputResult. Change its current:
if outputToJsonP {
mJson, err := json.Marshal(jsonResponse)
if err != nil {
return err
}
fmt.Println(string(mJson))
} else {
To remove that bloody else that wraps the entire function. Simply write
if outputToJsonP {
mJson, err := json.Marshal(jsonResponse)
if err != nil {
return err
}
fmt.Println(string(mJson))
// return early HERE
return nil
}
// rest of the function here
return nil | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
Right, I though this was going to be a short review, I digressed quite a bit, but I do hope that, despite my just typing out what essentially is a stream of consciousness, you gain something from this.
I am aware that I can sometimes come across as harsh/blunt. Just keep in mind that none of this criticism is in any way meant as a personal attack, or aimed to be discourage you. I've always felt that I learned more/faster after a particularly brutally honest review of my work.
Replies to comments
So you've raised a couple more questions in comments. I'll add the answers here for clarity and completeness.
First up: does the channel buffer in my example limit the number of routines? The short answer is no. Earlier on, I included an example of the processURLs function with channels buffered to a size of 10. The being made here is that connecting to, and checking the certs will take longer than pushing the result on the channel, and the routine consuming said channel data will do so faster than the requests themselves (otherwise, using routines in the way you are doing doesn't make all that much sense). In my example, I'm checking all URL's in a single routine. I didn't explicitly say otherwise, but in reality, each URL would be checked in its own routine. I'll rewrite the processURLs function here, this time adding the "1 routine per URL" bit. In doing so, I'll also give an example of when you should pass an argument to an anonymous function:
func processURLs(ctx context.Context, uCh <-chan string, timeout time.Duration, verifySSL bool) (<-chan JSONSuccess, <-chan JSONErr) {
sCh, eCh := make(chan JSONSuccess, 10), make(chan JSONErr) // make channels with some buffer
wg := sync.WaitGroup{} // create a waitgroup
go func() {
defer func() {
wg.Wait() // now add the waitgroup so as to not close the channels too soon
// cleanup when this routine exists
close(sCh)
close(eCh)
}() | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
close(sCh)
close(eCh)
}()
// read the URL's. This loop will break once the channel is both empty and closed
for URL := range uCh {
wg.Add(1) // we're adding a new routine
// start the routine for this particular URL
go func(URL string) { // takes the current value as an argument
defer wg.Done() // decrease waitgroup
select {
case <-ctx.Done():
return // the context was cancelled, indicating we're shutting down
default:
// we have a URL, check it
resp, err := checkHTTPSCert(context.WithTimeout(ctx, timeout), URL, verifySSL)
// depending on the result, write to the appropriate channel
if err != nil {
eCh <- err
} else {
sCh <- resp
}
}
}
}(URL) // pass in URL value
}()
return sCh, eCh // return channels right away
} | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
So we've added a waitgroup. Not to have this function wait for all the work to be done, but more because we need to make sure that we don't close the channels before all routines have returned (avoiding writes to a closed channel).
You can also see that the URL variable is passed in as an argument to our inner routine. If we didn't do this, the routine would just reference the outer URL variable, which could get reassigned before the routine gets created/executed. We need to provide the inner routine with the specific value for URL we want to use. If we didn't do this, we could end up in situations that -in pseudo code- boil down to something like this:
v := <-ch
go func() { fmt.Println(v) }()
v = <-ch // update v
<start the previously scheduled routine, which will now print out the new value of v
By masking the outer variable (URL or in the pseudo-code v), each routine has its own variable masking the outer one, set to the specific value at the point the routine was declared:
v := <-ch
go func(v1 any) { fmt.Println(v1) }(v)
v = <-ch // update v
go func(v2 any) { fmt.Println(v2) }(v)
Now we'll get the expected output. It's still possible to get the output of v2 first, and then v1, but both will be printed regardless.
Other, more niche, situations where you may want to pass in variables to pass in variables as arguments is when you're masking imports. 99% of times, this is the result of unfortunate package/variable naming, but it can sometimes be used as a safeguard, preventing you from making certain calls in the wrong place. This can be used in very rare (agian: 99% of the times, this is code smell), highly concurrent bits of code:
package foo
import (
// a bunch of packages|
"my.complex.mod/concurrent/niche"
"my.complex.mod/concurrent/danger"
) | {
"domain": "codereview.stackexchange",
"id": 44127,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, console, go, concurrency, ssl",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.