문제

If I have fnc like this:

void fnc(const SomeType&){/**/}  

And when I list preconditions and postconditions for this fnc I think that listing precondition of form:
SomeType must be of a correct type is rather dumb, isn't it? I'm asking for this because at my uni they want us to list something like this but if the type of an arg won't be correct code won't compile anyway so I think it is wrong to have precondition of this form. But as usual, I my be wrong.

도움이 되었습니까?

해결책

Don't state the obvious.

As you say, the code clearly won't compile if the types don't match up.

The pre- and post-conditions will depend on what the function is trying to do.

다른 팁

If your teachers are asking you to add comments of this kind, it's probably not for the simple cases, when such comment are just plain dumb and verified by the compiler anyway.

But in some cases, the formal type defined in the algorithm may be more restrictive than the implementation type used in C++. In such cases that kind of comments may have some use.

Another usefull case is for autogenerated documentation based on comments, but the documentation system should be able to extract that information by itself from function prototype.

I'd state it like this:

The first argument shall be of type SomeType, or castable to it.

Whether compiler can check it doesn't matter. If some preconditions can be devised from signature of a function, that doesn't mean that these things aren't preconditions. Having read the preconditions, user should be capable to writing a program that would be correctly compiled and run.

Make comments like that is stupid - I agree. The comments should provide some useful information.

List of preconditions should tell what has to be satisfied in order to run the function. List of postconditions should tell what has to be satisfied at the function's exit. You can check those conditions in three ways :

  • run-time assertion (using c macro assert()), when the condition has to be fulfilled in order to run the function. Otherwise the process terminates.
  • static assertion (using std::static_assert if you use c++0x, or BOOST_STATIC_ASSERT). This is usually not done, since this check is done at the compile time
  • error mechanism (throwing an exception or returning an error code)

You can also add a list of template arguments to the function comment, and make the compilation fails if they do not match the requirements.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top