Quick and simple style question

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

User avatar
Gatesunder
Posts: 120
Joined: Sat Feb 09, 2008 11:24 pm UTC
Location: KSU

Quick and simple style question

Postby Gatesunder » Sun Feb 24, 2008 9:47 pm UTC

So, I don't know why this just started bothering me. Perhaps it's like when you see a word printed on paper or the screen that you've known for your whole life and you look at it and suddenly it looks like it's spelled wrong or something when it's not.

This thing I speak of is the placement of data members and functions in a class I just started coding in C++. Normally I know that the data member are private or protected and the functions, most of the time, are public or protected, but I needed a private helper function and so I started coding and was like, "What the fudge? should I put this function above or below the data members in the private section?"

So what do you think? How do you usually style you're code? What, in this context, do you think looks more correct?

Code: Select all

class GenericClass
{
public:
           GenericClass();
           ~GenericClass();
private:
           int data1;
           int data2;
           int data3;

           int helper();
};


or

Code: Select all

class GenericClass
{
public:
           GenericClass();
           ~GenericClass();
private:
           int helper();

           int data1;
           int data2;
           int data3;
};


My VB origins are picking the former while my C++ induced self is battling for the latter . . .
I'm wrong 99% of the time, but some day that 1% will be better than the rest ...

User avatar
Aperfectring
Posts: 252
Joined: Fri Sep 07, 2007 3:47 am UTC
Location: Oregon (happily)

Re: Quick and simple style question

Postby Aperfectring » Sun Feb 24, 2008 11:03 pm UTC

I honestly don't do so much in the way of C++ coding. I am much more of a C guy. However, when I do write C++, I tend to put the groups in this order: private, protected, public. I then put the members and member functions in the groups in that order.

Code: Select all

class GenericClass
{
private:
   int data1;
   int data2;
   int data3;

   int helper();

protected:
   int inherited_data1;

   int inherited_helper();

public:
   GenericClass();
   ~GenericClass();
};


I also tend to order the member/variable definitions as follows: structures, pointers, and primitives (largest to smallest), and then sub-sorting for types, and then individual members/variables is lexicographical.

Code: Select all

Alpha alpha_instance;
Beta beta_instance;
Alpha *alpha_pointer;
int *integer_pointer;
uint64_t a_long_long;
uint32_t a_integer;
uint32_t b_integer;
uint32_t c_integer;
uint16_t a_short;
uint8_t a_char;
Odds are I did well on my probability exam.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Quick and simple style question

Postby EvanED » Sun Feb 24, 2008 11:30 pm UTC

I say screw the access level... I organize by purpose. So for instance, getter and setters would wind up adjacent to the field that they act on.

I think the logic is that grouping by access means that someone using your class can just look at the public section, and doesn't have to wade through the rest. But in my experience, the times when I'm looking at a header I'm usually concerned with the class in question.

maafy6
Posts: 102
Joined: Wed Aug 22, 2007 10:43 pm UTC

Re: Quick and simple style question

Postby maafy6 » Mon Feb 25, 2008 1:08 am UTC

This is more of an issue in Java, I think, but I can't stand when I come across a class that's been written an organized like

Code: Select all

//------------------------------------------------------------------------------------
private int bob;

public int getBob()
{
    return bob;
}

public void setBob(int val)
{
    bob = val;
}


And this is then repeated for every single member of the class, however of them there may be. In some respects, it obfuscates the class for me, because I then have to wade through the entire thing in order to know what all is even in the class. If you list all the members together, I can postulate the existence of getters and setters. I have harder times postulating members ex nihilo.

As far as C++, my normal style is:

Code: Select all

class Bob
{
public:
    // Constructors
    // Non-Trivial Useful Functions
    // Helper Functions
    // Setters
    // Getters
    // Members
protected:
    // Same order
private:
    // Same order
}


Interestingly, in Java, I get a feeling of vertigo if the above is used, and prefer

Code: Select all

class Bob
{
    // Static fields
    // Public members
    // Protected members
    // Private members
    // Package-Private members

    // Constructors
    // Non-Trivial Useful Functions
    // Helper Functions
    // Setters
    // Getters

    // Sub-Classes
    // Sub-Enums
}


Everything is mostly in the same order, but I just have to expect any members/fields at the beginning of the class. I feel weird scrolling down all the way to the bottom, but then here you've got the space eaten up by the actual implementation.

Posi
Posts: 111
Joined: Mon Jul 16, 2007 6:08 am UTC

Re: Quick and simple style question

