问:
Is possible to write too many asserts?
I am a big fan of writing assert checks in C++ code as a way to catch cases during development that cannot possibly happen but do happen because of logic bugs in my program. This is a good practice in general.

However, I've noticed that some functions I write (which are part of a complex class) have 5+ asserts which feels like it could potentially be a bad programming practice, in terms of readability and maintainability. I think it's still great, as each one requires me to think about pre- and post-conditions of functions and they really do help catch bugs. However, I just wanted to put this out there to ask if there is a better paradigms for catching logic errors in cases when a large number of checks is necessary.

Emacs comment: Since Emacs is my IDE of choice, I have it slightly gray out the assert statements which helps reduce the feeling of clutter that they can provide. Here's what I add to my .emacs file:

```<code>; gray out the "assert(...)" wrapper
(add-hook 'c-mode-common-hook
  (lambda () (font-lock-add-keywords nil
    '(("\\<\\(assert\(.*\);\\)" 1 '(:foreground "#444444") t)))))

; gray out the stuff inside parenthesis with a slightly lighter color
(add-hook 'c-mode-common-hook
  (lambda () (font-lock-add-keywords nil
    '(("\\<assert\\(\(.*\);\\)" 1 '(:foreground "#666666") t)))))
</code>```

答:
I want to work with you! Someone who writes a lot of asserts is fantastic. I don't know if there's such a thing as "too many". Far more common to me are people who write too few and ultimately end up running into the occasional deadly UB issue which only shows up on a full moon which could have been easily reproduced repeatedly with a simple assert.

Fail Message

The one thing I can think of is to embed failure information into the assert if you aren't doing it already, like so:

```<code>assert(n >= 0 && n < num && "Index is out of bounds.");
</code>```

This way you might no longer feel like you have too many if you weren't already doing this, as now you're getting your asserts to play a stronger role in documenting assumptions and preconditions.

Side Effects

Of course assert can actually be misused and introduce errors, like so:

```<code>assert(foo() && "Call to foo failed!");
</code>```

... if foo() triggers side effects, so you should be very careful about that, but I'm sure you are already as one who asserts very liberally (an "experienced asserter"). Hopefully your testing procedure is also as good as your careful attention to assert assumptions.

Debugging Speed

While the speed of debugging should generally be on the bottom of our priority list, one time I did end up asserting so much in a codebase before that running the debug build through the debugger was over 100 times slower than release.

It was primarily because I had functions like this:

```<code>vec3f cross_product(const vec3f& lhs, const vec3f& rhs)
{
    return vec3f
    (
        lhs[1] * rhs[2] - lhs[2] * rhs[1],
        lhs[2] * rhs[0] - lhs[0] * rhs[2],
        lhs[0] * rhs[1] - lhs[1] * rhs[0]
    );
}
</code>```

... where every single call to operator[] would do a bounds-checking assertion. I ended up replacing some of those performance-critical ones with unsafe equivalents that don't assert just to speed up the debugging build drastically at a minor cost to just implementation-detail-level safety, and only because the speed hit of it was starting to very noticeably degrade productivity (making the benefit of getting faster debugging outweigh the cost of losing a few asserts, but just for functions like this cross product function which was being used in the most critical, measured paths, not for operator[] in general).

Single Responsibility Principle

While I don't think you can really go wrong with more asserts (at least it's far, far better to err on the side of too many than too few), the asserts themselves may not be a problem but may be indicating one.

If you have like 5 assertions to a single function call, for example, it might be doing too much. Its interface might have too many preconditions and input parameters, e.g. I consider that unrelated to just the topic of what constitutes a healthy number of assertions (for which I'd generally respond, "the more the merrier!"), but that might be a possible red flag (or very possibly not).

Title: Is possible to write too many asserts?

Body:
I want to work with you! Someone who writes a lot of asserts is fantastic. I don't know if there's such a thing as "too many". Far more common to me are people who write too few and ultimately end up running into the occasional deadly UB issue which only shows up on a full moon which could have been easily reproduced repeatedly with a simple assert.

Fail Message

The one thing I can think of is to embed failure information into the assert if you aren't doing it already, like so:

assert(n >= 0 && n < num && "Index is out of bounds.");

This way you might no longer feel like you have too many if you weren't already doing this, as now you're getting your asserts to play a stronger role in documenting assumptions and preconditions.

Side Effects

Of course assert can actually be misused and introduce errors, like so:

assert(foo() && "Call to foo failed!");

... if foo() triggers side effects, so you should be very careful about that, but I'm sure you are already as one who asserts very liberally (an "experienced asserter"). Hopefully your testing procedure is also as good as your careful attention to assert assumptions.

Debugging Speed

While the speed of debugging should generally be on the bottom of our priority list, one time I did end up asserting so much in a codebase before that running the debug build through the debugger was over 100 times slower than release.

It was primarily because I had functions like this:

vec3f cross_product(const vec3f& lhs, const vec3f& rhs)
{
    return vec3f
    (
        lhs[1] * rhs[2] - lhs[2] * rhs[1],
        lhs[2] * rhs[0] - lhs[0] * rhs[2],
        lhs[0] * rhs[1] - lhs[1] * rhs[0]
    );
}

... where every single call to operator[] would do a bounds-checking assertion. I ended up replacing some of those performance-critical ones with unsafe equivalents that don't assert just to speed up the debugging build drastically at a minor cost to just implementation-detail-level safety, and only because the speed hit of it was starting to very noticeably degrade productivity (making the benefit of getting faster debugging outweigh the cost of losing a few asserts, but just for functions like this cross product function which was being used in the most critical, measured paths, not for operator[] in general).

Single Responsibility Principle

While I don't think you can really go wrong with more asserts (at least it's far, far better to err on the side of too many than too few), the asserts themselves may not be a problem but may be indicating one.

If you have like 5 assertions to a single function call, for example, it might be doing too much. Its interface might have too many preconditions and input parameters, e.g. I consider that unrelated to just the topic of what constitutes a healthy number of assertions (for which I'd generally respond, "the more the merrier!"), but that might be a possible red flag (or very possibly not).


问:
OpenGL, multithreading, and throwing destructors
How do you make an class that properly warns a developer in the future that they've made a mistake somewhere in their implementation that resulted in an object that gets deconstructed in a state that prevents the release of it's resources?

Background:

I recently upgraded to Visual Studio 2015 and began reloading and compiling code for a game engine I'm working on and ran into a new series of warnings "warning C4297: '*': function assumed not to throw an exception but does". A quick search revealed a C++ convention that I'd missed and the reasons behind said convention: destructors should not throw exceptions. I also can't really argue with the reasons, but I'm also not sure how to work around the problem.

Within OpenGL a Context basically holds all of the state information for the OpenGL engine. Only one thread may have a context at any given time and each thread may only have one current context. When the engine starts it creates the context and then relinquishes control over the context and starts up another thread which picks it up and proceeds to handle the graphics rendering for the engine. To handle all of this, I created a graphics engine class that uses semantics similar to a mutex to claim and relinquish the graphics engine and make sure that no mistakes are made that might some day result in someone attempting to do things with a context that it doesn't own.

During destruction, the graphics engine and a number of other classes that rely on it all check to make sure that the current thread has claimed the graphics engine before they perform actions that are necessary in their destruction. If the thread didn't have the graphics context claimed, the destructor was throwing. My goal was really to provide some basic protection against the class being used improperly on accident in the future, not to make the graphics engine thread-safe. Now... I'm uncertain of how best to handle this.

I've contemplated just switching over to a mutex-based approach which I could use to block access to the graphics context until a thread was done, possibly making the graphics engine class fully multi-threading capable (not that I can understand why you'd want to perform multi-threading with an OpenGL context, as the calls needed to do so are expensive enough to negate any benefit you might get out of it from what I understand).

The most tempting option has been to just log an error terminate any thread that attempts to misuse the class. Unfortunately, I can't find an OS-independent way of terminating just the current thread. If I was to go this route, I'd have to look up OS-appropriate ways to terminate the current threads.

I'm also not certain that I'm not being overly paranoid. Maybe I should just document the proper use of the class and if someone misuses it let them and hope that they're able to figure out why their application isn't doing what it's supposed to. I'm also worried about myself being the fool who misuses the class some day in the future.

答:
I get the impression that your goal in having the destructor throw an exception was to make it as clear as possible to library users that their program was incorrect in the way it was managing the lifetime of the object.  This is a noble goal, but I have some problems with the particular approach you are using for this particular problem.

An exception rises up when a program encounters a run-time error. But
the error was made at program-writing time (library users mismanaged
your object's lifetime).  So the earliest, most obvious time you can
make library users aware of their error is at compile time.

The root of the issue is a concurrency issue.  At run-time, the way
the OS schedules your program's execution is non-deterministic (as
far as you know).  So in fact, your indication to library-users that
their code uses your library incorrectly might not even appear, or it
could only appear some of the time.  And library users won't be able
to reliably reproduce the issue (probably).  So its actually a real troublesome and unreliable indicator that they did something wrong!

So my thinking is that your approach with throwing an exception in the destructor isn't really great at what you want to do anyway.  I don't think you should fight the current and try to keep doing it the way you're doing it right now, or a similar way by logging things and terminating threads at run-time.  I think you should move away from trying to "handle" this issue at run-time (by handle I mean "make it obvious to the programmer they need to fix their program").

You might want to re-think your architecture a little bit.  I also have two more specific recommendations:

Make the destructor block the current thread until it can acquire the graphics engine to release the resource.  Simple, but possibly undesirable if you don't want to wait to acquire the graphics engine.

