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.
Related
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 last month.
Improve this question
I am wondering... I have read about Go some time ago and I tried to program something in it. I seems quite interesting. But I have reached handling "exceptions" in this language. I have read about their approach and it seems reasonable. I would like to know what are the advantages of the standard exceptional approach over the Go's style? What are the pros and cons?
Edit To be straight: I do not want to make any holy war about exceptions. I just wonder if this style of handling errors has any advantages? What are actual advantages of this style over standard exceptions? Is it worth wondering at all?
panic/recover is moral equivalent of try/catch exceptions. There is superficial difference (syntax) and a subtle, but important, difference of intended use.
The best explanations of problems with exceptions in general is "Cleaner, more elegant, wrong" and that's a good overview of pros/cons of exceptions vs. returning error codes.
Go designers decided that error handling by returning error codes from functions is the idiomatic Go way and the language supports multiple return values to make it syntactically easy. While panic/recover is provided, the difference is not of functionality but intended use.
Other languages exposing exceptions promote their use and in practice they are used frequently (sometimes even misused).
Go discourages the use of panic/recover. You can do it but you're only supposed to do it in very limited scenarios.
If you look at Go's own standard library, most uses of panic are for signaling fatal errors, indicating either an internal error (i.e. bug) in the library code or calling the library with wrong data (e.g. passing non-json data to json decoding functions).
But as the article you linked to points out: "The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values."
This is different from languages like C#, Java, Python or C++, where a lot of standard library code can throw exceptions to signal errors. Those languages want you to use exceptions. Go discourages the use of panic/recover.
To summarize:
idiomatic Go style is to use error codes to tell the caller about errors
use panic/recover only in rare cases:
to "crash" your program when encountering internal inconsistency indicating bugs in your code. It's basically a debugging aid.
if it dramatically simplifies error handling in your code (but if the code is to be used by others, never expose such panics to callers)
In practice the important thing is to use language's idiomatic style. In Go that's returning error codes and avoiding panic/recover. In C# that's using exceptions to signal some of the errors.
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 6 years ago.
Improve this question
I had some experience on programming languages like Java, C#, Scala as well as some lower level programming language like C, C++, Objective - C.
My observation is that low level languages try separate out header files and implementation files while other higher level programming language never separate it out. Those languages use some identifiers like public, private, protected to try to do the jobs of header files. C++ also have both identifiers and header files as well
I saw one benefit of using header file (in some book like Code Complete), they talk about that using header files, people can never look at our implementation file and it helps with encapsulation.
A drawback is that it creates too many files for me. Sometimes, it looks like verbose.
It is just my thought and I don't know if there are any other benefits and drawbacks that people ever see and work with header file
This question may not relate directly to programming but I think that if I can understand better about programming to interface, design software.
They allow you to distribute the API of a library so the compiler can compile correct code.
As in C, rather than including the whole implementation, you just include the definition of what is in the library when linked.
In this sense, the benefits are mainly for the compiler. Hence you installing a binary library into say /lib and headers into your include search path. You are saying, at runtime, expect these symbols with this calling convention to be available.
When they are not required by the compiler/linker/interpreter then the convention for that language is the best way to do it because that's what other programmers expect to find. Conventional is expected.
Languages such as C# include the ability to inspect libraries for information from the binary blob, hence in many of these languages you don't require headers. Tools such as Cecil for C# also allow you to inspect a library yourself (and even modify it).
In short, some languages remove the benefits of headers and allow a library to be inspected for all the compile-time information required to ensure linking code meets the same interface/api specs.
I'm not sure exactly what question you are asking, so I will try to rephrase it:
What is the benefit of putting public information in a separate (header or interface) file, as opposed to simply marking information as public or private wherever it appears?
The main benefit of having a separate interface or header file is that it reduces the cognitive load on the reader. If you are a trying to understand a large system, you can tackle one implementation file at a time, and you need to read only the interfaces of the other implementations/classes/modules it depends on. This is a major benefit, and languages that do not require separate interface files (such as Java) or cannot even express interfaces in separate files (such as Haskell) often provide tools such as Doxygen or Haddock so that a separate interface, for people to read, is generated from the implementation.
I strongly prefer languages like Standard ML, Objective Caml, and Modula-2/3, where there is a separate interface file available for scrutiny. Having separate header files in C is also good, but not quite as good because in general, the header files cannot be checked independently by the compiler. (C++ header files are less good because they allow private information, such as private fields or the implementations of inline methods, to leak out into the header files, and so the public information becomes diluted.)
It's folklore in the language-design world that for typical statically typed languages, only about 10% of the information in a module is public (measured by lines of code). By putting this information in a separate header file, you reduce the reader's workload by roughly a factor of ten.
They use some identifiers like public, private, protected to do the jobs of header files.
I think you're wrong there: C++ for instance still has public private and protected, but it's common to split the implementation from the interface with a header file (although that doesn't go for function-templates).
I think it's in general a good idea to seperate interface from implementation when you're creating libraries, since you then never expose the inner workings of anything to the client and thus the client can never deliberately make code that depends on the implemenation. The choice if you want to split it is up to you. I must admit that for my own code (small programs I write for myself), I don't use it often.
In context of c The header file implementation brings lots of readability in our program and it becomes easy to understand. If it is the way to write our code systematically and header file brings abstraction,standardization and loose coupling between our main function file(.c) and other (.c) files which we are using.
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 1 year ago.
Improve this question
I'm trying to figure out what the correct form of exceptions to throw would be for a library I am writing. One example of what I need to handle is logging a user in to a station. They do this by scanning a badge. Possible things that could go wrong include:
Their badge is deactivated
They don't have permission to work at this station
The badge scanned does not exist in the system
They are already logged in to another station elsewhere
The database is down
Internal DB error (happens sometimes if the badge didn't get set up correctly)
An application using this library will have to handle these exceptions one way or another. It's possible they may decide to just say "Error" or they may want to give the user more useful information. What's the best practice in this situation? Create a custom exception for each possibility? Use existing exceptions? Use Exception and pass in the reason (throw new Exception("Badge is deactivated.");)? I'm thinking it's some sort of mix of the first two, using existing exceptions where applicable, and creating new ones where needed (and grouping exceptions where it makes sense).
I essentially agree with your current thinking.
Use existing core exceptions where appropriate: ArgumentException, InvalidOperationException, etc. Don't try to repurpose exceptions that are specific to some other module. Use those exceptions that have a clear, generic purpose, and don't use them for business rules. For example, InvalidOperationException should indicate a bad operation w/ regards to your API, not a violation of a business rule.
For exceptions specific to your library, create a base exception class, BadgeAuthException, and always throw that. The specific scenarios should each get their own subclass (BadgeDeactivatedException, NoPermissionsAtWorkstationException, etc.) This way apps can handle the individual sub-cases separately if they want to, but they can also just catch the generic BadgeAuthException if they don't want to grovel in specifics.
Whatever you do, ensure that the Message field always contains useful information beyond just the exception name.
Use Exception and pass in the reason (throw new Exception("Badge is deactivated.");)
This certainly is a bad practice, because it violates the purpose of exceptions - not just to signal an abnormal situation, but provide an ability to distinguish exceptions on a type level, so the user of a module can make a decision depending on a type of exception.
Generally, it is good to reuse standard exceptions as far as they can fully describe abnormal situations your code actually faces. It is quite hard to give an advise in a current situation, because exceptions can often depend on semantics ( argument exception or invalid operation exception (maybe suitable for 'Their badge is deactivated' case, for example ).
You have two species of exceptions.
Those that are specific to your application, where it's good to avoid any existing exceptions.
Your application-specific exceptions should simplify the use cases for the folks who use your libraries. 3 of your application specific exceptions are things users can do. The fourth (badge does not exist) is clearly not procedural, but far more serious.
It looks like you have two application-specific errors: user-oriented things and administrative mistakes.
The others are part of some other piece of technology; i.e., database errors. You can -- generally -- ignore these. If the DB isn't available, the API will throw errors and you can let those bubble up through your library.
You can also "wrap" these as an application-specific exception which contains a lower-level exception. This is sometimes helpful if there is a lot of lower-level technology. In your case, it's just a database. Ignore it and let the DB errors bubble through.
You can nearly never go wrong by having fine-grained exception classes that extend a common base class. That way, callers who need to specifically catch some and let others through can, and callers who want to treat them all together can do so.
I think you need to have one base exception and one subtype exception for each of the situalitions you describe (actually you can make db down and internal db error to have the same base exception). The key point is that it is good practice to have your own exceptions for your library.
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.
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.