Style Points

Started by
8 comments, last by wioneo 13 years, 9 months ago
A few things that I've seen as good style/proper in various tutorials have been confusing me.

First, and most importantly I think, what is the purpose of declaring any members of a class as private? I keep seeing that it is to "prevent other parts from accessing them" or something to that effect, but isn't the best way to prevent that to just...not referrence them? Having certain members be inaccessible seems, more of a hinderance than help to me.

Secondly, what is the purpose of seperating a function into a prototype in one file and then defining it in another file as opposed to just defining it as part of the prototype? This just seemed to add a small amount of unnecessary work...

Does 'else' consume any resources? Meaning if it is not at all necessary to have an else statement, am I hurting efficiency by including it? They make things look more structured in my opinion, but I will definately stop using extras( for examples...
if (5==5){return true;}else{return false;}//instead of....if (5==5){return true;}return false;


Does variable length affect anythign at all? As in, is 'j' slightly more efficient than 'iy' as an identifier?

Is...
if (5==5){return true;}

...less efficient than...
return (5==5)

...resource wise, I mean. Again, I like to make things blatantly obvious to myself so possible future revisions are easier.

I apologize if any/all of my questions are...lets say 'daft,' but I really preferr to learn things the bes way when possible and any assistance on these issues would be greatly appreciated.

EDIT: Aha! so I guessed right about the code tags(thought it doesn't seem to do anything...), but is there a more detailed post editor hiding somewhere that I am missing? I would rather not learn all of this forums tags through guess and check.
Advertisement
Quote:
First, and most importantly I think, what is the purpose of declaring any members of a class as private?

Making something 'private' is part of encapsulation. You can make getters/setters to access private members, and do error checks on the values being set. This is better than having a plain variable there.

Private members can't be accessed directly from the outside, this lets you hold invariants true in your code. If 'int foo' is public, you can't assume anything about it. If it is private, you control all access to it, and can safely write code that makes assumptions about its value. For instance: a public "int *foo" has to be error checked for foo being NULL before every function that uses it. A private "int *foo", you'd know exactly at what points in time it is or isn't NULL, since you control exactly where it gets set.

Quote:
but isn't the best way to prevent that to just...not referrence them?

Since private members can't be accessed from outside, OTHER PEOPLE using your code will know that those variables and functions are 'internal' and know not to use them. If everything is public, the assumption will be that those variables are free to access. You might know not to access them, but making them private insures other people know the access pattern.

Quote:
Having certain members be inaccessible seems, more of a hinderance than help to me.

You might have too much data in your classes. You might have too much or too little obligation to your classes. If you think everything needs to be public, you need to better define the boundries of where that data is useful to you. If you end up with a lot of "GetHP" "GetAP" "GetMP" functions floating around, try to encapsulate further to a "GetStats()" that returns a collection of related values.

Quote:
Does 'else' consume any resources?

nope.

Quote:
Does variable length affect anythign at all?

It doesn't affect the runtime performance of your program. Having well named variables helps in readability too much to be ignored.

Quote:
if (5==5)
{return true;}
...less efficient than...
return (5==5)

no. and even on the off chance that it is (maybe in debug mode), it isn't worth making micro optimizations like that when they affect the readability of the code.
(aside: they both result in 'return true;' because (5==5) can be proven true at compile time.)

Quote:
Secondly, what is the purpose of seperating a function into a prototype in one file and then defining it in another file as opposed to just defining it as part of the prototype? This just seemed to add a small amount of unnecessary work...

1) Compile time. Including a header file pulls in the entire header. If you have a lot of code in your headers, it takes longer to compile. Putting the prototype in the header reduces the compile time for all files that include the header.
As well as the fact that changing a include forces you to recompile everything that included it. By seperating the definition and declaration, you can make edits to the functionality of your code without incurring that huge recompile.
2) Dependences. If 'foo' can call 'bar', and 'bar' can call 'foo', then you can't actually declare the functions without getting either 'bar is undefined' or 'foo is undefined'. By having a seperate prototype section, you can tell the compiler about 'foo' and 'bar' so that it knows they exist, even if it hasn't seen them in full yet.
3) Readability. Looking at a prototype section, I can explicitly see all the functions I have available. In the declaration section, all the functions take up a lot of room, and even folded, it isn't quite as easy to read through.
4) Similar to the public-private thing, you can put some prototypes in the header, and leave the more internal ones in the .cpp file.



note: code tags do preserve formatting, and give your code a different font. For better formatting, and colors, use the source tag.
Quote:Original post by wioneo
Does 'else' consume any resources? ...
To be pedantic: It depends. The body of the 'then' block usually needs to jump behind the body of the 'else' block, so one can say that an unconditional branch is caused by the 'else'. However ...

Quote:Original post by wioneo
... Meaning if it is not at all necessary to have an else statement, am I hurting efficiency by including it?...
...if it is not necessary, then today a compiler will usually be smart enough to optimize it.

Quote:Original post by wioneo
if (5==5){return true;}else{return false;}...return (5==5)
This wasn't exactly asked for, but here my optinion is that the compact form can be scanned easier by a human eye and is to be preferred for just that reason.

