How to document the Main method? [closed] - documentation

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
Okay, so I've got a .NET console application with it's Main method, contained in a Program class. You know, the usual:
class Program
{
static void Main(string[] args)
{
// Do something spectactular
}
}
Since I've started using StyleCop and FxCop so rigorously, I've become kind of nit-picky about making sure everything is properly documented.
Then it hit me. I have absolutely no idea how to properly document Program and Program.Main.
I suppose, in the long run, that you could go with the following:
/// <summary>
/// Encapsulates the application's main entry point.
/// </summary>
class Program
{
/// <summary>
/// The application's main entry point.
/// </summary>
static void Main(string[] args)
{
// Do something spectactular
}
}
But that seems woefully inadequate (despite the fact that my Main routines always delegate to other classes to do the work).
How do you folks document these things? Is there a recommendation or standard?

In my humble opinion, it's not worth the trouble to document the main function, especially if you are just going to say "The application's main entry point." If someone doesn't know that Main is the application's main entry point, you don't want them anywhere near your code :-)
If you were to put anything there, you might document what the expected or accepted arguments are, but I think there are better places to document program options (like, a usage function that prints usage, the users manual, a readme file, or elsewhere), since that information is useful not only to developers but also to users of the software.

Documentation is there to add something that's not obvious from the code. And tools are there to help you, not to dictate you what should and should not be documented.
"The application's main entry point" does not add anything, so don't write it.
If there's anything non-obvious like parameters, document this.

Add documentation at the class level that describes what the console program actually does, so it's purpose.
In the Main method, document the required arguments etc., unless if you hand that off, 'main entry point' does suffice.
I tend to hand it off to an instance method in Program called Run(string[] args), so in that case, document the Run method with the arguments/switches options.
The body of my Main() method then simply looks like:
Program prog = new Program();
prog.Run(args);

Don't, just don't.
Just look at those 2 samples you created and compare which is more readable?
I'll bet you'll choose the one without comments.

Related

Execute a method upon loading a class

I need to have a static constructor. I was always wondering why there is no support for this functionality.
I need to run a function once when the class is loaded, currently the way I've seen it done is just include a bunch of code in the file after the class declaration. That kinda works until you need to modify protected or private members of the class, then you would need to define a function on the class itself then call it from down there which all gets the job done but seems hacky to me.
What I went ahead and did was in my loader class after the include statement I added this little bit:
if (method_exists($class, 'onLoad')) {
$class::onLoad();
}
I am having my doubts about that, though, because there may be quite a number of classes included in a request. And this is on each request, so eventually this may add up to some processor time - which leads me to the question I want to ask, since not many classes will even have an onLoad method:
Would you consider this to be a reasonable addition to my framework?
EDIT: Regarding the suggested possible duplicate question - I am not asking for singleton this is not a static class it can be instantiated freely.
There's no reason your "SomeClass.class.php" file can't look like this:
class SomeClass {
public static function onLoad() {
// ...
}
// ...
}
SomeClass::onLoad();
Whether or not this is a Good Idea is up for debate, but I don't see anything overly wrong with initialisation code added in this way to the class file.

