Open Mike: Code Organization

Do you order your functions and variables by their purpose, or by an unchanging set of rules? This is Open Mike, a series of discussion posts to throw the cat amongst the pigeons. These posts are all about you — we want to hear your opinions, ideas, and thoughts. This one’s as straightforward as they come; one question, one poll, but a potentially huge discussion. Let’s hear what you have to say about code organization.

There are two approaches to ordering the properties and methods in your classes:


The Methodological Approach

You could have a strict set of rules, like:

  • Imports are arranged alphabetically.
  • Public consts come immediately after the class name, then private consts.
  • After consts come variables: public, protected, private, then internal; all arranged alphabetically.
  • Constructor function comes after the variables.
  • Public functions come after the constructor, then protected, private, and internal; again, all in alphabetical order.

These rules don't take into account what any of the variables or functions do; they just provide you with a simple way to make sure that everything's in its place. You can easily find any code you're looking for, though a decent code editor would make that easy anyway.


The Functional Approach

On the other side of the spectrum, you could group your functions and variables by their purpose. Perhaps all the code related to initializing a class goes at the top, while the code for deconstructing it goes near the bottom.

This makes code easier to read through, though it can be harder to find a specific function in a rush. Some would argue that this is unnecessary, because a class should only contain the code required for a single purpose anyway.


What's Your Approach?

So, how do you arrange your code? Methodically, functionally, or some mix of the two? Take part in our Facebook poll and let us know :)


How do you arrange your code?
Tags:

Comments

Related Articles