Do graphics-engine tasks on a dedicated thread, and use a message queue pattern so other threads can dispatch certain tasks to the graphics engine.

As you can see from my recommendations, I think making your graphics engine thread-safe will save you a lot of headaches in the future even though you may have some doubts about doing that work at the moment.  Both these recommendations shouldn't require a radical departure from your current architecture either (hopefully).

Hope this helps.

OwnerDisplayName: Darinth

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: dog jones


问:
Is it reasonable to null guard every single dereferenced pointer?
At a new job, I've been getting flagged in code reviews for code like this:

```<code>PowerManager::PowerManager(IMsgSender* msgSender)
  : msgSender_(msgSender) { }

void PowerManager::SignalShutdown()
{
    msgSender_->sendMsg("shutdown()");
}
</code>```

I'm told that last method should read:

```<code>void PowerManager::SignalShutdown()
{
    if (msgSender_) {
        msgSender_->sendMsg("shutdown()");
    }
}
</code>```

i.e., I must put a NULL guard around the msgSender_ variable, even though it is a private data member. It's difficult for me to restrain myself from using expletives to describe how I feel about this piece of 'wisdom'. When I ask for an explanation, I get a litany of horror stories about how some junior programmer, some-year, got confused about how a class was supposed to work and accidentally deleted a member he shouldn't have (and set it to NULL afterwards, apparently), and things blew up in the field right after a product release, and we've "learned the hard way, trust us" that it's better to just NULL check everything.

To me, this feels like cargo cult programming, plain and simple. A few well-meaning colleagues are earnestly trying to help me 'get it' and see how this will help me write more robust code, but... I can't help feeling like they're the ones who don't get it.

Is it reasonable for a coding standard to require that every single pointer dereferenced in a function be checked for NULL first—even private data members? (Note: To give some context, we make a consumer electronics device, not an air traffic control system or some other 'failure-equals-people-die' product.)

EDIT: In the above example, the msgSender_ collaborator isn't optional. If it's ever NULL, it indicates a bug. The only reason it is passed into the constructor is so PowerManager can be tested with a mock IMsgSender subclass.

SUMMARY: There were some really great answers to this question, thanks everyone. I accepted the one from @aaronps chiefly due to its brevity. There seems to be fairly broad general agreement that:

Mandating NULL guards for every single dereferenced pointer is overkill, but

You can side-step the whole debate by using a reference instead (if possible) or a const pointer, and

assert statements are a more enlightened alternative to NULL guards for verifying that a function's preconditions are met.

答:
This is Outright Dangerous!

I worked under a senior developer in a C codebase with the shoddiest "standards" who pushed for the same thing, to blindly check all pointers for null. The developer would end up doing things like this:

```<code>// Pre: vertex should never be null.
void transform_vertex(Vertex* vertex, ...)
{
    // Inserted by my "wise" co-worker.
    if (!vertex)
        return;
    ...
}
</code>```

I once tried removing such a check of the precondition one time in such a function and replacing it with an assert to see what would happen.

To my horror, I found thousands of lines of code in the codebase which were passing nulls to this function, but where the developers, likely confused, worked around and just added more code until things worked.

To my further horror, I found this issue was prevalent in all sorts of places in the codebase checking for nulls. The codebase had grown over decades to come to rely on these checks in order to be able to silently violate even the most explicitly-documented preconditions. By removing these deadly checks in favor of asserts, all the logical human errors over decades in the codebase would be revealed, and we would drown in them.

It only took two seemingly-innocent lines of code like this + time and a team to end up masking a thousand accumulated bugs.

These are the kinds of practices that make bugs depend on other bugs to exist in order for the software to work. It's a nightmare scenario. It also makes every logical error related to violating such preconditions show up mysteriously a million lines of code away from the actual site in which the mistake occurred, since all these null checks just hide the bug and hide the bug until we reach a place that forgot to hide the bug.

To simply check for nulls blindly in every place where a null pointer violates a precondition is, to me, utter insanity, unless your software is so mission-critical against assertion failures and production crashes that the potential of this scenario is preferable.

Is it reasonable for a coding standard to require that every single
  pointer dereferenced in a function be checked for NULL first—even
  private data members?

So I'd say, absolutely not. It's not even "safe". It may very well be the opposite and mask all kinds of bugs throughout your codebase which, over the years, can lead to the most horrific scenarios.

assert is the way to go here. Violations of preconditions should not be allowed to go unnoticed, or else Murphy's law can easily kick in.

Body:
This is Outright Dangerous!

I worked under a senior developer in a C codebase with the shoddiest "standards" who pushed for the same thing, to blindly check all pointers for null. The developer would end up doing things like this:

// Pre: vertex should never be null.
void transform_vertex(Vertex* vertex, ...)
{
    // Inserted by my "wise" co-worker.
    if (!vertex)
        return;
    ...
}

I once tried removing such a check of the precondition one time in such a function and replacing it with an assert to see what would happen.

To my horror, I found thousands of lines of code in the codebase which were passing nulls to this function, but where the developers, likely confused, worked around and just added more code until things worked.

To my further horror, I found this issue was prevalent in all sorts of places in the codebase checking for nulls. The codebase had grown over decades to come to rely on these checks in order to be able to silently violate even the most explicitly-documented preconditions. By removing these deadly checks in favor of asserts, all the logical human errors over decades in the codebase would be revealed, and we would drown in them.

It only took two seemingly-innocent lines of code like this + time and a team to end up masking a thousand accumulated bugs.

These are the kinds of practices that make bugs depend on other bugs to exist in order for the software to work. It's a nightmare scenario. It also makes every logical error related to violating such preconditions show up mysteriously a million lines of code away from the actual site in which the mistake occurred, since all these null checks just hide the bug and hide the bug until we reach a place that forgot to hide the bug.

To simply check for nulls blindly in every place where a null pointer violates a precondition is, to me, utter insanity, unless your software is so mission-critical against assertion failures and production crashes that the potential of this scenario is preferable.

Is it reasonable for a coding standard to require that every single
  pointer dereferenced in a function be checked for NULL first—even
  private data members?

So I'd say, absolutely not. It's not even "safe". It may very well be the opposite and mask all kinds of bugs throughout your codebase which, over the years, can lead to the most horrific scenarios.

assert is the way to go here. Violations of preconditions should not be allowed to go unnoticed, or else Murphy's law can easily kick in.


问:
what are the benefits of closure, primarily for PHP?
I am beginning the process of moving code over to PHP 5.3 and one of the most highly touted features of PHP 5.3 is the ability to use closures.  My understanding of closures is that they allow anonymous functions, can be assigned to variable names, and have interesting scoping abilities.

From my point of view the only seeming benefits in real world applications is the reduction of clutter in the namespace because closures are anonymous.

Am I wrong in this?

Should I be trying to put closures wherever I code?

EDIT:

I have already read this post on Javascript closures.

答:
As a guy whose responsibility among other things is unit testing in php using PhpUnit, Closures are also you great friend for testing a code which was not written in the best regards of test.

About two months ago I took over a team who had been developing a project with no unit tests what so ever and decided to dedicate a few programmers to learn how to unit test and write the tests. The project had service locator all over it, and I had to find a solution on how to solve the problem and with the help of a SO user Elias Van Ootegem I was able to.

As mentioned in the post, you can also simulate parameters passed and returned through a reference.

Should you have a function to test:

```<code>public function ReturnIntAndChangeOutputParameter(&$outputParameter = false)
{
    $outputParameter = true;
    return 10;
}
</code>```

You can use callback to simulate the parameter return:

```<code>$function = function(&$outputParameter)
{
    $outputParameter = true;
    return 10;
}

$classMock
    ->expects(/* */)
    ->method('ReturnIntAndChangeOutputParameter')
    ->will($this->returnCalback($function));
</code>```

In fact, when writing unit tests, this is the only way how to do that, PhpUnit otherwise converts all variables to be passed by value even if the definition is pass by reference.

ContentLicense: CC BY-SA 2.5

Body:
As a guy whose responsibility among other things is unit testing in php using PhpUnit, Closures are also you great friend for testing a code which was not written in the best regards of test.

About two months ago I took over a team who had been developing a project with no unit tests what so ever and decided to dedicate a few programmers to learn how to unit test and write the tests. The project had service locator all over it, and I had to find a solution on how to solve the problem and with the help of a SO user Elias Van Ootegem I was able to.

As mentioned in the post, you can also simulate parameters passed and returned through a reference.

Should you have a function to test:

public function ReturnIntAndChangeOutputParameter(&$outputParameter = false)
{
    $outputParameter = true;
    return 10;
}

You can use callback to simulate the parameter return:

$function = function(&$outputParameter)
{
    $outputParameter = true;
    return 10;
}

$classMock
    ->expects(/* */)
    ->method('ReturnIntAndChangeOutputParameter')
    ->will($this->returnCalback($function));

In fact, when writing unit tests, this is the only way how to do that, PhpUnit otherwise converts all variables to be passed by value even if the definition is pass by reference.


问:
How to implement efficient heterogeneous microservice data queries?
Our team has an idea of implementing a simple declarative DSL that would let users query the enterprise's domain model via a single interface without caring which specific microservices to call to get specific portions of data and how to then relate and combine them.

Suggested syntax is based on SQL, but:

Is much more limited: no grouping or aggregation, no explicit subqueries, no functions etc.

Joins cannot be specified and are only implicit based on the predefined schema (entities and relations).

Example:

SELECT entityTypeOne.name, entityTypeTwo.value, entityTypeTwo.date
 WHERE entityTypeOne.name LIKE 'Sample%'
   AND entityTypeTwo.date BETWEEN (2015-05-01, 2015-05-31)
