is declaring variables in between code bad practice? [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I realize this might be a controversial topic, but as a prospective developer who is entering industry in a couple of weeks, I'm trying to get an idea of the do's and dont's when writing code.
One of the things that even my professors seem to be at odds on is where should local variables be declared. I've had professors insist that the only way is to declare them all at the start of the function. This has the benefit of not reconstructing a new object every time a loop is entered, for example. But it has the draw back of making logic harder to follow since you don't know which variables are used in which scopes.
Other professors say that it is good practice to declare them when you use them. Even if it's in the middle of the lines of code. This seems to be more of a Python style of coding and could possibly clutter the code with, verbose, and unnecessary type information. Also, this could incur a performance penalty since the object will get constructed and then destructed in every iteration of the loop.
Then I had another professor say to declare them at the start of their respective scopes. So ideally, after each { there would be declarations for all the variables used in that scope. This seems to offer the best readability, and the worst performance since now the object could potentially be constructed and then assigned to (two separate, possibly expensive operations) in every loop iteration.
I hope you can see how a new programmer can get confused about what format to follow. So is there consensus in the work field about which style is the "best"?

Related

C++: Is it alright to keep creating new variables? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am new to C++ and I have a general question. In order to solve any question in the exercises of the book I am learning from, while I am able to successfully solve the questions, I usually end up creating a lot of new variables within functions in addition to the ones that I have already initialised. For some reason, this worries me because I feel that I am writing inefficient code that might hog resources if I follow this practice for more complex programmes. Am I wrong in thinking this way? Are there any best practices regarding initialising and declaring new variables?
EDIT: I forgot to add, before resolving any question, I tend to convert the solution into plain English and then attempt to draw the program structure.
Normally compilers do liveness analysis of variables during the compilation of your code. Variables are considered live only starting from their assignment till their last use - optimizing compilers are capable of reducing the amount of local storage on the stack that is required by sequentially used variables (sometimes they even can eliminate their use entirely or keep them in registers only for a short period of time).

Is it considered bad programming practice to have a large number of overloaded class constructors? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm making a calendar application in c++ and I'm making a great number of overloaded constructors for the appointment class depending on the information provided(e.g. if i have a start time for the event but no end time, and a location, but no attached contacts)
class Appointment {
public:
//overloaded Constructors
Appointment();
Appointment(Date);
Appointment(Date,Date);
Appointment(Date,Date,std::string);
Appointment(Date,Date,std::string,std::string);
Appointment(Date,Date,std::string,std::string,Contact);
etc. etc. Is there a better way to do this?
You could either:
Create the object (a valid one) and set its properties afterwards via interface setters (since it seems an object can have a variable number of properties this seems like a good choice)
Use default parameters, e.g.
Appointment(Date=getDefaultDate(),
Date=getDefaultDate(),
std::string=getDefaultString(),
std::string=getDefaultString(),
Contact=getDefaultContact());
It really boils down to how you prefer to handle and initialize your objects.
An important sidenote: in large production codebases default parameters is a C++ feature often frowned upon because it might hinder readability and/or render debugging more difficult in particular scenarios (especially when something unwanted goes on and you didn't consider a default parameter being chosen, default parameters are specified on the declaration and that might also "hides" a potential problem from the developers)
This is totally unnecessary. As pointed out Macro A , you can default construct the object and afterwards you can use setters for them.
One more thing when designing a software you should keep in mind the rule of complete and minimal i.e you should provide all facilities in a class avoiding duplication/redundancy.

Style and Enumerators [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
So, in the process of taking a data-structures class (in C++), my professor wanted us to manipulate a linked list of playing cards. That doesn't matter however, what I am interested in is why she did not use an enumerator to represent the suites.
In her code, she used strings to hold the suite of a card. This seemed inefficient because she wanted us to sort them based on suite, under the circumstances, it would have been considerably easier if she had used an enumerated type instead of a string. The string did not offer any help either, because in printing the suite, she output a Unicode character, roughly doubling the length of her function, simply because she did not use an enum.
Is there any reason for her to have done this, or does she simply have strange preferences when it comes to code style?
If you really want to know what your professor's reasoning is, you have to ask your professor. I can only speculate.
But if I were to speculate, I would guess that there are two possible reasons why your professor chose to use strings as descriptors for these attributes.
She is trying to keep the code simple and easy for newbie C++ programmers to understand. Whether the means meet the goal is debateable.
(Personal bias alert) Professors and others in academia, with no real-world experience, often do and teach things that I would consider to be highly sub-optimal.
My guess would be that she either had not considered that approach or that she wanted to test your ability to work with sorting strings.
Code examples might help in that they might clarify what she did and what you think she should have done.
The likely answer is that she just didn't think about the problem she was using to demonstrate whatever she is trying to teach you. That is, she wanted you to focus on sorting (for example), and probably took some code written by someone else and just adapted it to that purpose without much thought.

Are out-parameters out-dated? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
My intuition and practice for a long time has been to avoid out params if at all possible. I believe that a function should have one logical purpose and that usually implies one return type (not returning multiple things). Sometimes, returning multiple things is desirable (f.e. std::map::insert). I know this can be done as a pair/tuple or as output params; the argument of which of those to use is less important to me.
What are the conceptual, design, or performance reasons to prefer either output parameters or return values?
You're right, out parameters are not really needed as RVO makes returning by value feasible, even with large types. And having to return multiple things is either a code smell, or can be sensibly packed in a structure.
I'd say the only remaining reason, and it's a biggie, is consistency. If the class already has tens of methods returning by parameter, stick to it (unless you have the liberty to refactor the darn thing :).
Depending on the context, a third alternative might be to pass a callback. The callback might have multiple methods if the called function "produces" multiple values.
Though a function that takes a callback argument doesn't really fit the definition of a "function", neither does a function that returns multiple values, IMO.

Good style to avoid global variables in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
In much different projects, I got sooner or later some errors/warnings/problems while using global variables. Is there style a good program design to use global variables right in my projects or to avoid it completely
I read much articles about this issue and all are telling the same: Replace global variables with local variables, context objects, different patterns (singleton) and such things, but there are no explicit examples and descriptions how to use it right.
Do you have some good hints or references about that theme?
singletons are very similar to global variables in the problems they cause. Try looking at the "Parametrisation From Above" pattern instead.
It is a though task to get rid of global variables. Obviously there might be some strictly necessary, those will most likely be declared in your main or in header files.
A good example of global variable is a "struct" for parsing options from a configuration file: you load it once at the beginning of the execution and then you can keep accessing it from everywhere else. Or, you could also do the same with an object with set/get methods to retrieve those same config options (but still, the object would be declared global).
Also do not underestimate the power of macros. Whatever you decide to do, never forget the basic principle: DRY, Don't Repeat Yoursef. Keep things simple and keep them stored one place only.