What's wrong with singleton? [closed] - language-agnostic

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Do not waste your time with this question. Follow up to: What is so bad about singletons?
Please feel free to bitch on Singleton.
Inappropriate usage of Singleton may cause lot of paint. What kind of problem do you experienced with singleton? What is common misuse of this pattern?
After some digging into Corey's answer I discovered some greate articles on this topic.
Why Singletons Are Controversial
Performant Singletons
Singletons are Pathological Liars
Where Have All the Singletons Gone?
Root Cause of Singletons

There's nothing inherently wrong with the Singleton pattern. It is a tool and sometimes it should be used.

Sometimes it can make your code more tightly coupled with the singleton class being refrerenced directly by name from different parts of your codebase. So, for example, when you need to test some part of your code and it references a singleton from a diferent part of the code you cannot easily fake that dependency with a mock object.

I think a more appropriate question might be: In what situations is the use of a SIngleton Pattern inappropriate? Or what have you seen that uses a Singleton that shouldn't.

There's nothing wrong with a singleton in itself, and as a pattern it fills a vital role in recognising the need for certain objects to only be created a single time.
What it is frequently used for is a euphemism for global variables as an attempt to get around global variable stigma, and it is this use that is inherently wrong. If a global variable happens to be the correct solution, using a singleton won't improve it. If it is (as is fairly common) incorrect to use a global variable, wrapping it in a singleton won't make it any more correct.

I haven't been exposed to the Singleton as much as some of the other posters have, but nearly all implementations that I have seen (in C#) could have been achieved with static classes/methods. I suppose you could argue that a static class is an implementation of the singleton pattern, but that's not what I've been seeing. I've been seeing people build up and manage these Singleton classes/objects when all they really needed was to use the static keyword.
So, I wouldn't say the Singleton pattern is bad. I'd say it's kinda like guns. I don't think guns are bad, but they can most certainly can be used inappropriately.

Basically singleton is a way to have static data and pretend it is not really static.
Of course I use it, but try to not abuse it.

One basic problem with the original GoF design is the fact that the destructor isn't protected. Anyone with a reference to the singleton instance is free to destroy the singleton.
See John Vlissides update "To Kill A Singleton" in his book "Pattern Hatching" (Amazon link).
cheers,
Rob

Most of the singleton patterns that I see written aren't written in a thread safe manner. If written correctly, they can be useful.

Related

PreUpdate, Update, PostUpdate... Anyone use better names?

Does anyone use a prettier naming convention for these types of methods? I know better is subjective but I hate them. Methods should (generally) be named as verbs. Object.Move(), Object.Talk() not Object.PreDatabaseUpdateStep().
I've been using Think() for my PreUpdate(), which is generally pure logic compared to Update() which is generally pure physics. I haven't thought of anything fancier for PostUpdate() yet.
Suggestions?
A pragmatic programmer should always strive to design code for readability. The names PreUpdate, Update, and PostUpdate communicate their intentions much more clearly than a name like Think.
Similarly, we can look to what other projects do for inspiration. For example, the JUnit suite uses similar naming convention with #Before and #After (and #BeforeClass and #AfterClass) annotations. And by convention, iOS delegate patterns often specify "Will" and "Did" (like WillUpdateFoo and DidUpdateFoo) methods.
PreUpdate is indeed not really specific. Probably you could make it even more clear what's happening in these methods.
Whatever replacement you find for Pre and Post. When you use the same terms in different cases, it can't have specific information. So it doesn't matter much.
What about PrepareUpdate and FinishUpdate?
There is a naming convention for this kind of events in C#, which makes use of the tense. Updating is called before update happens, Updated afterwards. Personally, I think Pre and Post is more clear to everyone, but I also use this naming convention.