```

<p>Expected result:</p>

```╔════════╦═══════╦════════════╗
║  name  ║ value ║    date    ║
╠════════╬═══════╬════════════╣
║ London ║  1000 ║ 01/05/2015 ║
║ London ║  2000 ║ 02/05/2015 ║
║ London ║  3000 ║ 03/05/2015 ║
║ Moscow ║  2000 ║ 02/05/2015 ║
║ Moscow ║  9000 ║ 05/05/2015 ║
║ Tokyo  ║  1000 ║ 30/05/2015 ║
╚════════╩═══════╩════════════╝
```

The underlying entity-relation schema knows that entities are related like this: entityTypeOne.id = entityTypeTwo.parentId which creates an implicit join.

The "query engine" should know that it will first query the entityTypeTwo microservice applying the date range filtering on server, then entityTypeOne microservice applying the id filtering based on previous query's result.

The problems we currently see:

Representing the object-relation schema.

Figuring out the optimal order of querying.

Denormalizing resulting data.

I was wondering if this is a known problem and if there are any algorithms to check (maybe something from graph theory)?

This is the closest thing I could find so far:

What is a heterogeneous query?

If it makes things simpler we can assume that microservices are exposing data via OData.

答:
If what you are trying to do is present a single endpoint to many APIs, you might find some value in Netflix' Falcor project.

Falcor is not a query engine. It is a library for "efficient data fetching." It is one example of a growing set of tools delivering "Demand Driven Architectures" -- alternatives to traditional rest services that allow the author of a client tool to specify what they want in terms related to a canonical data model, thus obviating the need to develop UIs (the demand) in tandem with a backend. The "fetch" tools translate the canonical model into calls to individual rest services, and a combination of in-browser and reverse proxy caches make things efficient by avoiding subsequent calls to the data services for the same data.

To paraphrase Falcor lead author Jafar Husein: picture your service graph not as a bunch of discrete services, but as a single massive JSON Graph document. That is what users feel they are making requests of -- and Falcor handles the necessary caching, batching and routing that make it efficient.

It's almost as if these tools bring SELECT and WHERE clause behavior to a collection of REST APIs. And while that's not quite the same as building an efficient query API on top of REST, it may offer you the same benefits -- without your having to invent an efficient query processor, which frankly could take years.


问:
Does making a method static save memory on a class you'll have many instances of?
In response to Aaronaught's response to the question at:

Can't I just use all static methods?

Isn't less memory used for a static method? I am under the impression that each object instance carries around its own executable version of a non-static member function.

Regardless of how much overhead is involved in calling a static method, regardless of poor OO design, and possible headaches down the road, doesn't it use less memory at runtime?

Here is an example:

I make a vector of zero-initialized objects. Each object contains one piece of data (a triangle consisting of nine double's). Each object is populated in sequence from data read from a .stl file. Only one static method is needed. Proper OO design dictates that a method dealing with the the data directly should be distributed to each object. Here is the standard OO solution:

```<code>foreach(obj in vec) {
  obj.readFromFile(fileName);
}
</code>```

Each obj carries readFromFile's compiled code alongside the data!

Memory is more of a concern than performance in this case, and there is a LOT of data on a constrained system.

Solutions:

Namespace method (great for C++ but not possible in Java)

One static method in obj's class. Executable code is kept in one place at runtime. There is a small overhead to call the method.

A parent class from which obj is derived, which contains the private method readFromFile. Call with super.callPrivateMethod() which calls readFromFile. Messy, and still some memory overhead in each object.

Implement readFromFile outside obj's scope, so in vec's class or in the calling class. This, in my opinion, breaks data encapsulation.

I realize for large amounts of data one explicit object for each triangle is not the best approach. This is only an example.

答:
In principle, there's only one copy of the code, whether it's static member functions or not:

In C++ you can easily verify this by looking at the assembler list of the generated code.

I'm not Java expert, but from the JNI specification you can deduce it's the same logic: you can fetch a single reference to a function and call it many times for different objects (passing it a class reference as argument, as well as the object reference if it's not a static method).

Using a static or a non-static function will hence not change the memory footprint.

There is in reality a very very small difference, both in the code generated as well as in the memory consumed on the stack during the execution time of the function:

A call to the non-static function requires to pass a reference/pointer to the object on which the function/method is applied.  This requires usually an additional push and a pop instructions in the calling sequence.

A call to a static function doesn't require this overhead.

But this is truly negligible:  we are speaking of one or two machine instructions more or less compared to the full code. So it's definitively not something to worry about.

The stack consumption difference at run-time is limited to the time of the execution of the function, to the size of a pointer.  This is also negligible, unless you are thinking of a a function called recursively a huge number of times (several millions of time).

So in conclusion, I fully share gnasher729 opinion:  premature optimization is the root of all evil.  If the function is independent of the object make it static and that should be the only criteria.


答:
Your fundamental problem is that you've designed a contradiction.

On the one hand, your objects are RAII-encapsulated, managing resources from another system (OpenGL). But on the other hand, all of your objects silently and invisibly depend on something that isn't encapsulated: the current context. Your objects need it, but they cannot control it.

So you really only have two options:

Accept reality. Your interface is fragile, and users have to use it correctly in order to get reasonable results. They must have the proper context bound when they use your objects in any way, whether creating them, using them, or destroying them. If they violate this... things blow up.

Personally, I'd go with this option. If you're writing a graphics application that needs to talk to OpenGL, then performance is probably not unimportant to you. And this is probably the highest performing way to do it. You get reasonable RAII safety from sane use of the API.

Bring the context into the abstraction. Do not give users the freedom to break your objects. One way to do this would be to make it so that objects are really owned by the context object. Thus, destruction of an object is just a signal to the context object to get rid of it later. This also means each RAII-wrapped OpenGL object becomes non-functional once the context is destroyed.

This will generally require a lot of overhead. The RAII-wrapped objects have to talk to the context object a lot. And the context object needs to know about every RAII-wrapped object in existence. That sounds like a lot of pointer indirection, weak-references, and other non-trivially expensive things.

Title: OpenGL, multithreading, and throwing destructors

Body:
How do you make an class that properly warns a developer in the future that they've made a mistake somewhere in their implementation that resulted in an object that gets deconstructed in a state that prevents the release of it's resources?

Background:

I recently upgraded to Visual Studio 2015 and began reloading and compiling code for a game engine I'm working on and ran into a new series of warnings "warning C4297: '*': function assumed not to throw an exception but does". A quick search revealed a C++ convention that I'd missed and the reasons behind said convention: destructors should not throw exceptions. I also can't really argue with the reasons, but I'm also not sure how to work around the problem.

Within OpenGL a Context basically holds all of the state information for the OpenGL engine. Only one thread may have a context at any given time and each thread may only have one current context. When the engine starts it creates the context and then relinquishes control over the context and starts up another thread which picks it up and proceeds to handle the graphics rendering for the engine. To handle all of this, I created a graphics engine class that uses semantics similar to a mutex to claim and relinquish the graphics engine and make sure that no mistakes are made that might some day result in someone attempting to do things with a context that it doesn't own.

During destruction, the graphics engine and a number of other classes that rely on it all check to make sure that the current thread has claimed the graphics engine before they perform actions that are necessary in their destruction. If the thread didn't have the graphics context claimed, the destructor was throwing. My goal was really to provide some basic protection against the class being used improperly on accident in the future, not to make the graphics engine thread-safe. Now... I'm uncertain of how best to handle this.

I've contemplated just switching over to a mutex-based approach which I could use to block access to the graphics context until a thread was done, possibly making the graphics engine class fully multi-threading capable (not that I can understand why you'd want to perform multi-threading with an OpenGL context, as the calls needed to do so are expensive enough to negate any benefit you might get out of it from what I understand).

The most tempting option has been to just log an error terminate any thread that attempts to misuse the class. Unfortunately, I can't find an OS-independent way of terminating just the current thread. If I was to go this route, I'd have to look up OS-appropriate ways to terminate the current threads.

I'm also not certain that I'm not being overly paranoid. Maybe I should just document the proper use of the class and if someone misuses it let them and hope that they're able to figure out why their application isn't doing what it's supposed to. I'm also worried about myself being the fool who misuses the class some day in the future.


答:
This is the darker side of OpenGL, right here.  I've thought about this same issue.

Fortunately, there is a relatively small number of objects types, and you could handle destruction through a simple resource manager.  This resource manager would manage object lifetimes and forward them to the OpenGL library when a context is active.  This is a sketch of what the code might look like.

```<code>#include <GL/gl.h>
#include <mutex>
#include <vector>