Objective C Asynchronous to Synchronous Database Access [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have found an open source Objective-C library for connecting to Microsoft SQL Server databases.
The problem is, that I would like to use it synchronously.
This is how my Swift project uses the library.
func execute(query: String) {
self.client.connect(host + ":" + port, username: username, password: password, database: database) { (connected) -> Void in
if connected {
self.client.execute(query, completion: { (results: Array<AnyObject>!) -> Void in
self.result = results[0] as! Array<AnyObject>
})
}
}
}
The block passed is execute asynchronously by the library. Is there a way to make the code execute synchronously so that whenever I call execute, that thread waits for the library work to complete before execute returns?
So, I have some experience with the github library you're using.
It seems most likely that you might want to make this call synchronously because of some of the problems this library has (you can't make multiple queries at once, and can't open multiple connections to the server because the library does all of its SQL work through a singleton). To resolve some of these problems, I highly recommend you check out the SQLConnect library that I wrote (after spending some time trying to use Martin's library that you're using). My library steps away from the singleton approach and you can make as many connections on as many different threads as you want.
With that said... you can make this library (and mine as well) perform synchronously.
If you notice in the SQLClient.h file, the SQLClient object specifies a workerQueue and a callbackQueue. Martin has set the callbackQueue to be on whatever queue the singleton is first instantiated on, and the workerQueue is a queue he specifies. However, these are public properties which can be set perfectly fine.
If you really want the query to perform synchronously, just set the workerQueue and callbackQueue to operate on the current queue.
SQLClient.sharedInstance.workerQueue = NSOperationQueue.currentQueue()
SQLClient.sharedInstance.callbackQueue = NSOperationQueue.currentQueue()
And then perform your query.
All of the code will execute on the same NSOperationQueue, and as such, will by synchronous.
Of course, you can do the same thing using my SQLConnect library, as the SQLConnection object similarly specifies a workerQueue and callbackQueue which you can specify to any queue you want.
With all of this said, I highly, highly, highly recommend that you allow the operation to remain asynchronous and come up with some other solution to whatever problem makes you think it should be performing synchronously. And even if you still think it should by synchronous, please be sure it's not blocking the UI thread.

Design best practice - should an object own what is passed to its constructor? [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 4 years ago.
Improve this question
I have the following class:
public class SqlCeEventStore: EventStore
{
private EventStoreDB db;
public SqlCeEventStore(EventStoreDB db)
{
this.db = db;
}
public void Dispose()
{
db.Dispose();
}
}
My problem is this: am I correct in disposing the EventStoreDB in the Dispose method of my class, given that it was passed to it in the constructor (and thus, might conceivably be reused after my class is disposed)?
That is, if I dispose it I mandate that the correct usage of my class is:
using (var store = new SqlCeEventStore(new EventStoreDB)){
{
//...
}
but I can see this alternative call being used:
using (var db = new EventStoreDB())
using (var store = new SqlCeEventStore(db))
{
//...
}
in which case I should not dispose of the EventStoreDB from the SqlCeEventStore class.
Are there any arguments for one style or the other? I want to pick one and stick to it, and I'd rather not flip a coin :)
In general there is no rule to this, but yes I would agree that since the object was created outside your scope and was passed to you, you don't own it.
If you had created it, then you should have all rights to do whatever you like to (with documenting the expected behavior for the callers)
This is the classical composition vs aggregation stuff.
If the EventStoreDB is owned by SqlEventStore (ie is part of its composition), it should be constructed by or be merged with the SqlEventStore class.
If it has uses outside the scope of the SqlEventStore lifetime then it should be created and disposed by the external code.
There is no general rule here, and IMHO, there should not be one either. Different objects have different lifespans, and the most general guideline would be to make sure that objects are managed consistently according to their lifespans, and that lifespans are as short as possible.
You could try to use the following as a guideline (but don't be afraid to deviate when you need to): Dispose of an object in the same scope as you allocate it. This guideline is suitable for many scenarios, and it is exactly what the using statement simplifies.
If you have long-lived objects without an obvious disposal point, don't worry. That's normal. However, ask yourself this: Do I really need this object to live for as long as it does? Is there some other way I can model this to make the lifespan shorter? If you can find another way that makes the lifespan shorter, that generally makes the object more manageable, and should be preferred.
But again, there is not any "one true rule" here.
You can not pick one and stick to it. The user can always choose what ever he wants.
However, keep in mind that you are not responsible as a class of disposing objects passed through the constructor.
note
The coming is really silly to discuss because if you want to impose initiation of the class using *new SqlCeEventStore(new EventStoreDB))* then why don't you remove this EventStoreDB parameter and instantiate the variable db inside your constructor.
Workaround
There is a workaround -check this:
public myClass {
//do not make the constructor public //hide it
private myClass(EventStoreDB db){
this.db = db;
}
//make a public constructor that will call the private one in the way you want
public myClass(){
this(myClass(new EventStoreDB()));
}
}
I would suggest that if one can reasonably imagine situations in which the constructed object would be the last thing in the universe that's interested in the passed-in object, as well as situations in which other things will want to keep using the passed-in object after the constructor is done with it, it may be desirable to have a constructor parameter which specifies whether the new object should take ownership of the object that was passed in.
Note that if the constructed object will be taking ownership of the passed-in object, it's important to make certain that object will be disposed even if the constructor throws an exception. One way to do this would be to wrap the constructor call in a routine which will, in a "finally" block, dispose the passed-in object unless the constructor had completed successfully.

FxCop (/VS2010 Code Analysis), possible to flag method result as "callers responsibility now" for IDisposable?

If I write the following code:
public void Execute()
{
var stream = new MemoryStream();
...
}
then code analysis will flag this as:
Warning 1 CA2000 : Microsoft.Reliability : In method 'ServiceUser.Execute()', call System.IDisposable.Dispose on object 'stream' before all references to it are out of scope. C:\Dev\VS.NET\DisposeTest\DisposeTest\ServiceUser.cs 14 DisposeTest
However, if I create a factory pattern, I still might be required to dispose of the object, but now FxCop/Code Analysis doesn't complain. Rather, it complains about the factory method, not the code that calls it. (I think I had an example that did complain about the factory method, but the one I post here doesn't, so I struck that out)
Is there a way, for instance using attributes, to move the responsibility of the IDisposable object out of the factory method and onto the caller instead?
Take this code:
public class ServiceUser
{
public void Execute()
{
var stream = StreamFactory.GetStream();
Debug.WriteLine(stream.Length);
}
}
public static class StreamFactory
{
public static Stream GetStream()
{
return new MemoryStream();
}
}
In this case, there are no warnings. I'd like FxCOP/CA to still complain about my original method. It is still my responsibility to handle that object.
Is there any way I can tell FxCOP/CA about this? For instance, I recently ventured into the annotation attributes that ReSharper has provided, in order to tell its analysis engine information it would otherwise not be able to understand.
So I envision something like this:
public static class StreamFactory
{
[return: CallerResponsibility]
public static Stream GetStream()
{
return new MemoryStream();
}
}
Or is this design way off?
There is a difference between FxCop 10 (which ships with the Windows 7 and .NET 4.0 SDK) and Code Analysis 2010 (which ships with Visual Studio Premium and higher). Code Analysis 2010 has a set of additional rules, which includes a highly improved version of the IDisposable rules.
With Code Analysis 2010 under Visual Studio Premium, the Factory isn't being flagged (as the rule now sees the IDisposable variable is returned to the calling method). The Receiving method, however, isn't flagged either, due to one of the corner case exceptions to the rule. There is a list of method names that will cause the rule to trigger. If you rename your GetStream method to CreateStream, suddenly the rule will trigger:
Warning 4 CA2000 : Microsoft.Reliability : In method 'ServiceUser.Execute()',
call System.IDisposable.Dispose on object 'stream' before all references to it are out
of scope. BadProject\Class1.cs 14 BadProject
I was unable to locate the list of method pre-fixes that will work. I've tried a few and Create~, Open~ trigger the rule, many others that you might expect to work, don't, including Build~, Make~, Get~.
Additionally there is a long list of bugs surrounding this rule. The rule was altered in Visual Studio 2010 to trigger fewer false positives, but now it sometimes misses items it should have flagged (and would have flagged in the previous version). There wasn't enough time to fix the rules in the Visual Studio 2010 time frame (check the bug report comments).
With the upcoming Roslyn compilers, Code Analysis will probably see a major upgrade, until then there are only minor updates to be expected. The current build of Visual Studio Dev11 does not trigger where you want it.
So concluding, no your attribute wouldn't help much, as the rule already detects that you're passing the IDisposable as a return value. Thus Code Analysis knows it's not good to dispose it before returning. If you're using the undocumented naming rules, the rule will trigger. Maybe an attribute could extend the naming rules, but I'd rather have Microsoft would actually fix the actual rule.
I created a connect bug requesting the naming guideline to be documented in the rules documentation.
Comment from Microsoft:
Posted by Microsoft on 1/19/2012 at 10:41 AM
Hello,
Thank you for taking the time to investigate this and file the request for the documentation update. However after some discussion with our documentation team, we have decided to not document the naming convention as you requested.
As you indicated on the stackoverflow thread, there have historically been a lot of reliability issues with this rule, and keying off of the names was an internal implementation detail added to try to reduce the number of false positives. However this is not considered prescriptive guidance for how developers should name their methods, it was added after a survey of common coding practices. We believe the long-term fix is to improve the reliability of the rule, not add naming guidance to our public documentation based on internal implementation details that will continue to change as the rule is improved.
Best Regards,
Visual Studio Code Analysis Team

Where to put the doxygen comment blocks for an internal library - in H or in CPP files? [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
The common sense tells that the Doxygen comment blocks have to be put in the header files where the classes, structs, enums, functions, declarations are. I agree that this is a sound argument for a libraries that are mean to be distributed without its source (only headers and libs with object code).
BUT...I've been thinking of the exact opposite approach when I'm developing an internal to the company (or as a side project for myself) library that will be used with its full source code. What I propose is to put the large comment blocks in the implementations files (HPP, INL, CPP, etc) in order NOT to clutter the inteface of the classes and functions declared in the header.
Pros:
Less clutter in the header files, only categorizing of the functions can be added.
The comment blocks that are previewed when Intellisense for example is used doesn't clash - this is a defect that I have observed when I have a comment block for a function in the .H file and have its inline definition in the same .H file but included from .INL file.
Cons:
(The obvious one) The comment blocks are not in the header files where the declarations are.
So, what do you think and possibly suggest?
I like to make use of the fact that names can be documented in multiple places.
In the header file, I write a brief description of the method, and document all its parameters - these are less likely to change than the implementation of the method itself, and if they do, then the function prototype needs to be changed in any case.
I put long-format documentation in the source files next to the actual implementation, so the details can be changed as the method evolves.
For example:
mymodule.h
/// #brief This method adds two integers.
/// #param a First integer to add.
/// #param b Second integer to add.
/// #return The sum of both parameters.
int add(int a, int b);
mymodule.cpp
/// This method uses a little-known variant of integer addition known as
/// Sophocles' Scissors. It optimises the function's performance on many
/// platforms that we may or may not choose to target in the future.
/// #TODO make sure I implemented the algorithm correctly with some unit tests.
int add(int a, int b) {
return b + a;
}
Put the documentation where people will read and write it as they are using and working on the code.
Class comments go in front of classes, method comments in front of methods.
That is the best way to make sure things are maintained. It also keeps your header files relatively lean and avoids the touching issue of people updating method docs causing headers to be dirty and triggering rebuilds. I have actually known people use that as an excuse for writing documentation later!
Having comments in the header means that all users of a class must be recompiled if a comment is changed. For a large projects, coders will be less inclined to update comments in headers if they risk spending the next 20min rebuilding everything.
And.. since you're supposed to read the html doc and not browse through the code for documentation, it's not a large problem that the comment blocks are more difficult to locate in the source files.
Headers:
Easier to read the comments since there is less other "noise" when looking at the files.
Source:
Then you have the actual functions available for reading while looking at the comments.
We just use all global functions commented in headers and local functions commented in source. If you want you can also include the copydoc command to insert the documentation in multiple places without having to write it several times ( better for maintenance )
You could however also get the results copied over to different file documentation with a simple command. E.g. :-
My file1.h
/**
* \brief Short about function
*
* More about function
*/
WORD my_fync1(BYTE*);
MY file1.c
/** \copydoc my_func1 */
WORD my_fync1(BYTE* data){/*code*/}
Now you get the same documentation on both functions.
This gives you less noise in the code files at the same time you get the documentation written in one place presented in several places in the final output.
I'm using QtCreator for programming. A very useful trick consists in Ctrl-Clicking on a function or method to get the declaration in the header file.
When the method is commented in the header file, you can quickly find the information you are looking for. So for me, comments should be located in the header file!
Usually I put documentation for interface (\param, \return) in .h file and documentation for implementation (\details) in .c/.cpp/.m file. Doxygen groups everything in the function/method documentation.
I put everything in the header file.
I document everything, but only generally extract the public interface.
In c++ sometimes implementation can be split between header and .cpp modules. Here it seems cleaner to put it documentation into the header file as that is the only place that all public functions and methods are guaranteed.