Mandatory method documentation [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 5 years ago.
Improve this question
On my previous job, providing all methods with javadoc was mandatory, which resulted in things like:
/**
* Sets the Frobber.
*
* #param frobber The frobber
*/
public setFrobber(Frobber frobber) { ... }
As you can see, the documentation takes up space and work, but adds little to the code.
Should documenting all methods be mandatory or optional? Is there a rule for which methods to document? What are pros and cons of requiring every method to be documented?
"providing all methods with javadoc was mandatory"
I strongly suspect that documenting all methods was mandatory, but providing javadoc comments was all that could be automatically enforced and hence all that was uniformly done.
Personally I think it's better to have no javadoc than completely useless javadoc - at least you can see from a glance at the HTML which methods are undocumented, because there are no descriptions of the parameters etc.
Documentation is frequently underrated, because it always seems less important and urgent when you're writing the code, than it does when you're using it later. But the style and form of documentation is often overrated - auto-generated XML nonsense is still nonsense. Given the choice, I'd rather have the code comment // Sets this object to use the specified frobber for all future frobbing, than your zero-information javadoc.
For all I know from your docs, the function doesn't actually modify this object at all, it might call the set() function on frobber, or it might be while(!frobber.isset()) { refrigerator.add(frobber); sleep(3600); refrigerator.remove(frobber); } Hence it "sets the frobber". I'm sure I read somewhere that "set" is the word with the most distinct definitions in the OED. Brief descriptions are ambiguous and hence misleading, and the purpose of documentation is to stop people relying on your source, and hence on details of your current implementation. My comment doesn't really take any longer to write than it took to add "Sets the frobber" and "the frobber" to the IDE-generated javadoc stub. It doesn't explain what frobbing is or when this object does it (hopefully that's elsewhere in the class docs) but at least it tries to tell you what the function does.
As for when to mandate documentation - I think every interface must be documented. If you're not defining Java interface s, the "interface" is every public and protected method, and every package-protected method unless the package is tiny. Implementation doesn't have to be documented, although it should be commented if the way it works is non-obvious. Documentation might be as simple as the sentence in my comment above - you don't necessarily need a separate sentence for each parameter if the method description already says what they are.
If you have code review, then IMO the answer is to review comments and documentation at the same time. If you don't have code review, then you need a cone of shame for whichever developer most recently forced someone else to come over and ask what the code actually does.
The same applies to anyone who relied on undocumented behaviour of a function, with a result that an implementation change that didn't change the interface, breaks their code. The way you enforce that code be documented, is to complain that you can't call it until you know what it guarantees to do. Arbitrary rules like, "javadoc comments must exist" become less important, at least for functions that other developers need to call.
For big projects or frameworks/libraries or even open source project that you are creating, it is mandatory. For small personal or private projects it is optional. Having said that, it is always a good idea to document your code so if you come back to your project after a year whether small or big, you know what it was doing. This really helps greatly.
You should always document your code. especially if someone else work or will work on your code. Maybe you didn't have a chance yet to work on legacy not-documented code but it can be a real pain!
About the comment itself, one thing to avoid is writing a comment because it is mandatory, Just think a few second and you'll find something to tell about your method, something that's not already in the method name, something that might not be obvious to the next developer. Explain what your method does, what are the corner cases, what it expect as input.
And remember :
Always code as if the guy who ends up
maintaining your code will be a
violent psychopath who knows where you
live.
it applies to comments too :)
It's much easier to maintain "self-documenting" code. If you choose good function and variable names, keep functions short (eg. < 10 lines with only a single idea per function), this will help keep the purpose of the code clear. And you won't have to try to keep the comments up to date - the only thing worse than no comments is comments that are wrong!
There's a good and recent summary of various points of view at InfoQ.
Documentation of code is very important. But Javadoc (or similar tools) are not the only and not the best method for this. The biggest downside is, that Javadoc-documentation must be kept up to date. If the method is changed, but the description stays the same, this documentation can do more trouble than good.
To avoid the problem with documentation not in sync with the code, use code to document. Unit-tests show how your code is used and asserts in the code can ensure that parameters and return-values are validated. In a project I added asserts to a calculation, that the probabilities in this calculation are always between 0 and 1. Later this assert triggered in a use case and pointed me directly to a bug.
The most important documentation is a good naming. If you set a Frobber, then setFrobber is a good name. The Javadoc given in your example adds nothing to this naming. frobIt would be a not so good name, method3 would be very bad. Code reviews should help to get good naming.
Javadocs and ither documentation should be added, if the other methods aren't sufficient. But in this case you need to take care, that this documentation is always up to date.
Q: Should documenting all methods be mandatory or optional?
A: Mandatory.
Q: Is there a rule for which methods to document?
A: All of them.
Q: What are pros and cons of requiring every method to be documented?
A: Pros: Smart people can spend time focusing on code writing, not code figuring-out. Code is well explained. Code can be passed to newbies. Cons: Whining. Stale comments.
A focus on quality commenting obviates the 'code is self-documenting' issues.
In the case of getters and setters, not every get and set is trivial. Sometimes it is, that's great. When it isn't, the comment should note the information. It's better to be conservative and always have comments than unconservative and have to scrap code and waste time figuring it out.
Final example: The Carmack Inverse Square Root code. Self-documenting, eh?

How do you prefer to organize exception definitions? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I almost feel embarrassed to ask, but I always struggle with how to organize exception definitions. The three ways I've done this before are:
Use the file-per-class rule. I'm not crazy about this because it clutters up my directory structure and namespaces. I could organize them into subdirectories and segment namespaces for them, but I don't really like that, and that's not how the standard libraries usually do it.
put the definitions in a file containing the related class(es). I don't really like this either because then exception definitions are scattered about and may be hard to find without the aid of a code navigation tool.
One file with all the exception definitions for a namespace or "package" of related classes. This is kind of a compromise between the above two, but it may leave situations in which it's hard to tell which exceptions "belong" to a particular group of classes or set of functionality.
I don't really like any of the above, but is there a sort of best-practice that I haven't picked up on that would be better?
Edit: Interesting. From the "Programming Microsoft Visual C# 2008: The Language", Donis suggests:
For convenience and maintainability,
deploy application exceptions as a
group in a separate assembly. (p. 426)
I wonder why?
I tend to place the Exceptions one per file in the same package as the objects which produce them, in individual files. This is the paradigm used by the Java APIs and the .Net libraries, so most people are at least familiar with the organization of the objects at that point.
Modern IDE's do a good enough job of keeping track of the files in a directory that the benefits of having the class in a file of the same name tend out outweigh the value of having fewer files.
I use the following approaches:
Exception class in a separate file: when it's generic and can be thrown by more than one class
Exception class together with the class throwing it: when there is only one such class. This makes sense because the exception is part of that class' interface
A variant on the latter is making the exception a member of the throwing class. I used to do that but found it cumbersome.
In C++, I've always defined classes that I will use as exceptions in the same namespace as the classes which throw them, co-locating them in the same header. For general purpose exceptions, that will be shared between classes, I use a single header to group them together, along with other utility functions and classes.
I don't believe there's any one correct way of doing things in this regard; it's whatever works for you in your context.

Singletons: good design or a crutch? [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
Singletons are a hotly debated design pattern, so I am interested in what the Stack Overflow community thought about them.
Please provide reasons for your opinions, not just "Singletons are for lazy programmers!"
Here is a fairly good article on the issue, although it is against the use of Singletons:
scientificninja.com: performant-singletons.
Does anyone have any other good articles on them? Maybe in support of Singletons?
In defense of singletons:
They are not as bad as globals because globals have no standard-enforced initialization order, and you could easily see nondeterministic bugs due to naive or unexpected dependency orders. Singletons (assuming they're allocated on the heap) are created after all globals, and in a very predictable place in the code.
They're very useful for resource-lazy / -caching systems such as an interface to a slow I/O device. If you intelligently build a singleton interface to a slow device, and no one ever calls it, you won't waste any time. If another piece of code calls it from multiple places, your singleton can optimize caching for both simultaneously, and avoid any double look-ups. You can also easily avoid any deadlock condition on the singleton-controlled resource.
Against singletons:
In C++, there's no nice way to auto-clean-up after singletons. There are work-arounds, and slightly hacky ways to do it, but there's just no simple, universal way to make sure your singleton's destructor is always called. This isn't so terrible memory-wise -- just think of it as more global variables, for this purpose. But it can be bad if your singleton allocates other resources (e.g. locks some files) and doesn't release them.
My own opinion:
I use singletons, but avoid them if there's a reasonable alternative. This has worked well for me so far, and I have found them to be testable, although slightly more work to test.
Google has a Singleton Detector for Java that I believe started out as a tool that must be run on all code produced at Google. The nutshell reason to remove Singletons:
because they can make testing
difficult and hide problems with your
design
For a more explicit explanation see 'Why Singletons Are Controversial' from Google.
A singleton is just a bunch of global variables in a fancy dress.
Global variables have their uses, as do singletons, but if you think you're doing something cool and useful with a singleton instead of using a yucky global variable (everyone knows globals are bad mmkay), you're unfortunately misled.
The purpose of a Singleton is to ensure a class has only one instance, and provide a global point of access to it. Most of the time the focus is on the single instance point. Imagine if it were called a Globalton. It would sound less appealing as this emphasizes the (usually) negative connotations of a global variable.
Most of the good arguments against singletons have to do with the difficulty they present in testing as creating test doubles for them is not easy.
There's three pretty good blog posts about Singletons by Miško Hevery in the Google Testing blog.
Singletons are Pathological Liars
Where Have All the Singletons Gone?
Root Cause of Singletons
Singleton is not a horrible pattern, although it is misused a lot. I think this misuse is because it is one of the easier patterns and most new to the singleton are attracted to the global side effect.
Erich Gamma had said the singleton is a pattern he wishes wasn't included in the GOF book and it's a bad design. I tend to disagree.
If the pattern is used in order to create a single instance of an object at any given time then the pattern is being used correctly. If the singleton is used in order to give a global effect, it is being used incorrectly.
Disadvantages:
You are coupling to one class throughout the code that calls the singleton
Creates a hassle with unit testing because it is difficult to replace the instance with a mock object
If the code needs to be refactored later on because of the need for more than one instance, it is more painful than if the singleton class were passed into the object (using an interface) that uses it
Advantages:
One instance of a class is represented at any given point in time.
By design you are enforcing this
Instance is created when it is needed
Global access is a side effect
Chicks dig me because I rarely use singleton and when I do it's typically something unusual. No, seriously, I love the singleton pattern. You know why? Because:
I'm lazy.
Nothing can go wrong.
Sure, the "experts" will throw around a bunch of talk about "unit testing" and "dependency injection" but that's all a load of dingo's kidneys. You say the singleton is hard to unit test? No problem! Just declare everything public and turn your class into a fun house of global goodness. You remember the show Highlander from the 1990's? The singleton is kind of like that because: A. It can never die; and B. There can be only one. So stop listening to all those DI weenies and implement your singleton with abandon. Here are some more good reasons...
Everybody is doing it.
The singleton pattern makes you invincible.
Singleton rhymes with "win" (or "fun" depending on your accent).
I think there is a great misunderstanding about the use of the Singleton pattern. Most of the comments here refer to it as a place to access global data. We need to be careful here - Singleton as a pattern is not for accessing globals.
Singleton should be used to have only one instance of the given class. Pattern Repository has great information on Singleton.
One of the colleagues I have worked with was very Singleton-minded. Whenever there was something that was kind of a manager or boss like object he would make that into a singleton, because he figured that there should be only one boss. And each time the system took up some new requirements, it turned out there were perfectly valid reasons to allow multiple instances.
I would say that singleton should be used if the domain model dictates (not 'suggests') that there is one. All other cases are just accendentally single instances of a class.
I've been trying to think of a way to come to the poor singelton's rescue here, but I must admit it's hard. I've seen very few legitimate uses of them and with the current drive to do dependency injection andd unit testing they are just hard to use. They definetly are the "cargo cult" manifestation of programming with design patterns I have worked with many programmers that have never cracked the "GoF" book but they know 'Singelton' and thus they know 'Patterns'.
I do have to disagree with Orion though, most of the time I've seen singeltons oversused it's not global variables in a dress, but more like global services(methods) in a dress. It's interesting to note that if you try to use Singeltons in the SQL Server 2005 in safe mode through the CLR interface the system will flag the code. The problem is that you have persistent data beyond any given transaction that may run, of course if you make the instance variable read only you can get around the issue.
That issue lead to a lot of rework for me one year.
Holy wars! Ok let me see.. Last time I checked the design police said..
Singletons are bad because they hinder auto testing - instances cannot be created afresh for each test case.
Instead the logic should be in a class (A) that can be easily instantiated and tested. Another class (B) should be responsible for constraining creation. Single Responsibility Principle to the fore! It should be team-knowledge that you're supposed to go via B to access A - sort of a team convention.
I concur mostly..
Many applications require that there is only one instance of some class, so the pattern of having only one instance of a class is useful. But there are variations to how the pattern is implemented.
There is the static singleton, in which the class forces that there can only be one instance of the class per process (in Java actually one per ClassLoader). Another option is to create only one instance.
Static singletons are evil - one sort of global variables. They make testing harder, because it's not possible to execute the tests in full isolation. You need complicated setup and tear down code for cleaning the system between every test, and it's very easy to forget to clean some global state properly, which in turn may result in unspecified behaviour in tests.
Creating only one instance is good. You just create one instance when the programs starts, and then pass the pointer to that instance to all other objects which need it. Dependency injection frameworks make this easy - you just configure the scope of the object, and the DI framework will take care of creating the instance and passing it to all who need it. For example in Guice you would annotate the class with #Singleton, and the DI framework will create only one instance of the class (per application - you can have multiple applications running in the same JVM). This makes testing easy, because you can create a new instance of the class for each test, and let the garbage collector destroy the instance when it is no more used. No global state will leak from one test to another.
For more information:
The Clean Code Talks - "Global State and Singletons"
Singleton as an implementation detail is fine. Singleton as an interface or as an access mechanism is a giant PITA.
A static method that takes no parameters returning an instance of an object is only slightly different from just using a global variable. If instead an object has a reference to the singleton object passed in, either via constructor or other method, then it doesn't matter how the singleton is actually created and the whole pattern turns out not to matter.
It was not just a bunch of variables in a fancy dress because this was had dozens of responsibilities, like communicating with persistence layer to save/retrieve data about the company, deal with employees and prices collections, etc.
I must say you're not really describing somthing that should be a single object and it's debatable that any of them, other than Data Serialization should have been a singelton.
I can see at least 3 sets of classes that I would normally design in, but I tend to favor smaller simpler objects that do a narrow set of tasks very well. I know that this is not the nature of most programmers. (Yes I work on 5000 line class monstrosities every day, and I have a special love for the 1200 line methods some people write.)
I think the point is that in most cases you don't need a singelton and often your just making your life harder.
The biggest problem with singletons is that they make unit testing hard, particularly when you want to run your tests in parallel but independently.
The second is that people often believe that lazy initialisation with double-checked locking is a good way to implement them.
Finally, unless your singletons are immutable, then they can easily become a performance problem when you try and scale your application up to run in multiple threads on multiple processors. Contended synchronization is expensive in most environments.
Singletons have their uses, but one must be careful in using and exposing them, because they are way too easy to abuse, difficult to truly unit test, and it is easy to create circular dependencies based on two singletons that accesses each other.
It is helpful however, for when you want to be sure that all your data is synchronized across multiple instances, e.g., configurations for a distributed application, for instance, may rely on singletons to make sure that all connections use the same up-to-date set of data.
I find you have to be very careful about why you're deciding to use a singleton. As others have mentioned, it's essentially the same issue as using global variables. You must be very cautious and consider what you could be doing by using one.
It's very rare to use them and usually there is a better way to do things. I've run into situations where I've done something with a singleton and then had to sift through my code to take it out after I discovered how much worse it made things (or after I came up with a much better, more sane solution)
I've used singletons a bunch of times in conjunction with Spring and didn't consider it a crutch or lazy.
What this pattern allowed me to do was create a single class for a bunch of configuration-type values and then share the single (non-mutable) instance of that specific configuration instance between several users of my web application.
In my case, the singleton contained client configuration criteria - css file location, db connection criteria, feature sets, etc. - specific for that client. These classes were instantiated and accessed through Spring and shared by users with the same configuration (i.e. 2 users from the same company). * **I know there's a name for this type of application but it's escaping me*
I feel it would've been wasteful to create (then garbage collect) new instances of these "constant" objects for each user of the app.
I'm reading a lot about "Singleton", its problems, when to use it, etc., and these are my conclusions until now:
Confusion between the classic implementation of Singleton and the real requirement: TO HAVE JUST ONE INSTANCE OF a CLASS!
It's generally bad implemented. If you want a unique instance, don't use the (anti)pattern of using a static GetInstance() method returning a static object. This makes a class to be responsible for instantiating a single instance of itself and also perform logic. This breaks the Single Responsibility Principle. Instead, this should be implemented by a factory class with the responsibility of ensuring that only one instance exists.
It's used in constructors, because it's easy to use and must not be passed as a parameter. This should be resolved using dependency injection, that is a great pattern to achieve a good and testable object model.
Not TDD. If you do TDD, dependencies are extracted from the implementation because you want your tests to be easy to write. This makes your object model to be better. If you use TDD, you won't write a static GetInstance =). BTW, if you think in objects with clear responsibilities instead classes, you'll get the same effect =).
I really disagree on the bunch of global variables in a fancy dress idea. Singletons are really useful when used to solve the right problem. Let me give you a real example.
I once developed a small piece of software to a place I worked, and some forms had to use some info about the company, its employees, services and prices. At its first version, the system kept loading that data from the database every time a form was opened. Of course, I soon realized this approach was not the best one.
Then I created a singleton class, named company, which encapsulated everything about the place, and it was completely filled with data by the time the system was opened.
It was not just a bunch of variables in a fancy dress because this was had dozens of responsibilities, like communicating with persistence layer to save/retrieve data about the company, deal with employees and prices collections, etc.
Plus, it was a fixed, system-wide, easily accessible point to have the company data.
Singletons are very useful, and using them is not in and of itself an anti-pattern. However, they've gotten a bad reputation largely because they force any consuming code to acknowledge that they are a singleton in order to interact with them. That means if you ever need to "un-Singletonize" them, the impact on your codebase can be very significant.
Instead, I'd suggest either hiding the Singleton behind a factory. That way, if you need to alter the service's instantiation behavior in the future, you can just change the factory rather than all types that consume the Singleton.
Even better, use an inversion of control container! Most of them allow you to separate instantiation behavior from the implementation of your classes.
One scary thing on singletons in for instance Java is that you can end up with multiple instances of the same singleton in some cases. The JVM uniquely identifies based on two elements: A class' fully qualified name, and the classloader responsible for loading it.
That means the same class can be loaded by two classloaders unaware of each other, and different parts of your application would have different instances of this singleton that they interact with.
Write normal, testable, injectable objects and let Guice/Spring/whatever handle the instantiation. Seriously.
This applies even in the case of caches or whatever the natural use cases for singletons are. There's no need to repeat the horror of writing code to try to enforce one instance. Let your dependency injection framework handle it. (I recommend Guice for a lightweight DI container if you're not already using one).

What's the best way to organize code? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm not talking about how to indent here. I'm looking for suggestions about the best way of organizing the chunks of code in a source file.
Do you arrange methods alphabetically? In the order you wrote them? Thematically? In some kind of 'didactic' order?
What organizing principles do you follow? Why?
i normally order by the following
constructors
destructors
getters
setters
any 'magic' methods
methods for changing the persisted state of reciever (save() etc)
behaviors
public helper methods
private/protected helper methods
anything else (although if there is anything else its normally a sign that some refactoring is necessary)
I tend to use following pattern:
public static final variables
static functions, static blocks
variables
constructors
functions that do something related to logic
getters and setters (are uninteresing mostly so there is no need to read them)
I'm have no pattern of including local classes, and mostly I put them on top of first method that uses them.
I don't like separating methods depending on access level. If some public method uses some private method they will be close to one another.
I tend to group methods that relate to each other. Use of a good IDE removes much of this concern. Alphabetizing methods seems like a waste of effort to me.
I group them based on what there doing, and then in the order I wrote them (alphabetically would probs be better though)
eg in texture.cpp I have:
//====(DE)CONSTRUCTOR====
...
//====LOAD FUNCTIONS====
...
//====SAVE FUNCTIONS====
...
//====RESOURCE MANGEMENT FUNCTIONS====
//(preventing multiple copies being loaded etc)
...
//====UTILL FUNCTIONS====
//getting texture details, etc
...
//====OVERLOADED OPERTORS====
....
Pretty much use this approach for anything I am coding in. Good structure and well commented code makes good reading
Global Variables
Functions
Main Body/Method
public, protected and then private and within each section alphabetically although I often list constructor first and deconstructor last.
/Allan
I tend to group things thematically for lack of a better word.
For example, if I had a public method that used two private methods in the course of doing its work then I would group all three together in the implementation file since odds are good that if you're going to be looking at one of them then you'll need to look at one of the others.
I also always group get/set methods for a particular class member.
It's really personal preference, especially with modern IDEs since there are a lot of features that allow you to automatically jump to locations in the code.
I like to keep things simple, so I don't stuff a bunch of methods in a class. Within a class, I usually have the most commonly used (or modified-by-me ;-)) methods listed first. As far as specific code organization goes, each set of methods belongs to a class, so it organizes by itself.
I make use of my editor's search feature, and code folding to navigate through large source files. Similarly, I make use of search features to find things in other contexts too. A grand organization scheme never suited me, so I rely on the power of search in all things, not just code.
Interesting point. I hadn't really thought about this.
I tend to put frequently-accessed functions at the top (utility functions, and such), as they're most likely need tweaking.
I don't think organization is particularly important, as I can find any function quickly. I don't scroll through my file to find a function; I search for it.
In C++, I do expect that the functions in the .cpp file are in the same order in which they're declared in the .h file. Which is usually constructors, followed by destructors, followed by primary/central functionality functions, followed by utility functions.
I mostly write C code and I tend to order by dependency. If possible I try to match my source code file with me header files, but generally it's if void a() uses int b(char *foo), than int b(char *foo) comes first.
Saves me from adding entries to the header file for local functions.
For the rest it's mainly alphabetic actually, makes searching easier.
I have all the private fields, then the public, then the constructors, then the main, then the methods that main calls, in the order they are called.