Postby Posi » Mon Feb 25, 2008 3:54 am UTC

I usually put public above private and functions over members.

Code: Select all

class Foo
{
public:
  Foo();
  ~Foo();

  //functions in alphabetical order
  a();
  b();
  c();
  //overridden operators
  operator==();
  //members in alphabetical order
  bar;

private:
  //functions in alphabetical order
  helper();
  //members in alphabetical order
  a;
  b;
  c;
}

My reasoning is that headers are there (partially) to declare the class interface. Thus public items go first. I always put the functions before members because the constructor is almost always first, and the constructor is just a special function. I just like alphabetical ordering because it makes thing easier for me to find.

I think the most important thing is to pick a style and be consistent with it. If it is a large project, figure out the style already in use and use that.
Last edited by Posi on Mon Feb 25, 2008 8:01 am UTC, edited 2 times in total.

User avatar
Gatesunder
Posts: 120
Joined: Sat Feb 09, 2008 11:24 pm UTC
Location: KSU

Re: Quick and simple style question

Postby Gatesunder » Mon Feb 25, 2008 4:44 am UTC

ahh nice. I like the little variations you guys are giving.

I'm a bit of an OCD organization nut for some things, which is odd considering that most of my clothes and mail is strewn about my room and desk respectively. At least my code can be clean :mrgreen:

I decided to go with the following for my this particular class

Code: Select all

class SomeClass
{
       // friends
public:
       // constructors
            //- default
            //- copy
            //- (few args)
            //- (bit more args)
            //- (destructor)
       // overloaded operators
            //- incrementers/decrementers
            //- math ops
            //- comparison ops
            //- assignment ops
       // accessors
            //- sets
            //- gets
private:
      void helper();

      int a;
      int b;
      int c;
};
I'm wrong 99% of the time, but some day that 1% will be better than the rest ...

Notch
Posts: 318
Joined: Tue Dec 12, 2006 5:52 pm UTC
Location: Stockholm, Sweden
Contact:

Re: Quick and simple style question

Postby Notch » Mon Feb 25, 2008 11:44 am UTC

maafy6 wrote:

Code: Select all

class Bob
{
    // Static fields
    // Public members
    // Protected members
    // Private members
    // Package-Private members

    // Constructors
    // Non-Trivial Useful Functions
    // Helper Functions
    // Setters
    // Getters

    // Sub-Classes
    // Sub-Enums
}


Same layout as me, except I put Classes and Enums at the top (Enums before Classes). Usually (in my code), nested classes are a sign that I've been lazy, and they should really be refactored into separate classes, usually with some additional rewiring to get rid of the lazy and add to the OOP. If they're at the top they remind me to fix them every time I open the compilation unitclass file.
Still, I have a tendency to make up weird reasons to use inner classes, usually starting with "oh, wouldn't it be great if.."

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Quick and simple style question

Postby Berengal » Mon Feb 25, 2008 12:46 pm UTC

Usually I just let eclipse sort it out for me, if I even bother to put code in the right places. I do however put public methods in front of private ones, unless it's a short helper method for a particular public method, in which case I'll put it right below the method it's attached to, but once I tell eclipse to "sort members..." that's all screwed up again.

Besides, I use the outline window to navigate classes, not the code itself.

As for members, I go public members first, then private. I usually don't find a reason to make members public, however, as making getters and setters takes all of seven seconds in eclipse, and I want to make sure nobody invalidates my data. Much better to have a setter throw an exception in your face than get a RandomRuntimeException 1000 lines worth of function calls later.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

mrkite
Posts: 336
Joined: Tue Sep 04, 2007 8:48 pm UTC

Re: Quick and simple style question

Postby mrkite » Wed Feb 27, 2008 6:38 pm UTC

Code: Select all

class whatever
{
    public:
        whatever();
        ~whatever();
        methods grouped by function, ordered by most common usage
        members ordered by descriptiveness
    protected:
        same as above
    private:
        same as above.
};


Don't forget to indent the access specifier keywords. :)

zahlman
Posts: 638
Joined: Wed Jan 30, 2008 5:15 pm UTC

Re: Quick and simple style question

Postby zahlman » Sat Mar 01, 2008 11:17 pm UTC

I like to put the private stuff first - to take advantage of the "default private access" given by the class keyword (as opposed to struct). I don't add a level of indentation after 'public:' or 'private:' (or 'protected:'), because they're only labels - indentation should follow scope. Oh, and you very rarely need to write a destructor (except an empty, virtual one in a base class) in modern C++. So for me it usually looks like:

Code: Select all