class GLResourceManager {
private:
  // Types of resources
  enum class Type { Texture, Array, Buffer };
  // Record of a resource to be freed
  struct Resource {
    Type type;
    GLuint obj;
  };
  // Mutex for this object
  std::mutex m_mutex;
  // List of resources to be freed
  std::vector<Resource> m_objs;
  typedef std::lock_guard<std::mutex> lock_guard;

public:
  // Schedule a texture object for deletion
  void DeleteTexture(GLuint tex) {
    lock_guard lock(m_mutex);
    m_objs.push_back(Resource{Type::Texture, tex});
  }
  // Schedule a vertex array object for deletion
  void DeleteArray(GLuint array) {
    lock_guard lock(m_mutex);
    m_objs.push_back(Resource{Type::Array, array});
  }
  // Schedule a buffer object for deletion
  void DeleteBuffer(GLuint buffer) {
    lock_guard lock(m_mutex);
    m_objs.push_back(Resource{Type::Buffer, buffer});
  }
  // Process all pending deletions, requires an active context
  void Run() {
    lock_guard lock(m_mutex);
    for (const Resource &r : m_objs) {
      switch (r.type) {
      case Type::Texture:
        glDeleteTextures(1, &r.obj);
        break;
      case Type::Array:
        glDeleteVertexArrays(1, &r.obj);
        break;
      case Type::Buffer:
        glDeleteBuffers(1, &r.obj);
        break;
      }
    }
    m_objs.clear();
  }
};
</code>```

In the above class, you would just call DeleteTexture() in your destructor, and then call Run() once per frame, or however often you like.  This approach has a number of disadvantages.  The above class can still throw exceptions, but only when out of memory, and it's often okay to terminate the program when out of memory.

My personal preference is to avoid this extra work and just be careful about using OpenGL calls and objects that refer to OpenGL objects, and generous use of KHR_debug.  In my applications, only the rendering thread ever makes OpenGL calls, and only that thread can construct OpenGL objects.  Sometimes this means doing things like queuing state changes until the rendering thread gets around to it.

The most tempting option has been to just log an error terminate any thread that attempts to misuse the class. Unfortunately, I can't find an OS-independent way of terminating just the current thread. If I was to go this route, I'd have to look up OS-appropriate ways to terminate the current threads.

This is like saying, "I don't want to shoot myself in the foot, so I strapped a stick of dynamite to my foot, and if I ever do shoot myself in the foot, the dynamite will blow my whole leg off."  Leaking OpenGL objects is bad.  Terminating the program is bad.  Terminating an unknown thread is far worse.  Will it leave the process in a known state?  Chances are low.  Will the process be able to recover?  Probably not.  Could you end up with some kind of weird deadlock or unresponsive application?  Maybe.

Body:
This is the darker side of OpenGL, right here.  I've thought about this same issue.

Fortunately, there is a relatively small number of objects types, and you could handle destruction through a simple resource manager.  This resource manager would manage object lifetimes and forward them to the OpenGL library when a context is active.  This is a sketch of what the code might look like.

#include <GL/gl.h>
#include <mutex>
#include <vector>

class GLResourceManager {
private:
  // Types of resources
  enum class Type { Texture, Array, Buffer };
  // Record of a resource to be freed
  struct Resource {
    Type type;
    GLuint obj;
  };
  // Mutex for this object
  std::mutex m_mutex;
  // List of resources to be freed
  std::vector<Resource> m_objs;
  typedef std::lock_guard<std::mutex> lock_guard;

public:
  // Schedule a texture object for deletion
  void DeleteTexture(GLuint tex) {
    lock_guard lock(m_mutex);
    m_objs.push_back(Resource{Type::Texture, tex});
  }
  // Schedule a vertex array object for deletion
  void DeleteArray(GLuint array) {
    lock_guard lock(m_mutex);
    m_objs.push_back(Resource{Type::Array, array});
  }
  // Schedule a buffer object for deletion
  void DeleteBuffer(GLuint buffer) {
    lock_guard lock(m_mutex);
    m_objs.push_back(Resource{Type::Buffer, buffer});
  }
  // Process all pending deletions, requires an active context
  void Run() {
    lock_guard lock(m_mutex);
    for (const Resource &r : m_objs) {
      switch (r.type) {
      case Type::Texture:
        glDeleteTextures(1, &r.obj);
        break;
      case Type::Array:
        glDeleteVertexArrays(1, &r.obj);
        break;
      case Type::Buffer:
        glDeleteBuffers(1, &r.obj);
        break;
      }
    }
    m_objs.clear();
  }
};

In the above class, you would just call DeleteTexture() in your destructor, and then call Run() once per frame, or however often you like.  This approach has a number of disadvantages.  The above class can still throw exceptions, but only when out of memory, and it's often okay to terminate the program when out of memory.

My personal preference is to avoid this extra work and just be careful about using OpenGL calls and objects that refer to OpenGL objects, and generous use of KHR_debug.  In my applications, only the rendering thread ever makes OpenGL calls, and only that thread can construct OpenGL objects.  Sometimes this means doing things like queuing state changes until the rendering thread gets around to it.

The most tempting option has been to just log an error terminate any thread that attempts to misuse the class. Unfortunately, I can't find an OS-independent way of terminating just the current thread. If I was to go this route, I'd have to look up OS-appropriate ways to terminate the current threads.

This is like saying, "I don't want to shoot myself in the foot, so I strapped a stick of dynamite to my foot, and if I ever do shoot myself in the foot, the dynamite will blow my whole leg off."  Leaking OpenGL objects is bad.  Terminating the program is bad.  Terminating an unknown thread is far worse.  Will it leave the process in a known state?  Chances are low.  Will the process be able to recover?  Probably not.  Could you end up with some kind of weird deadlock or unresponsive application?  Maybe.


答:
In the past the way I've handled this is to create a queue of the OpenGL objects to be deleted. When the destructor gets called, instead of throwing it will add a new object to the queue that knows how to destroy the resource (by calling glDeleteBuffers, glDeleteLists, etc).

Then in your library, after each wglSwapBuffers (or equivalent) is completed, you're in code that controls the context, so have it check the "to be deleted" queue. If there are any items in the list, have them execute their cleanup and then clear the list. You will, of course, need a mutex or something to synchronize the accesses to that list.

It's a little bit messy, but sometimes that is the reality when working with external resources. With this strategy you won't need to change your API, and objects can be freed on any thread. I've used this to implement C# finalizers for objects wrapping OpenGL resources to prevent this exact threading issue.


问:
What is the best way to split up large methods where each subtask depends on previous tasks?
According to this question and just about every style guide I've ever read, large methods are bad. However, suppose I have a method that does the following:

Receive a JSON String from some service and store it as a Dictionary

For various parameters in the Dictionary, creates connections to other services, such as using AWS keys to open connections to AWS services

Downloads, Authenticates, or Manipulates data based on values in the Dictionary and new data received from step 2.

Creates a file on the local directory and writes various values to it, dependent on step 2 and 3.

Pushes the file from step 4 to another location

Clearly, this should not all be one large method. However, I'm not sure how to split this up into smaller methods without passing around a ton of parameters. For example, the first method is simple because I only need to tell the program one thing, and only one thing is returned. However, starting at step 3, I will either have to pass the entire Dictionary to the new method, or make the Dictionary an instance or global variable.

So, in short, here is my question. When breaking up a large method like this, what is the better alternative: should I make variables which need to be used by multiple methods instance/global variables (whichever is appropriate for this particular task), or should I pass create new methods which take many parameters?

To me, it seems like the first option is much worse, because it seems to break encapsulation: each method created in this way now has some strange dependency on a global or instance variable which is outside of its scope. However, the second method feels really messy.

答:
There's nothing wrong with passing a very large and complex parameter, as long as the structure and content of that parameter is well-defined and easy to understand. What you want to avoid is parameters that are easy to mix up, having parameters whose purpose is not clear, or depending too much on instance state rather than parameters. Even having lots of parameters is okay if you find an intuitive way of grouping them.

In fact, if I'm reading your question right, it sounds like you already know how to break up this task in a relatively simple way that only requires pure functions. Since Javascript is my main language, I'm imagining the code would look something like this:

var jsonStr = fetchJSONStringFromService();
var dict = JSON.parse(jsonStr);

var serviceConnections = createServiceConnections(dict);

var processedData = doVariousDataProcessingThings(dict);

var dataToWrite = serializeStuff(serviceConnections, processedData);
var fs = require('fs');
fs.writeFile('file/path', dataToWrite);

pushFileToOtherServer('file/path');
```

It's possible you left out some details that would make the real code significantly more complicated than this, but I'm assuming this is in the right ballpark. As you can see, it's already very easy to follow; the only thing missing is documentation of what structure the various objects being passed around are expected to have.

To answer your question directly, this sounds like a situation where you're better off aiming for stateless, pure, referentially transparent functions that only manipulate POJSOs, network connections and files. Even if some of the methods take more parameters than I've guessed above. That way each step will be straightforward to unit test (once you make all the required mocks), and very easy to change, move around or replace in the future without breaking the other steps. If any of the functions in your real code seem to take "too many" parameters, there's probably a way to break them into smaller functions or combine the parameters into meaningful objects until you end up with functions that are easy to understand.

Since your question implies this dict object is fairly large and complex, a possible improvement on top of the above would be to add a step where you break up the dict into smaller dictionaries or other data structures. In particular, I presume there's a subset of information in dict that needs to be used by createServiceConnections(), so it would be ideal to pass only that subset rather than the whole thing.

For completeness, I'm not saying that objects with instance variables are never useful. In fact, in the sample code above, it's likely that serviceConnections and fs are very stateful objects, which is fine because they represent inherently stateful things, unlike a blob of data.

Body:
There's nothing wrong with passing a very large and complex parameter, as long as the structure and content of that parameter is well-defined and easy to understand. What you want to avoid is parameters that are easy to mix up, having parameters whose purpose is not clear, or depending too much on instance state rather than parameters. Even having lots of parameters is okay if you find an intuitive way of grouping them.

In fact, if I'm reading your question right, it sounds like you already know how to break up this task in a relatively simple way that only requires pure functions. Since Javascript is my main language, I'm imagining the code would look something like this:

var jsonStr = fetchJSONStringFromService();
var dict = JSON.parse(jsonStr);

var serviceConnections = createServiceConnections(dict);

var processedData = doVariousDataProcessingThings(dict);

var dataToWrite = serializeStuff(serviceConnections, processedData);
var fs = require('fs');
fs.writeFile('file/path', dataToWrite);

pushFileToOtherServer('file/path');