Quote:Original post by wioneo
Does variable length affect anythign at all? As in, is 'j' slightly more efficient than 'iy' as an identifier?
To be exact: Yes. It causes shorter source code, lesser memory consumption in symbol tables and scan time during compilation, and perhaps also smaller binaries (at least in debugging mode).

But who cares whether the source file is 100 bytes shorter, especially if files are quantized with, e.g., 4kBytes? You will also not be able to measure a faster compilation. The aspects I've enumerated are only virtual advantages. But the big, very big disadvantage of short variable names is the less good readability. In favor to yourself and any person who has to read your source code: Choose "talking" variables/routine/class/... names.

Quote:Original post by wioneo
Is...
if (5==5){return true;}

...less efficient than...
return (5==5)

...resource wise, I mean.
This is an incomplete comparison. The top snippet may continue behind the if clause, while the bottom snippet returns ever.

Quote:Original post by wioneo
I apologize if any/all of my questions are...lets say 'daft,' but I really preferr to learn things the bes way when possible and any assistance on these issues would be greatly appreciated.
The first aspect should be to write clean and understandable code. "Optimizations" like those above are meaningless these days. Real optimizations come on the algorithmic level.

Quote:Original post by wioneo
EDIT: Aha! so I guessed right about the code tags(thought it doesn't seem to do anything...), but is there a more detailed post editor hiding somewhere that I am missing? I would rather not learn all of this forums tags through guess and check.
See the forum's FAQ; its link can be found in the collection at the top right of your current screen. Therein especially How do I put links/quotes/images/code/smileys in my posts? ...

Quote:Original post by wioneo
First, and most importantly I think, what is the purpose of declaring any members of a class as private?

In addition to points provided above, this encapsulation also lets you more easily change the internal implementation of your class.

Say you're developing a class that needs to associate a string with a string. Additionally, these need to ordered. Your first version simply uses a list that stores pairs (in C++ template-style):

class Some
{
public:
list<pair<string, string> >
};

Now you later find out that there exists an std::map. You want to change your implementation to std::map. But because your list was public and everywhere in your code you simply use this public list, ALL the code that uses your class must be recompiled.

Instead, if you'd done

class Some
{
public:
string getValue(string key) const;

private:
list<pair<string, string> >
};

you could easily change list to map and only this ONE class needs to be recompiled.

Quote:
They make things look more structured in my opinion


I prefer the version without the else for the following reason:

void makeCoffee(){  takeCoffeeFromShelf()  if (noCoffee)  {    return false;  }  else  {    takeWater()    if (noWater)    {      return false;    }    else    {      turnOnCoffeeMaker()      if (noElectricity)      {        return false;      }      else      {        ... etc


opposed to

void makeCoffee(){  takeCoffeeFromShelf()  if (noCoffee)    return false;  takeWater()  if (noWater)    return false;  turnOnCoffeeMaker()  if (noElectricity)    return false;


To me the latter is a lot clearer.
Ok, thank you all for the advice, I had not even considered compile time before but I see how could affect decisions.

But one thing about the public/private bit is still confusing me, namingly...
Quote:
...this lets you hold invariants true in your code.

I have no idea whatsoever what you meant by this.

It seems like the answer for most of my questions comes down to compile time...interesting.
@OP : From your example, you can just concise the return statement into this :
return 5 == 5;

no ifs, ands, or else.
Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github
Quote:But one thing about the public/private bit is still confusing me, namingly...
Quote:
...this lets you hold invariants true in your code.

I have no idea whatsoever what you meant by this.
The Wikipedia article on class invariants has some info on this.
Quote:First, and most importantly I think, what is the purpose of declaring any members of a class as private? I keep seeing that it is to "prevent other parts from accessing them" or something to that effect, but isn't the best way to prevent that to just...not referrence them? Having certain members be inaccessible seems, more of a hinderance than help to me.
Your logic breaks down here.

Say you have some member fields that you don't want to be modified from outside the class, so you say, 'no problem, I just won't modify them from outside the class'. But, if you've already determined that you're not going to modify them from outside the class (simply through programmer discipline), how would making them private be a hinderance? Wouldn't it simply formalize what was already your intent, while at the same time helping to prevent possible programmer error?
It has been mentioned already that having clearly defined interfaces (including what's public and what's private) is important when another programmer is involved. You should keep in mind that "another programmer" could be you in six months. You won't remember all the assumptions you made when designing and implementing your class. Whatever assumptions you can ask the compiler to enforce for you (`private' being a good example) you should use. Where the compiler can't help, make sure to document your decisions.

I present the top three, real-life reasons for paying attention to scoping:

3) Organization today makes it easier to perform maintenance tomorrow. 'nuff said about that.

2) Sloppy scoping might hurt your friends. Maybe *you* won't accidentally modify an important internal variable because you already know it's important not to modify it. However, you may not always be there when your code is being used. What about someone else on your team? Or maybe you write a great library that you want to share with others?

And finally, the number 1 reason to pay attention to scoping:

1) Sloppy scoping actually slows you down. IDEs generally have syntax popups that help to choose methods,properties, etc as you type. If you declare *everything* public the list becomes cluttered with items you already know you don't need.

=)
--- "A penny saved never boils."
Thank you, everyone, for your advice. I think that I've learned a good bit from your answers.

This topic is closed to new replies.

Advertisement