class something {
  int x, y, z;
  int helper();

  public:
  something(int x, int y, int z): x(x), y(y), z(z) {}
};
Belial wrote:I once had a series of undocumented and nonstandardized subjective experiences that indicated that anecdotal data is biased and unreliable.

User avatar
rrwoods
Posts: 1509
Joined: Mon Sep 24, 2007 5:57 pm UTC
Location: US

Re: Quick and simple style question

Postby rrwoods » Tue Mar 04, 2008 9:02 pm UTC

Berengal wrote:Usually I just let eclipse sort it out for me

How do you do this? I've been looking for a while.
31/M/taken/US
age/gender/interest/country

Belial wrote:The sex card is tournament legal. And I am tapping it for, like, six mana.

User avatar
segmentation fault
Posts: 1770
Joined: Wed Dec 05, 2007 4:10 pm UTC
Location: Nu Jersey
Contact:

Re: Quick and simple style question

Postby segmentation fault » Tue Mar 04, 2008 9:20 pm UTC

in the case that there isnt any declaration-before-use issues, i usually put methods first then data. public before private.

zahlman wrote:I like to put the private stuff first - to take advantage of the "default private access" given by the class keyword


if other people are looking at/using your code, they might appreciate reading the stuff they can actually use first. just my 2 cents.
people are like LDL cholesterol for the internet

User avatar
und3rdark
Posts: 27
Joined: Mon Jan 14, 2008 7:25 pm UTC
Location: Canton, Michigan

Re: Quick and simple style question

Postby und3rdark » Tue Mar 04, 2008 10:29 pm UTC

rrwoods wrote:
Berengal wrote:Usually I just let eclipse sort it out for me

How do you do this? I've been looking for a while.


Right-click on some whitespace
Go to source->sort members
"The impulse to discriminate is a feature of our brains. We look for patterns and make decisions based on them. Sometimes the patterns are illusions, and we come to irrational conclusions."
-Scott Adams

zahlman
Posts: 638
Joined: Wed Jan 30, 2008 5:15 pm UTC

Re: Quick and simple style question

Postby zahlman » Wed Mar 05, 2008 1:30 am UTC

segmentation fault wrote:in the case that there isnt any declaration-before-use issues, i usually put methods first then data. public before private.

zahlman wrote:I like to put the private stuff first - to take advantage of the "default private access" given by the class keyword


if other people are looking at/using your code, they might appreciate reading the stuff they can actually use first. just my 2 cents.


If I really care about hiding internals, the pImpl idiom will reduce the private section to a minimum. Otherwise, the problem is solved by either Intellisense (I think?), documentation (whee!) or just typing something like '<esc>/public' (or even recording that as a macro in gVim).
Belial wrote:I once had a series of undocumented and nonstandardized subjective experiences that indicated that anecdotal data is biased and unreliable.

ruds
Posts: 1
Joined: Thu Mar 06, 2008 6:28 am UTC

Re: Quick and simple style question

Postby ruds » Thu Mar 06, 2008 6:34 am UTC

zahlman wrote:
segmentation fault wrote:in the case that there isnt any declaration-before-use issues, i usually put methods first then data. public before private.

zahlman wrote:I like to put the private stuff first - to take advantage of the "default private access" given by the class keyword


if other people are looking at/using your code, they might appreciate reading the stuff they can actually use first. just my 2 cents.


If I really care about hiding internals, the pImpl idiom will reduce the private section to a minimum. Otherwise, the problem is solved by either Intellisense (I think?), documentation (whee!) or just typing something like '<esc>/public' (or even recording that as a macro in gVim).


All that to save you the <10 keystrokes necessary to add a "private:" line to your file? When you're writing code, remember that people (including you in a few weeks or months) will want to read the header to learn the interface more than you'll want to read it to learn the private implementation. Thus, more work on your part to make it easier for users to understand is the right thing to do if you care about global efficiency.

User avatar
rrwoods
Posts: 1509
Joined: Mon Sep 24, 2007 5:57 pm UTC
Location: US

Re: Quick and simple style question

Postby rrwoods » Thu Mar 06, 2008 3:43 pm UTC

und3rdark wrote:
rrwoods wrote:
Berengal wrote:Usually I just let eclipse sort it out for me

How do you do this? I've been looking for a while.


Right-click on some whitespace
Go to source->sort members

Sweet, I'll try this tonight if I remember.
31/M/taken/US
age/gender/interest/country

Belial wrote:The sex card is tournament legal. And I am tapping it for, like, six mana.


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 7 guests