It's possible you left out some details that would make the real code significantly more complicated than this, but I'm assuming this is in the right ballpark. As you can see, it's already very easy to follow; the only thing missing is documentation of what structure the various objects being passed around are expected to have.

To answer your question directly, this sounds like a situation where you're better off aiming for stateless, pure, referentially transparent functions that only manipulate POJSOs, network connections and files. Even if some of the methods take more parameters than I've guessed above. That way each step will be straightforward to unit test (once you make all the required mocks), and very easy to change, move around or replace in the future without breaking the other steps. If any of the functions in your real code seem to take "too many" parameters, there's probably a way to break them into smaller functions or combine the parameters into meaningful objects until you end up with functions that are easy to understand.

Since your question implies this dict object is fairly large and complex, a possible improvement on top of the above would be to add a step where you break up the dict into smaller dictionaries or other data structures. In particular, I presume there's a subset of information in dict that needs to be used by createServiceConnections(), so it would be ideal to pass only that subset rather than the whole thing.

For completeness, I'm not saying that objects with instance variables are never useful. In fact, in the sample code above, it's likely that serviceConnections and fs are very stateful objects, which is fine because they represent inherently stateful things, unlike a blob of data.


问:
Difference between Software Engineering and developing software in a Craftsmanship style
I have recently come across two terms: Software Engineering and Craftsmanship.
I would like to know what the difference is between Software Engineering and developing software in a Craftsmanship style. Intuitively I understand that these two approaches are not exactly the same, but I am not sure whether they are completely different.</p>

答:
They are buzzwords that mean different things to different people. I expect that they mean little in practice, and will vary greatly based on who you talk to.

That said, as a compare and contrast exercise:

Software Engineering pushes for code quality by having specifications, reusing well-known standardized components, and having processes to guide developers' work.

Software Craftsmanship pushes for code quality by trusting the pride of the programmer making the software, using more custom specialized components for the task at hand, and having close customer feedback to guide developers' work.


答:
So I understand that you want to be able to check for these potential problems with the thread not owning the context, but how will throwing an exception help? How do you plan to recover from the problem? And at what point in the program? My guess is that in general you can't fix the problem by the time this has happened, its just a major structural error in the program. So why not just make the best error report you can and then call std::abort, instead of throwing an exception?

Throwing exceptions from destructors violates the fundamental idea of C++ error handling, which is that destructors are used to clean up objects when an exception is thrown and the stack is being unwound. If one of those destructors throws an exception during stack unwinding for a different exception, so that there are two unresolved exceptions at the same scope, your program is terminated. In C++11, to make it safer, your program usually terminates whenever a destructor throws an exception, unless you take special boiler-plate steps to allow it. There are lots of other big problems with destructors that throw -- I have yet to see a situation where it's a good idea, or expedient in any way to make a throwing destructor.


问:
Should I avoid using unsigned int in C#?
I recently thought about the use of unsigned integers in C# (and I guess similar argument can be said about other "high level languages")

When In need of an integer I am normally not faced with the dilemma of the size of an integer, an example would be an age property of a Person class (but the question is not limited to properties) . With that in mind there is, as far as I can see, only one advantage of using an unsigned integer ("uint") over a signed integer ("int") - readability. If I wish to express the idea that an age can only be positive I can achieve this by setting the age type to uint.

On the other hand, calculations on unsigned integers can lead to errors of all sorts and it makes it difficult to do operations such as subtracting two ages. (I read this is one of the reasons Java omitted unsigned integers)

In the case of C# I can also think that a guard clause on the setter would be a solution that gives the best of two worlds, but, this would not be applicable when I for example, an age would be passes to some method. A workaround would be to define a class called Age and have the property age be the only thing there, but this pattern would have Me create many classes and would be a source of confusion (other developers would not know when an object is just a wrapper and when it's something more sofisticaded).

What are some general best practices regarding this issue? How should I deal with this type of scenario?

答:
Generally, you should always use the most specific data type for your data possible.

If, for example, you are using Entity Framework to pull data from a database, EF will automatically use the data type closest to the one used in the database.

There are two problems with this in C#.

First, most C# developers use only int, to represent whole numbers (unless there is a reason to use long).  This means that other developers will not think to check the data type, so they will get the overflow errors mentioned above.
The second, and more critical issue, is/was that .NET's original arithmetic operators only supported int, uint, long, ulong, float, double, and decimal*.  This is still the case today (see section 7.8.4 in C# 5.0 language spec). You can test this yourself using the following code:

```<code>byte a, b;
a = 1;
b = 2;
var c = a - b;      //In visual studio, hover over "var" and the tip will indicate the data type, or you can get the value from cName below.
string cName = c.GetType().Namespace + '.' + c.GetType().Name;
</code>```

The result of our byte-byte is an int (System.Int32).

These two issues gave rise to the "only use int for whole numbers" practice which is so common.

So to answer your question, in C# it is usually a good idea to stick to int unless:

An automated code generator used a different value (like Entity Framework).

All other developers on the project are aware that you are using the less common data types (include a comment pointing out that you used the data type and why).

The less common data types are commonly used in the project already.

The program requires the benefits of the less common data type (you have 100 million of these you need to keep in RAM, so the difference between a byte and an int or an int and a long is critical, or the arithmetic differences of unsigned already mentioned).

If you need to do math on the data, stick to the common types.

Remember, you can cast from one type to another.  This can be less efficient from a CPU stand point, so you are probably better off with one of the 7 common types, but it is an option if needed.

Enumerations (enum) is one of my personal exceptions to the above guidelines.  If I have only a few options, I will specify the enum to be a byte or a short. If I need that last bit in a flagged enum, I will specify the type to be uint so I can use hex to set the value for the flag.

If you do use a property with value restricting code, be sure to explain in the summary tag what restrictions are there and why.

*C# aliases are used instead of .NET names like System.Int32 since this is a C# question.

Note: there was a blog or article from the .NET developers (which I cannot find), which pointed out the limited number of arithmetic functions and some reasons why they did not worry about it.  As I remember, they indicated that they had no plans for adding support for the other data types.

Note: Java does not support unsigned data types and previously had no support for 8 or 16 bit whole numbers.  Since many C# developers came from a Java background or needed to work in both languages, the limitations of one language would sometimes be artificially imposed on the other.

Body:
Generally, you should always use the most specific data type for your data possible.

If, for example, you are using Entity Framework to pull data from a database, EF will automatically use the data type closest to the one used in the database.

There are two problems with this in C#.

First, most C# developers use only int, to represent whole numbers (unless there is a reason to use long).  This means that other developers will not think to check the data type, so they will get the overflow errors mentioned above.
The second, and more critical issue, is/was that .NET's original arithmetic operators only supported int, uint, long, ulong, float, double, and decimal*.  This is still the case today (see section 7.8.4 in C# 5.0 language spec). You can test this yourself using the following code:

byte a, b;
a = 1;
b = 2;
var c = a - b;      //In visual studio, hover over "var" and the tip will indicate the data type, or you can get the value from cName below.
string cName = c.GetType().Namespace + '.' + c.GetType().Name;

The result of our byte-byte is an int (System.Int32).

These two issues gave rise to the "only use int for whole numbers" practice which is so common.

So to answer your question, in C# it is usually a good idea to stick to int unless:

An automated code generator used a different value (like Entity Framework).

All other developers on the project are aware that you are using the less common data types (include a comment pointing out that you used the data type and why).

The less common data types are commonly used in the project already.

The program requires the benefits of the less common data type (you have 100 million of these you need to keep in RAM, so the difference between a byte and an int or an int and a long is critical, or the arithmetic differences of unsigned already mentioned).

If you need to do math on the data, stick to the common types.

Remember, you can cast from one type to another.  This can be less efficient from a CPU stand point, so you are probably better off with one of the 7 common types, but it is an option if needed.

Enumerations (enum) is one of my personal exceptions to the above guidelines.  If I have only a few options, I will specify the enum to be a byte or a short. If I need that last bit in a flagged enum, I will specify the type to be uint so I can use hex to set the value for the flag.

If you do use a property with value restricting code, be sure to explain in the summary tag what restrictions are there and why.

*C# aliases are used instead of .NET names like System.Int32 since this is a C# question.

Note: there was a blog or article from the .NET developers (which I cannot find), which pointed out the limited number of arithmetic functions and some reasons why they did not worry about it.  As I remember, they indicated that they had no plans for adding support for the other data types.

Note: Java does not support unsigned data types and previously had no support for 8 or 16 bit whole numbers.  Since many C# developers came from a Java background or needed to work in both languages, the limitations of one language would sometimes be artificially imposed on the other.


问:
If Class is to define attributes and methods, and Interface is to define (a set of) methods, then how to think of interface needing new attributes?
I thought a class is supposed to define, or give a blueprint, of attributes and methods for an object.  And then, an interface is to provide a set of methods, as a contract for its clients. (and so a class also gives an interface as well, because a class also define a set of methods).

But say, if we have a class called Shape.  Now we add an interface to it, called Moveable.  Now we may have to add attributes to the class, such as velocity.  But interface is only about methods, then how would we think about adding attributes to the class due to interface?

答:
An interface can be thought of as representing a behavior, or a role, that one or more objects can exhibit.

A shape might be movable, as might many other things.  With a movable interface, one can start working with things that are movable without regards to what they are.

If you realize that the internal implementation of your object needs to change, it doesn't affect the separate concept of a particular behavior (interface).  If however, you realize the behavior needs to change, likely you will need to modify all those things (objects) that have that behavior.

If velocity is just an internal implementation detail of an object, it affects no interface (behavior).  If however you realize the behavior the interface represents was incorrectly defined, and now requires velocity, you need to modify the interface and each object exhibiting the interface accordingly.

Hopefully, you can start to see that the object and the interface are two separate concepts.  They are orthogonal to each other.


答:
You don't create a class and then create an interface for it. That's getting it completely backwards. The creator of a class should never control the definition of interfaces that the class supports.

An interface is defined by someone outside the class. Someone says "I need an object here, and I don't really care at all what kind of object it is, as long as it has this set of capabilities". And that someone defines the interface.

Someone else might then come along and either they say "I want to create a brand new class that can be used when someone needs an object with that interface, and not for anything else", and create a class that very closely matches the interface and nothing else.

Alternatively they say "I have this instance here of a class that I wrote long time ago, and I would like that instance in a situation where an object with that interface is needed". And then they add everything needed to implement the interface to the class, possibly creating new methods that just call other methods that were already there but didn't match the requirements of the interface, or adding completely new methods.

Especially in the second case, the interface and its methods are not how instances of the class are usually supposed to be used; the interface implementation is specialised code to be able to plug instances into existing other code.

Title: If Class is to define attributes and methods, and Interface is to define (a set of) methods, then how to think of interface needing new attributes?

Body:
I thought a class is supposed to define, or give a blueprint, of attributes and methods for an object.  And then, an interface is to provide a set of methods, as a contract for its clients. (and so a class also gives an interface as well, because a class also define a set of methods).

But say, if we have a class called Shape.  Now we add an interface to it, called Moveable.  Now we may have to add attributes to the class, such as velocity.  But interface is only about methods, then how would we think about adding attributes to the class due to interface?


答:
My view is little different. The first step in the workflow is the key to move ahead with the remaining steps. I believe, if your first step results in any exception or an empty resultset then you would not go for the remaining steps. And attempt to have a reTry mechanism in between the steps.

You should create separate classes to perform various actions required in the entire workflow. This would keep the code clean & easier to troubleshoot also. This would promote loose coupling among the workflow steps and easier to make independent modifications in the future requirements.

Receive a JSON String from some service and store it as a Dictionary.

---- Make a class which would initiate the connection to the external service with the required set of parameters. Lets say we name the class as PreRequisiteExternalInfoClass. Fetch the result of the call appropriately. If the call results in success, then only perform the next step. You can add a reTry mechanism to the connection process for extern service, if it results in failure. And log the data into the db for analysis and troubleshooting. If your application is multi-threaded based, then replace the simple Dictionary object with ConcurrentDictionary obj (.NET framework).

For various parameters in the Dictionary, creates connections to other services, such as using AWS keys to open connections to AWS services.

----Create a new class which can take care of the connections to the AWS services. Probably think of making a singleton object for the connection object. Let's say we name the class as AWS_ServiceClass.

Downloads, Authenticates, or Manipulates data based on values in the Dictionary and new data received from step 2.

---- Add new methods into the AWS_ServiceClass to perform downloads, authentication, manipulating datasets, etc...

Creates a file on the local directory and writes various values to it, dependent on step 2 and 3.

---- Create a new static class say ManageFiles to have static methods like fileCreation, fileMove, fileCopy etc.. And pass appropriate parameter values to these methods.

Pushes the file from step 4 to another location

---- If there are large number of files for the movement to another location, then probably take the help of Robocopy utility at the OS level.

Title: What is the best way to split up large methods where each subtask depends on previous tasks?

Body:
According to this question and just about every style guide I've ever read, large methods are bad. However, suppose I have a method that does the following:

Receive a JSON String from some service and store it as a Dictionary

For various parameters in the Dictionary, creates connections to other services, such as using AWS keys to open connections to AWS services

Downloads, Authenticates, or Manipulates data based on values in the Dictionary and new data received from step 2.

Creates a file on the local directory and writes various values to it, dependent on step 2 and 3.

Pushes the file from step 4 to another location

Clearly, this should not all be one large method. However, I'm not sure how to split this up into smaller methods without passing around a ton of parameters. For example, the first method is simple because I only need to tell the program one thing, and only one thing is returned. However, starting at step 3, I will either have to pass the entire Dictionary to the new method, or make the Dictionary an instance or global variable.

So, in short, here is my question. When breaking up a large method like this, what is the better alternative: should I make variables which need to be used by multiple methods instance/global variables (whichever is appropriate for this particular task), or should I pass create new methods which take many parameters?

To me, it seems like the first option is much worse, because it seems to break encapsulation: each method created in this way now has some strange dependency on a global or instance variable which is outside of its scope. However, the second method feels really messy.


问:
Which design pattern is it if any for providing a general logger interface?
I have a library where I want to use a logger but I don't have (and cannot) create any interface for it because I'll be using it on different systems that have nothing in common (and won't have). So this won't work:

```<code>public void Foo(ILogger logger, ... other params)
{
    logger.Info(...):
}
</code>```

To overcome this problem and to make it possible to use any logging framework a particular system is using I came up with this solution:

I created a class that would provide delegates for the logging methods:

```<code>public class LoggerProxy
{
    private Action<string> _info;

    public LoggerProxy(Action<string> info)
    {
        _info = info;
    }

    public void Info(string message)
    {
        if (_info != null) _info(message);
    }
}
</code>```

And would use it like this:

```<code>static void Main()
{
    var logger = new LoggerProxy(SomeLoggingSystem.Info);
    Foo(logger, ...);
}

public void Foo(LoggerProxy logger, ... other params)
{
    logger.Info(...):
}
</code>```

I call it proxy but I'm just curious if it is really a proxy or maybe an adapter or still something else. I read the answers to How do the Proxy, Decorator, Adapter, and Bridge Patterns differ? but I cannot say that I can for sure say that any of those names is fine here.

答:
Based on your provided code LoggerProxy is just a simple class not following any famous pattern, saying that closest pattern I would compare it to is singleton (not that I recommend using it at least yet).

Since you seem to be after a well designed logging interface, I would recommend you to go through answers in this SO post,

Is it a good practice to have logger as a singleton?

Back to your LoggerProxy class with information provided it doesn't seems to be following OOP approach - just simple procedural programming I would say.


答:
IMHO

I tend to prefer not to expose inner class variables, like in this code:

person.name="sampleName";
s = person.name;
```

<p>I like to encapsulate things so consumers are not coupled to inner components of a class.</p>

<p>Than means I use getters and setters to access or change inner state, like this:</p>

<pre class="lang-java prettyprint-override"><code>person.setName("sampleName");
s = person.getName();
</code>```

That way I keep the members private or protected.

That explained, a valid interface could be:

public interface Person {
     public void setName(String value);
     public String getName();
     public void doSomething();
}
```

Which does imply some state in a class impementing it. Perhaps implementors will have a name class member of type String.

Bottom line:

Interfaces can in a way force implementors to have attributes, only not exposed in a public way but using getters and setters.

Body:
IMHO

I tend to prefer not to expose inner class variables, like in this code:

person.name="sampleName";
s = person.name;

I like to encapsulate things so consumers are not coupled to inner components of a class.

Than means I use getters and setters to access or change inner state, like this:

person.setName("sampleName");
s = person.getName();

That way I keep the members private or protected.

That explained, a valid interface could be:

public interface Person {
     public void setName(String value);
     public String getName();
     public void doSomething();
}

Which does imply some state in a class impementing it. Perhaps implementors will have a name class member of type String.

Bottom line:

Interfaces can in a way force implementors to have attributes, only not exposed in a public way but using getters and setters.


问:
Which specific practices could be called "software craftsmanship" rather than "software engineering"?
Although not a new idea there seems to have been a big increase in the interest in software craftsmanship over the last couple of years (notably the often recommended book Clean Code's full title is Clean Code: A Handbook of Agile Software Craftsmanship).

Personally I see software craftsmanship as good software engineering with an added interest in ensuring that the end result is a joy to work with (both as an end user and as someone maintaining that software) - and also that its focus is more at the coding level of things than the higher level process things.

To draw an analogy - there were lots of buildings constructed in the 50s and 60s in a very modern style which took very little account of the people who would be living in them or how those buildings would age over time. Many of those buildings rapidly developed into slums or have been demolished long before their expected lifespans. I'm sure most developers with a few years under their belts will have experienced similar codebases.

What are the specific things that a software craftsman might do that a software engineer (possibly a bad one) might not?

答:
Uncle Bob somehow hinted that programming is a very young discipline that doesn't yet have a stable body of laws or rules recognized by goverments (or was it Frederick Brooks?). I'm not making a verbatin citation here.

You cannot revoke anyone the permit to program due to malpractice. Programming lacks a body of laws and rules than are legally enforced by legislation that conforms a "profession". A doctor kills a patient due to incompetence and he risks his physician title or permission being taken from him.

A programmer makes a buggy program or makes a project fail due to incompetence and he is free to continue programming.

I think that's pretty much what makes programming a craft. A clay-pot maker don't make two identical pots. Nor have you heard of a clay-pot maker forced to recall defective pots. Programming is still a very manual, personal kind of work. Sometimes you can even tell who wrote a piece of code judging by the style of it.


问:
Is PHP7 a static or dynamic typed language?
In the past few years, we've been using dynamically typed versions of PHP. However, in PHP7 we have an option to enable 'strict types':

PHP RFC: Return Type Declarations

PHP RFC: Scalar Type Declarations

(Note: Scalar Type Declarations repeatedly uses the phrase "weak type checking" or "strictly typed" versus static/dynamic.)

Is it right to say that PHP7 is a statically typed language? If so or not, why?

答:
As mentioned, "strong" and "weak" type systems are ill-defined:

'Languages are often colloquially referred to as "strongly typed" or
  "weakly typed". In fact, there is no universally accepted definition
  of what these terms mean. In general, there are more precise terms to
  represent the differences between type systems that lead people to
  call them "strong" or "weak"'.

Static types can be verified at compile time. The compiler has enough information to verify static types before a program runs. (If a typed variable is used where the type is not expected, it's a compiler error.) Dynamic types cannot be perfectly determined at compile time. This doesn't mean variables in dynamic languages don't have types. It just means there's no way to be 100% certain of a variable's type until run-time.

According to the PHP RFCs for return type declaration and scalar type declaration, non-typed declarations and evaluation modes are still allowed. This means not all of PHP is statically typed. As such, it doesn't make sense to call PHP a statically typed language. Instead, it's a dynamically typed language with a couple static type features.

The fact that the scalar type declaration RFC actually uses the definitions "strict" and "weak" type checking is telling. The PHP folks pride themselves on not being language nerds. This is neither good nor bad. It just means the language designers are focusing on different things than, say, Haskell designers.


问:
Implements > extends, but what about variables?
It's preferable to write programs that depend on interfaces rather than on superclasses, but what if you want a class to have certain variables? Sometimes you want a class to implement a certain variable. (For example, imagine you have a datasource interface, and want all classes to implement a "String user").

In this case, I can see making an abstract class "datasource", which other classes could then extend. But this means they can't extend another class anymore, due to no multiple inheritance in Java.

So, to conclude, if I would have the above scenario, should I rethink my design, or is there a pattern I don't know about that I could follow to achieve the interface-with-variable design?

答:
You can add the following to the interface:

```<code>public void setUser(String s);
public String getUser();
</code>```

That way implementors are kind of forced to have a username variable in their state. Although implementors may name it whatever they like.

That way you continue simulating multiple-inheritance through interfaces.

Any class extending another one that implements the interface can access the variable with super.getUser(); or you can even make the state variable protected, but that's an implementation detail.

Body:
You can add the following to the interface:

public void setUser(String s);
public String getUser();

That way implementors are kind of forced to have a username variable in their state. Although implementors may name it whatever they like.

That way you continue simulating multiple-inheritance through interfaces.

Any class extending another one that implements the interface can access the variable with super.getUser(); or you can even make the state variable protected, but that's an implementation detail.


问:
Java Heap Allocation Faster than C++
I already posted this question on SO and it did ok. It was unfortunately closed though(only needs one vote to reopen) but someone suggested I post it on here as it is a better fit so the following is literally a copy paste of the question

I was reading the comments on this answer and I saw this quote.

Object instantiation and object-oriented features are blazing fast to use (faster than C++ in many cases) because they're designed in from the beginning. and Collections are fast. Standard Java beats standard C/C++ in this area, even for most optimized C code.

One user (with really high rep I might add) boldly defended this claim, stating that

heap allocation in java is better than C++'s

and added this statement defending the collections in java

And Java collections are fast compared to C++ collections due largely to the different memory subsystem.

So my question is can any of this really be true, and if so why is java's heap allocation so much faster.

答:
It all depends who measures the speed, what implementation's speed they measure, and what they want to prove. And what they compare.

If you just look at allocating / deallocating, in C++ you might have 1,000,000 calls to malloc, and 1,000,000 calls to free (). In Java, you would have 1,000,000 calls to new () and a garbage collector running in a loop finding 1,000,000 objects that it can free. The loop can be faster than the free () call.

On the other hand, malloc / free have improved other time, and typically malloc / free just sets one bit in a separate data structure, and is optimised for malloc / free happening in the same thread, so in a multithreaded environment no shared memory variables are used in many cases (and locking or shared memory variables are very expensive).

On the third hand, there are things like reference counting which you might need without garbage collection, and that doesn't come for free.

Title: Java Heap Allocation Faster than C++


答:
You are concerned with how to structure a single function, therefore whatever solution you come up with, it should not affect the structure of the class.

What this means is that you should definitely not introduce instance variables; passing all necessary parameters to methods is the way to go.

As for global variables, you should not have even considered them, nor brought them up in this question.  There is no application of global variables which does not result in evil, and there is no evil which does not get worsened by the introduction of global variables.  And as a matter of fact, even instance variables are nothing but global variables within the scope of a class, (the class being thought of as the globe in this case,) so it is best to never have any instance variables that could have been avoided.

I do not see why you regard passing parameters as an onerous task.  You speak of having to "pass the entire Dictionary to the new method"; well, it is not like you are going to be transferring it in truckloads; you just declare the method to accept the dictionary as a parameter, and then later when you invoke that method, you make sure to pass the dictionary as a parameter.  It is not a big deal, really.

All that having been said, let me also add that the maxim which proclaims that functions should be as small as possible should be taken with a grain of salt.  The ultimate goal is to reduce the complexity of the code, and all these lofty principles, guidelines, and words of wisdom have nothing but one end goal: to help reduce complexity.  So, keep in mind that it is entirely possible that a single long method consisting of a few sequentially executed chunks sharing some local state may represent a smaller amount of complexity than a small method which sequentially invokes a multitude of other methods which serve no purpose other than to break the code into smaller chunks, simply because the work done is the same, the code which does it is the same, and we now have the additional burden of packaging and passing parameters around, un-packaging results, etc. And of course, if this mechanism requires the introduction of additional entities, like global variables, instance variables, or new classes to hold temporary results, then it is by definition a solution of greater complexity than the single long method approach.


问:
code review with git-flow and github
With regular git and github I can do a code review by simply creating a pull request of the feature branch I'm working on to the master branch. How would I do code reviews with git-flow? With workflow like "git flow feature finish` I'm confused as to where the code review actually happens and how git-flow or git can facilitate that review.</p>

答:
Here is another suggestion.

Do the regular git flow process to create a feature, but do not finish or merge it.

Create a pull request, but do not merge it. Wait for the approver to leave a comment. The comment is the mark of approval.

Do the git flow finish. (Either the approver or the developer can do this, depending on what the team agreed upon.) The pull request will be marked as merged on github. You still need to delete the branch on origin.

Title: code review with git-flow and github


答:
Your class already does too much but I will not address that here.

Regarding the specific question:

should I make variables which need to be used by multiple methods
  instance/global variables (whichever is appropriate for this
  particular task), or should I pass create new methods which take many
  parameters?

Having too many parameters passed between methods is an indicator of low cohesiveness of the class. In the case of a static methods belonging to an utility class, that maybe OK but not otherwise.

If the method really belongs to that class then upon splitting it into separate methods, resulting methods should access the state of the class instead of passing lots of parameters between them. Keep the number of parameters to one or two at most.

The ideal number of arguments for a function is zero (niladic). Next
  comes one (monadic), followed closely by two (dyadic). Three arguments
  (triadic) should be avoided where possible. More than three (polyadic)
  requires very special justification—and then shouldn’t be used anyway.

Clean Code, A Handbook of Agile Software Craftsmanship
  -- Robert C. Martin


问:
Linking stylesheets and scripts when using server side includes
I am working on a site where I want to have a header and footer on each page, so I thought about using server side includes for this. I have not used them before so I am a little bit unsure about best practices when it comes to styling my site. I am currently including the styles and scripts in the file for the header, and when it is included the rest of the site is styled, and it seems to be working, but I was wondering if there are best practices I should be aware of when it comes to this.</p>

答:
If the webiste is small as you clained in the comments just create stylesheet with all general styles and use some more specific styles to override the defaults when necessary.

Something like:

file1

```<code><section class="home">
<h1>Home</h1>
</section>
</code>```

file2

```<code><section class="breakingNews">
<h1>Very important title</h1>
</section>
</code>```

styles

```<code>h1 {
    font-weight: bold;
}

.breakingNews h1 {
    color: red;
}
</code>```

I did find the trello css guide quite useful but maybe it's a bit of an overkill if the project is so small. Worthy read anyway:
https://gist.github.com/bobbygrace/9e961e8982f42eb91b80

As for js files I'll still keep to one file and detecting content, again, if you are building something very simple.

Something like:

```<code>//code you'll want to run always
$(function(){
    alert("welcome to my awesome site");
});

//code only if some elements are present on the site
$(function(){
    if($('.breakingNews').size()){
        alert("OMG those news are so breaking");
    }
});
</code>```

This advice may not be a good idea on big websites

Body:
If the webiste is small as you clained in the comments just create stylesheet with all general styles and use some more specific styles to override the defaults when necessary.

Something like:

file1

<section class="home">
<h1>Home</h1>
</section>

file2

<section class="breakingNews">
<h1>Very important title</h1>
</section>

styles

h1 {
    font-weight: bold;
}

.breakingNews h1 {
    color: red;
}

I did find the trello css guide quite useful but maybe it's a bit of an overkill if the project is so small. Worthy read anyway:
https://gist.github.com/bobbygrace/9e961e8982f42eb91b80

As for js files I'll still keep to one file and detecting content, again, if you are building something very simple.

Something like:

//code you'll want to run always
$(function(){
    alert("welcome to my awesome site");
});

//code only if some elements are present on the site
$(function(){
    if($('.breakingNews').size()){
        alert("OMG those news are so breaking");
    }
});

This advice may not be a good idea on big websites


问:
Programming to Data Oriented Interfaces
There is a portion of our codebase written in the following style:

```<code>// IScheduledTask.cs
public interface IScheduledTask
{
    string TaskName { get; set; }
    int TaskPriority { get; set; }
    List<IScheduledTask> Subtasks { get; set; }
    // ... several more properties in this vein
}

// ScheduledTaskImpl.cs
public class ScheduledTaskImpl : IScheduledTask
{
    public string TaskName { get; set; }
    public int TaskPriority { get; set; }
    public List<IScheduledTask> Subtasks { get; set; }
    // ... several more properties in this vein,
    // perhaps a constructor or two for convenience.
}
</code>```

That is, there are a large number of interfaces specifying just a set of properties with no behavior each with a sole corresponding implementation that implements these with auto-properties. The code is written by someone fairly senior (much more so than myself) and is apart from this use of interfaces reasonable procedural code. I was wondering if anyone else had encountered/used this style and if it has any advantages over just using concrete DTOs everywhere without the interfaces.

答:
Here's my two cents:

We are not sure a DTO will never ever have at least a little bit of behavior. So for me there are objects which may or may not have behavior in the future.

One possible cause of having so many sole-implementation classes is a lack of design, for example failing to see that ScheduledTask, ScheduledJob, ScheduledEvent, ScheduledInspection, etc, should be only one segregated Schedulable interface making any implementor schedulable.

Creating the interfaces first is a very good practice, it gives you insight of what you need. Many interfaces begin by having no implementation at all. Then someone writes one implementation and they have that one. The state of having a sole implementation is temporary if you avoided what I mention in the second point. How do you know beforehand that some interface will never ever have a second of third implementation?

The name we choose for a well thought interface has a tendency to not change in the future, so dependencies to that interface will not be affected. On the other hand a concrete class is prone to be renamed when something important in the way it is implemented changes, for example a concrete class named TaxSheet could change to SessionAwareTaxSheet because a significant overhaul was made but the interface ITaxSheet will probably not be renamed so easily.

Bottom-line:

Good design practices apply also to DTOs.

DTOs can be added a little behavior down the road.

Every interface begins by having only one implementation.

In the other hand if you have too many one-interface-one-class combos, there could be a lack of design that should be pointed out. Your preocupation may be justified.

Title: Programming to Data Oriented Interfaces


问:
Hypothetical extension to C# property initializer syntax
In C#, when you call a constructor, you can add one or more property initializers in curly braces:

```<code>var foo = new Bar() { Armpit = new Flapdoodle() { Limpet = 2 } };
</code>```

What if that feature were generalized to "set properties on a return value":

```<code>var baz = foo.Armpit { Limpet = 4 };
</code>```

This would be handy in cases like this:

```<code>var things = coll
    .Select(x => {
        var a = CreateA(x);
        a.Parent = this;
        return a;
    });
</code>```

That's a common pattern in projecting collections via LINQ, but you see it elsewhere too: You have to declare a local variable and add some noise just to set one property on a return value before you pass it along to something else.

You write

```<code>f2(f1());
</code>```

...but then whoops, something needs to change, so it becomes three lines:

```<code>A a = f1();
a.B = "c";
f2(a);
</code>```

It seems like it might be nicer to be able to express the same code as follows:

```<code>var things = coll.Select(x => CreateA(x) { Parent = this } );

f2(f1() { B = "c" });
</code>```

My question is this: Is this merely not useful enough to bother with, or is it actively a bad idea for some reason that's obvious to the C# team but not to me?

答:
Is this merely not useful enough to bother with, or is it actively a bad idea for some reason that's obvious to the C# team but not to me?

I can't think of any actively bad reason except perhaps the lack of atomicity (which also applies to the multi-line versions) but I think that it is not particularly useful. I've not had to do a lot of this, but then again, I dislike mutable types. Mostly though, I find this syntax to be mostly shuffling the deck chairs.

```<code>var a = f1();
a.B = "c";
f2(a);
</code>```

Is about as readable as

```<code>f2(f1() { B = "c" });
</code>```

to me. If anything, spreading the operations over multiple lines helps with the readability.

Sure, the select case is more compelling, but a select doing mutation strikes me as a bit smelly.

Body:
Is this merely not useful enough to bother with, or is it actively a bad idea for some reason that's obvious to the C# team but not to me?

I can't think of any actively bad reason except perhaps the lack of atomicity (which also applies to the multi-line versions) but I think that it is not particularly useful. I've not had to do a lot of this, but then again, I dislike mutable types. Mostly though, I find this syntax to be mostly shuffling the deck chairs.

var a = f1();
a.B = "c";
f2(a);

Is about as readable as

f2(f1() { B = "c" });

to me. If anything, spreading the operations over multiple lines helps with the readability.

Sure, the select case is more compelling, but a select doing mutation strikes me as a bit smelly.


答:
You've discovered a real problem when you want your code to consist of expressions rather than statements: you can't easily apply side effects to a value. However, introducing extra syntax is both inelegant and unncessary. Instead, I'd rather define a static helper function that can be used like

```<code>f2(With(f1(), a => { a.B = "c"; }));
var things = coll.Select(x => With(CreateA(x), a => { a.Parent = this; }));
</code>```

where With would be implemented as With = (x, f) => { f(x); return x; }, i.e. the function is only evaluated for its side effects. This pattern allows side effects to be embedded into an expression.

Title: Hypothetical extension to C# property initializer syntax

Body:
In C#, when you call a constructor, you can add one or more property initializers in curly braces:

```<code>var foo = new Bar() { Armpit = new Flapdoodle() { Limpet = 2 } };
</code>```

What if that feature were generalized to "set properties on a return value":

```<code>var baz = foo.Armpit { Limpet = 4 };
</code>```

This would be handy in cases like this:

```<code>var things = coll
    .Select(x => {
        var a = CreateA(x);
        a.Parent = this;
        return a;
    });
</code>```

That's a common pattern in projecting collections via LINQ, but you see it elsewhere too: You have to declare a local variable and add some noise just to set one property on a return value before you pass it along to something else.

You write

```<code>f2(f1());
</code>```

...but then whoops, something needs to change, so it becomes three lines:

```<code>A a = f1();
a.B = "c";
f2(a);
</code>```

It seems like it might be nicer to be able to express the same code as follows:

```<code>var things = coll.Select(x => CreateA(x) { Parent = this } );

f2(f1() { B = "c" });
</code>```

My question is this: Is this merely not useful enough to bother with, or is it actively a bad idea for some reason that's obvious to the C# team but not to me?

Body:
You've discovered a real problem when you want your code to consist of expressions rather than statements: you can't easily apply side effects to a value. However, introducing extra syntax is both inelegant and unncessary. Instead, I'd rather define a static helper function that can be used like

f2(With(f1(), a => { a.B = "c"; }));
var things = coll.Select(x => With(CreateA(x), a => { a.Parent = this; }));

where With would be implemented as With = (x, f) => { f(x); return x; }, i.e. the function is only evaluated for its side effects. This pattern allows side effects to be embedded into an expression.


答: Probably its good to use frames in html.While creating your html page.what should be done is just split the page into 3 frames.one frame for header and the last one for your footer.It is possible to split according to your choice i.e,you can specify the split percentage.

Title: Linking stylesheets and scripts when using server side includes

Body: I am working on a site where I want to have a header and footer on each page, so I thought about using server side includes for this. I have not used them before so I am a little bit unsure about best practices when it comes to styling my site. I am currently including the styles and scripts in the file for the header, and when it is included the rest of the site is styled, and it seems to be working, but I was wondering if there are best practices I should be aware of when it comes to this.</p>


问:
How to create "constructors" for structures in C

The problem

I have this structure that I want to create a "constructor" for it.

```<code>struct example {
    int x, y, z; /* various members */
    struct another *another; /* pointer to another structure */
}
</code>```

The two different ways I know of

Using functions that create and delete structures on heap

I can create structures by making functions that allocates them on the heap like this:

```<code>/* create example */
struct example *example_new(int x, int y, int z) {
    struct example *p = malloc(sizeof *p);
    p->x = x;
    p->y = y;
    p->z = z;
    p->another = another_new();
}

/* delete example */
void example_new(struct example *p) {
    another_del(p->another);
    free(p);
}
</code>```

Using functions that initializes and frees memory for structure through pointer

Or I could initalize the structure by passing pointer to the function and have the user responsible for allocating and deallocating memory for it.

```<code>/* initalize example */
void example_init(struct example *p, int x, int y, int z) {
    assert(p);
    p->x = x;
    p->y = y;
    p->z = z;
    p->another = another_new();
}

/* free memory allocated for example */
void example_free(struct example *p) {
    another_del(p->another);
}
</code>```

My thoughts

I usually prefer first approach when creating recursive structures (like Trees and Linked Lists) but use the second approach in all other cases.

I tried to use the second approach for a recursive structure and it turned out to be quite messy.

The question

How do you choose between these two ways? Is there a third way you would use to solve this problem?

答:
The primary advantage of the first option is that it encapsulates the memory allocation into your "new" and "delete".  You only have to remember to create and destroy your structures.  With the second option, you have to remember separately to create/destroy and allocate/free your objects.

The advantage of the second option is that it allows you to create objects on the stack:

```<code>struct example;
example_init(&example, 1,2,3);
</code>```

This can have big performance benefits over allocating on the heap.  However, you have to be very careful to call example_free before your object goes out of scope.

So option 1 should generally be less error prone, and should be preferred unless your requirements mean you need the performance benefits of putting these objects on the stack.

Body:
The primary advantage of the first option is that it encapsulates the memory allocation into your "new" and "delete".  You only have to remember to create and destroy your structures.  With the second option, you have to remember separately to create/destroy and allocate/free your objects.

The advantage of the second option is that it allows you to create objects on the stack:

struct example;
example_init(&example, 1,2,3);

This can have big performance benefits over allocating on the heap.  However, you have to be very careful to call example_free before your object goes out of scope.

So option 1 should generally be less error prone, and should be preferred unless your requirements mean you need the performance benefits of putting these objects on the stack.