答:
Ok - you cannot make an ordered small table - the order you insert records is not guaranteed to be the order you get them out when doing a SELECT - assuming anything else and you're going to be asking for bugs in the future even if it works now.

One table per client is fine but probably unnecessary - it's one of these things that depends on your specific situation.

However, adding an ordering clause to a query when appropriate will not be expensive - the things you need to make sure you're doing well:

Normalisation
Query Structure / only retrieving the correct data

The key issue with most new database developers are that they have enormous god tables with hundreds of columns and they don't actually query for what they want - aim to retrieve the least amount of data necessary and then the ordering becomes trivial.

Title: Violating SQL principles

Body:
I have  to write a decent size database, 1GB more or less.

I have only taken an introductory semester regarding SQL databases. During the course we learned that the relational model under SQL has no implied order and that therefore when querying we should always have a variable that sets the correspondant order in the table.

However, when doing practical work I find 'convenient' to make already ordered small, infinite number of tables.

For example, lets say that you have 5 clients and that their info will never join their data together. Is it admissible to have a potentially infinite number of tables with a table per client?

For example, I append new rows already ordered to the database. The database is already ordered. Is it admissible to make an unordered query and just assume that is implicitly ordered?

All this violates the principles that I know. My boss, who does not know about databases says that if it works it works and that speed is important. What shall answer to him?


问:
Specifics of Switch and If statements
Why do we need the  switch statement if there is the if statement? Why can't we use several ifs like

if(a==1) do this1;

  if(a==2) do this2;

  ...

instead of

switch (a) {

  case(1): {do this1;break;}

  case(2): {do this2;break;}

  ...

  }

My teacher said that the answer is built on how assembler works, but I've never worked with it.

Explain, please, why we have both switch and if?

答:
Conceptually we all think of a switch statement as a series of if statements. Conceptually, that is the correct way of thinking about the switch statement.

However, the compiler has more information to work with when it is compiling a switch statement. When compiling an if statement, each if statement must be treated independently. The compiler has no way of determining that a series of if statements are related.

That of course is not true with a switch statement. The compiler perfectly understands that each case in the switch is related to each other. The compiler can now generate code that is faster than a series of if statements.

For example, it is not uncommon for a compiler to generate a binary search tree for sufficiently large set of cases. In other cases, the compiler may generate a jump table. Compilers will also simplify ranges so that it can more easily generate a jump table.

The case you point out here could cause a jump table to be generated rather than any compares at all. The compiler would generate a simple range check to make sure the jumps work, then jump through an table to precisely the right instruction. No additional comparisons and each case takes the same amount of time to execute.

So, the switch statement gives the compiler more information to work with which can result in better optimized (read faster) code.

ContentLicense: CC BY-SA 3.0

Title: Specifics of Switch and If statements


问:
Using partially implemented interfaces
Consider the following hierarchy in C++ notation:

```<code>class A
    {
    public:
        virtual void doStuff()=0;
        virtual void doOtherStuff()=0;
    };

class B:public A
    {
    public:
        void doStuff();
        void doOtherStuff();
    };

class C:public A
    {
    public:
        void doStuff();
        void doOtherStuff();
    };
</code>```

Now, assume that the code for doStuff is identical in B and C. What is the best practice of

implementing doStuff in a class D:public A and let B and C derive from A

Let the real task be performed in a function that is called from doStuff in both B and C

Somehow the latter seems more clean, is it? It should be noted that there are other methods in B and C with common implementations as well, and that in the underlaying model, the concept of D does not exist.

答:
I would create a class E to hold the shared implementation of doStuff

```<code>class E : class A
{
override doStuff() {}
}
</code>```

and have classes B and C inherit from E. This allows you to maintain the inheritance if B and C still need to be types derived from A, but allows A and other derivations to not share the same implementation and B and C

Title: Using partially implemented interfaces

Body:
I would create a class E to hold the shared implementation of doStuff

class E : class A
{
override doStuff() {}
}

and have classes B and C inherit from E. This allows you to maintain the inheritance if B and C still need to be types derived from A, but allows A and other derivations to not share the same implementation and B and C


问:
Violating SQL principles
I have  to write a decent size database, 1GB more or less.

I have only taken an introductory semester regarding SQL databases. During the course we learned that the relational model under SQL has no implied order and that therefore when querying we should always have a variable that sets the correspondant order in the table.

However, when doing practical work I find 'convenient' to make already ordered small, infinite number of tables.

For example, lets say that you have 5 clients and that their info will never join their data together. Is it admissible to have a potentially infinite number of tables with a table per client?

For example, I append new rows already ordered to the database. The database is already ordered. Is it admissible to make an unordered query and just assume that is implicitly ordered?

All this violates the principles that I know. My boss, who does not know about databases says that if it works it works and that speed is important. What shall answer to him?

答:
5 clients and that their info will never join their data together. Is it admissible to have a potentially infinite number of tables with a table per client?

I'm not sure where you're going with this. Do you have multiple copies of your Client table? do you have multiple copies of the tables that are joined with Client? Either way, both of these designs will cause problems in the future, mostly with long-term maintenance issues.

Usually what happens is that the data model changes, and then you have to propagate the change to all copied tables and hope that nothing breaks. For example, removing/modifying columns might not break referential integrity for most clients, but it might for some, so your test environment must include samples of all copied data.

Another issue is that if you're doing reporting, you need to join all the copied tables if you want your report to cover more than one subset of the copied structures. This can make for very long and unwieldy queries, and if you forget one client's table then your results will be wrong.

And then you have the problem of having queries and code bound to the names of copied tables even though they may all be doing the same thing.

There are some cases where doing this is useful and possibly necessary, but I find it's something that needs a bit of thought and a good reason to do it.

Is it admissible to make an unordered query and just assume that is implicitly ordered?

If the ordering of the result set doesn't matter, or if you plan to re-order it in your application later (maybe after some very specific in-application filtering/procesing), then I don't see why this is a problem. If you want to ensure that the result set is ordered correctly, add an ORDER BY clause to your query.

Of course, if you find that some tables are frequently hit with the same query and ordering conditions, it might make sense to order the index that your query uses so that it's ordered it the most commonly used way. This could give you some performance improvements. Even if you do this, I'd say it's still a good idea to include the ORDER BY. Mostly so that someone who's unfamiliar with the code knows exactly what the order is and doesn't have to go digging through database definitions to figure it out. How you do this may vary depending on which database product you're using (if it's even supported at all, but I think most major database engines would support this).

Title: Violating SQL principles


问:
How to trace logical errors in algorithms
I am beginner in algorithms. Last year I participated in Google Code Jam. One of the major issues I faced during the competition was my code was working fine on my test cases, but when I submitted on a large number of test cases, I failed to pass them causing some logical error.

So, my question is basically how can I trace logical errors in my code in such situation where it fails to match some test cases?

答:
There's no easy way around it.  You have to look at the test case inputs one by one for situations you didn't think about, work out manually the correct answer, and see if your algorithm agrees.

For example, one thing that bit me on a recent Google Code Jam question I tried for practice was not allocating a big enough numeric type to hold the result.  I was using a 32-bit int and needed at least 64 bits.  Looking at the difference between the long and short test inputs, I noticed how much larger the input values were, like they were purposely trying to see if I would overflow.

That's part of the contest.  They want to see how well you anticipate the edge cases.  Otherwise, they would tell you which test case specifically failed.

Another thing that can help is writing your own test cases, so you can see for yourself which one failed before you submit.  Try really large numbers, really small ones, different combinations of positive and negative, etc.  Try to push the boundaries of the problem to make sure you cover all the angles.  The trick is to make your own test cases simple enough to manually calculate while also complex enough to be a thorough test.  That just comes with practice.


问:
Where does Windows Workflow Foundation fit into the messaging oriented middleware architecture?
I've been trying to find information online about where WWF 4.5 fits with in an architecture based around an enterprise message queue using central broker(s) (RabbitMQ in particular).

It seems like responsibilities overlap a bit since WWF offers the ability to pause-and-resume (persist/restore) workflow instances. I'm wondering if I'm erroneously equating this pause-and-resume WWF functionality to the general message queuing concept.

Having looked at MassTransit, in particular a code listing of a sample Saga showing parallel code "activities" that then "combine" when completed... it seems like WWF excluding the pause-resume functionality in this context, is better compared against MassTransit.. is this an accurate assessment?

答:
WF (Microsoft doesn't call it WWF to avoid battles with the wrestling organization and the conservatory) offers both pause and resume, and it also offers orchestration of activities.

Where an ESB can distribute messages and a workflow does not, a workflow orders the sequence to occur.

webhooks is new to me but it still looks like it's about distributing messages. WF would be used to create a context of Activity started -> Call Method#1 (method puts specific message on queue), Call Method#2 (method does something), Suspend until ..., Call Method#3 (method reads from queue), etc. until your context is complete.

Using WF to replace writing functions is just painful as MetaFight so eloquently stated. Its key purpose to is to provide a context the execution of > 1 operation. It can arrange operations in a GUI which can be a good visualization tool of the process, and provides the suspend / awaken / compensation activities for long running and fault-tolerant processes.

For example, and I'm picking a short process here rather than a long one:

Context is, user logs in

Write audit log to database via AuditOperation();

Put message on queue to notify friends user logged in

Redirect user to their profile page

The execution of each of these operations has nothing to do with the other, but the sum of their parts is completing the scenario. For more information I would check out Data-Context-Interaction (http://en.wikipedia.org/wiki/Data,_context_and_interaction)


答:
I've had to use WF before in an integration scenario based on a Pub-Sub messaging system... and we found that using WF was a pain in the ass.

Firstly, it's awkward to code with.  At first you'll be tempted to code all your logic with activities in the Designer, but this is a very bad thing.  Even simple things like object instantiation turns into either a mess of value-setting activities, or is hard to follow because it's all hidden within variable declaration default values.

Secondly, it's god awful to debug with.  Even if you're lucky enough for your workstation to be one of the selected few where the debugger actually chooses to wake up, listen, and do work, then get ready for a horrible debugging experience anyway.  The debugger detaches from processes seemingly randomly and doesn't actually provide much valuable information any way.  I would have expected for the debugger to show me exceptions when they're thrown, but no such luck.  Get ready to sprinkle your catch blocks with break-points.

If multiple developers are going to be working on the same workflows then you'll have a hard time merging changes.  This is because workflows are XML.  This wouldn't be too bad if it weren't also for the fact the the WF Designer's visual state is actually stored within the same XML.  Granted, they finally moved the visual state info to one contiguous block of text (instead of decorating 60% of all XML elements), but it's still a pain in the ass.  It means everytime you expand or collapse an activity your file changes.  Which means you'll be committing a lot of useless changes... and then you'll be stuck navigating through them later.

The only thing I can see WF being good for is long-running workflows.

NOT as a technology for building a message bus.

Title: Where does Windows Workflow Foundation fit into the messaging oriented middleware architecture?

Body:
I've been trying to find information online about where WWF 4.5 fits with in an architecture based around an enterprise message queue using central broker(s) (RabbitMQ in particular).

It seems like responsibilities overlap a bit since WWF offers the ability to pause-and-resume (persist/restore) workflow instances. I'm wondering if I'm erroneously equating this pause-and-resume WWF functionality to the general message queuing concept.

Having looked at MassTransit, in particular a code listing of a sample Saga showing parallel code "activities" that then "combine" when completed... it seems like WWF excluding the pause-resume functionality in this context, is better compared against MassTransit.. is this an accurate assessment?


问:
Is Convention Over Configuration "Knowledge in the World" or "Knowledge In Your Head"?
In Don Norman's seminal work "The Design of Everyday Things", the author coined the phrases and explains the difference between "Knowledge in the World" and "Knowledge In Your Head"; an example of this is a multi-switch light panel that can either incorporate "Knowledge in the World"  by being a model/map of the room, with the switches in the corresponding location, or "Knowledge In Your Head" (which is how they are almost always designed/implemented) when you have to memorize which switch toggles which light.

You could think of "Knowledge in the World" as something you can deduce by using observation and logic, and "Knowledge in your Head" as something that has to be memorized.

In the world of DI, and "Auto-Registration," which relies on the "Convention Over Configuration" pattern, would using this process be a case of the programmer using "Knowledge in the World" (the functionality is expected, as the framework provides it) or is it "Knowledge In Your Head" (the programmer has to be aware of and learn the convention).

I am taking the wishy-washy/middle-of-the-road view that Convention Over Configuration is a midway world twixt the two.

Am I wrong?

答:
Convention Over Configuration is pretty much by definition "Knowledge in the World" - the convention is always meant to be so "obvious" that you don't have to learn much: things like having URLs automatically mapped to controller classes and DB tables to model classes. The same for auto-registration DI - you have objects automatically instantiated and injected into others based on naming conventions. It "just works".

Of course, the problem is that in practice it's not always (and almost never in sufficiently large systems) that simple. You have special requirements and edge cases not covered by the conventions, and it stops working. The problem then is that all this "magic" you're supposed to depend on is opaque to you and relies on mechanisms that are quite complex by themselves. And you have to invest a lot of time to learn how it works so you can make it work the way you need and fix it when it breaks. And then it has become "Knowledge in your head".

But in a well-designed and correctly-used system, this should be rare enough that it's still worthwhile.


答:
How do you acquire that knowledge?

"Knowledge in the world": mostly by experience and conventions. In your switch example, you know already what a plan is and how to map it to the actual room.

"Knowledge in your head": mostly by experimentation - in the switch example, you try them.

From that perspective, convention over configuration is definitely "knowledge in the world".

(Note that while most house switches end up 'knowledge in your head', they still respect some 'knowledge in the world' conventions such as being - generally - in the same room as the lights and - if your electrician is any good - roughly ordered like the lights in a multi switch configuration)

Title: Is Convention Over Configuration "Knowledge in the World" or "Knowledge In Your Head"?

Body:
In Don Norman's seminal work "The Design of Everyday Things", the author coined the phrases and explains the difference between "Knowledge in the World" and "Knowledge In Your Head"; an example of this is a multi-switch light panel that can either incorporate "Knowledge in the World"  by being a model/map of the room, with the switches in the corresponding location, or "Knowledge In Your Head" (which is how they are almost always designed/implemented) when you have to memorize which switch toggles which light.

You could think of "Knowledge in the World" as something you can deduce by using observation and logic, and "Knowledge in your Head" as something that has to be memorized.

In the world of DI, and "Auto-Registration," which relies on the "Convention Over Configuration" pattern, would using this process be a case of the programmer using "Knowledge in the World" (the functionality is expected, as the framework provides it) or is it "Knowledge In Your Head" (the programmer has to be aware of and learn the convention).

I am taking the wishy-washy/middle-of-the-road view that Convention Over Configuration is a midway world twixt the two.

Am I wrong?


答:
Logical Issues can be solved only logically, you test cases may pass since they are specific data set designed and written by you

The best way to make sure your code does not fail in the logical sense is to take paper and pencil, and write down each logical step ( with data set in mind) as you go through the loops and the logical conditions
 for example as you come across a loop think if the input is a 0 how will it react, if the input is a 100 how will the loop react, writing down helps you get clarity and actually cuts down the time you would spent in fixing bugs.

And as most coders will testify this system get embedded in you head as you code and more and more , then you don't need to write stuff down, you will automatically think about logical consequence of your code when you write code.

Title: How to trace logical errors in algorithms

Body:
I am beginner in algorithms. Last year I participated in Google Code Jam. One of the major issues I faced during the competition was my code was working fine on my test cases, but when I submitted on a large number of test cases, I failed to pass them causing some logical error.

So, my question is basically how can I trace logical errors in my code in such situation where it fails to match some test cases?


答:
Although it's not a panacea, there may be some code inspection tools for your language that can help find errant behavior.

For example, Pex is a white-box testing tool for .NET applications that looks for code paths and creates a series unit tests using data that exercise each code path. You can try it on the web at Pex For Fun. And I just discovered Code Digger, a lightweight version of Pex built as a Visual Studio extension.

When I've run it against my code, I've had some success discovering edge cases I'd failed to account for. I found the exercise made me a better unit test author.


问:
Dependency injection: How to sell it
Let it be known that I am a big fan of dependency injection (DI) and automated testing. I could talk all day about it.

Background

Recently, our team just got this big project that is to built from scratch. It is a strategic application with complex business requirements. Of course, I wanted it to be nice and clean, which for me meant: maintainable and testable. So I wanted to use DI.

Resistance

The problem was in our team, DI is taboo. It has been brought up a few times, but the gods do not approve. But that did not discourage me.

My Move

This may sound weird but third-party libraries are usually not approved by our architect team (think: "thou shalt not speak of Unity, Ninject, NHibernate, Moq or NUnit, lest I cut your finger"). So instead of using an established DI container, I wrote an extremely simple container. It basically wired up all your dependencies on startup, injects any dependencies (constructor/property) and disposed any disposable objects at the end of the web request. It was extremely lightweight and just did what we needed. And then I asked them to review it.

The Response

Well, to make it short. I was met with heavy resistance. The main argument was, "We don't need to add this layer of complexity to an already complex project". Also, "It's not like we will be plugging in different implementations of components". And "We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit".

Finally, My Question

How would you handle my situation? I am not good in presenting my ideas, and I would like to know how people would present their argument.

Of course, I am assuming that like me, you prefer to use DI. If you don't agree, please do say why so I can see the other side of the coin. It would be really interesting to see the point of view of someone who disagrees.

Update

Thank you for everyone's answers. It really puts things into perspective. It's nice enough to have another set of eyes to give you feedback, fifteen is really awesome! This are really great answers and helped me see the issue from different sides, but I can only choose one answer, so I will just pick the top voted one. Thanks everyone for taking the time to answer.

I have decided that it is probably not the best time to implement DI, and we are not ready for it. Instead, I will concentrate my efforts on making the design testable and attempt to present automated unit testing. I am aware that writing tests is additional overhead and if ever it is decided that the additional overhead is not worth it, personally I would still see it as a win situation since the design is still testable. And if ever testing or DI is a choice in future, the design can easily handle it.

答:
Although one of the things that promote DI is unit testing, but I believe that it adds layer of complexity in some cases.

Better To have a car hard in Testing, but easy in Repair than car easy in testing and Hard in repair.

Also it seems to me that the group pushing for DI are only presenting their ideas through influencing that some existing designs approaches are bad.

if we have a method doing 5 different functions

DI-People Says:

no separation of concerns. [ what is the problem of that? they are trying to make it look bad, which in logic and programming it is much better to know what each other is doing closely to better avoid conflicts and wrong-expectations and to see the impact of code change easily, because we cannot make all your objects not related to each other 100% or at least we cannot guarantee this {unless why regression testing is important?} ]

Complex [They want to reduce complexity by making additional five more classes each to handle one function and additional class(Container) to create the class for needed function now based on settings (XML or Dictionary)  in addition to philosophy "to have a default/or not" discussions, ... ] then they moved the complexity to the container and to the structure , [ to me looks like moving complexity from one place to two places with all complexities of language specifics to handle this. ]

I believe that it is better to create our own design pattern that suits the business needs
rather than to be influenced by DI.

in favor of DI, it might help in some situations, for example if you have hundreds of implementations for the same Interface depends on a selector and these implementations are far different in logic, in this case I would go with DI or DI similar techniques. but if we have few implementations for the same interface we don't need DI.

Title: Dependency injection: How to sell it


答:
One shouldn't worry about whether or not the data in the table is ordered in SQL.  There's the ORDER BY clause in SQL if you need to order the result of the query.  If you don't need to order resuts, just select.  Performance will depend on use of proper indexing and keeping the indexes and statistics and up to date.  1 gig may seem big, but in today's world should not be that big of deal to create a performant table structure.

It is not necesary to have lots of small tables for each client.  You don't want to support a database with lots of tables where just a few will be needed, unless you want to provide those levels of isolation as a service.  In other words, one model that can be deployed across 1 to many instances and 1 to many servers.

There are roughly 3 levels for for your model:

Shared - One Server, One database, Many Client, clients shared the
same model and tables.

Instance - One Server, Multiple databases, Many Clients, clients
share or have thier own instance of the model.

Server - Mulitple Servers, Multiple database, Multiple Instance, Many Clients - Clients
share, have thier own instance, or have thier own instance and server
(isolated)

Cost wise  $ Share <  $$$ Intannce < $$$$$ Server and should be priced as such.

What do you say to your boss?

We will develop 1 database model that can be deployed as needed depending on how the client wants to isolate thier data.

Title: Violating SQL principles


问:
Is there any specific reason to use "else if" clause?
We all use if ..else if.. else.

But still I'm confused as to why we use else if. Where if does the same thing as else if.

So why are we using else if?

Any specific reasons behind this?

Is there any algorithm where it's mandatory to use else if?

答: It's for efficiency.  If you have a chain of if...else if...else if clauses, then evaluation stops after one evaluates to true.  If you simply have a list of if clauses, then even after one evaluates to true, you'll still check the rest of them, even though they'll be false. If the conditions involve invoking functions or other "expensive" operations then you'll waste resources (especially if your conditions involve web service calls or database lookups).  This is also why you should try to structure complicated conditional expressions like this so that the "cheapest" conditions are checked first.


问:
Build number when supporting previous version
I am developing and maintaining a web-based application that's used internally at my job.  I am the only developer and so I'm not really using branches; everything happens on the trunk. I do tag releases in Git with the date and time, and I'm starting to transition to using a build number instead of date/time.

In the production instance of the app (which is just a tag on the trunk), a bug has been discovered that needs to be fixed ASAP. In the meantime, I've been developing new features, but they're not ready to be distributed.

Fixing the bug is easy: check out the tag into a new branch, fix, publish.  However, in such a situation, what should the fix's build number be?

If I follow the existing build strategy of incrementing a serial number, my build numbers will be, e.g.

```<code>1234: production
1235: development (with new features)
1236: production fix (doesn't have new features)
</code>```

which doesn't seem to make sense.  Alternately, incrementing the production tag's build number would lead to, e.g.

```<code>1234: production
1235: development (new features)
1235: production fix
</code>```

which defeats the purpose of build numbers (uniquely identify a particular build).

Using Git's revision ID is another option, but they're not exactly readable.

答:
You could use Semantic Versioning as well as follow the Git workflow. You can move your current development work into a feature branch, bring master back to a commit prior to having done any new feature development and only merge the new features into master when it is ready (i.e. cleared all your tests and cleared QA). That way you can directly apply your bug fix to master.

Following the Git Workflow helps avoid situations similar that in which you are in and would be my recommended approach moving forward


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
I work for a public body. There's really no way to adequately explain the level of waste that can go on when the workplace is so heavily legislated and unionised that sacking someone is practically almost impossible.

Managers play pass the parcel with bad staff, and hope to remove them all at once under cover of restructuring. Some bad staff are promoted, just to move them out of an area that needs improvement. Any good staff end up struggling constantly just to make up for the bad staff's work. Staff you wouldn't keep for 3 months forge 40 year careers. The amount of money they waste over such careers is astronomical.

I worked in the private sector previously, and saw a lot of waste, but public sector waste is a whole different sport, let alone ballgame.

It was suggested in a comment that establishing sinecures for underperforming staff would help. It would help in that it would limit the damage they could do, but wouldn't impact the root causes of the problem. I think the best thing would be the adoption of some private sector hiring and management procedures, and changes in legislation to make it easier for public bodies to let staff who underperform go. Unions should also change their policies in consultation with the government - their role of protecting their members is important, but they should recognise that sometimes their members are truly out of their depth, and should be moved on

ContentLicense: CC BY-SA 2.5


问:
Why separate class CommandHandler with Handle() instead of handling method in Command itself
I have a part of CQRS pattern implemented using S#arp Architecture like this:

```<code>public class MyCommand
{
    public CustomerId { get; set; }

    // some other fields
}

public class MyCommandHandler<MyCommand> : ICommandHandler<MyCommand, CommandResult>
{
    Handle(MyCommand command)
    {
        // some code for saving Customer entity

        return CommandResult.Success;
    }
}
</code>```

I wonder why not just have class Command containing both data and handling method? Is it a kind of testability benefit, where you need to test command handling logic separately from command properties? Or is it some frequent business requirement, where you need to have one command handled by different implementations of ICommandHandler<MyCommand, CommandResult>?

UPDATE:

Looking at it after 6 years, I say making a handler class for each command type is definitely an overkill with a lot of syntactic noise. Nowadays I would have a single class to handle a bunch of commands related to the same topic (akin to Sum Types in more functional languages). If each of them requires a gigantic handler, than they should be split into simpler steps, managed by finer grained commands. Or use a different pattern altogether.

答:
Normal command pattern is about having the data and behavior in single class. This kind of 'Command/Handler pattern' is slightly different. The only advantage compared to the normal pattern is added advantage of not having your command depend on frameworks. For example, your command might need DB access so it has to have some kind of DB context or session, meaning it is dependent on frameworks. But this command might be part of your domain, so you don't want it to depend on frameworks according to Dependency Inversion Principle. Separating the input and output parameters from the behavior and having some dispatcher to wire them up can fix this.

On the other hand, you will loose advantage of both inheritance and composition of commands. Which I think is it's true power.

Also, minor nitpick. Just because it has Command in name doesn't make it part of CQRS. That is about something much more fundamental. This kind of structure can serve both as command and as a query even at the same time.

ContentLicense: CC BY-SA 4.0


答:
Funny, this question just reminded me of exactly same conversation I had with one of our engineers about communications library I was working on.

Instead of commands, I had Request classes and then I had RequestHandlers. The design was very much like what you are describing.  I think part of the confusion that you have is that you see the English word "command", and instantly think "verb, action... etc".

But in this design, think of Command (or Request) as a letter. Or for those that don't know what a postal service is, think e-mail.  It is simply content, decoupled from how that content should be acted upon.

Why would you do this? In most simple cases, of Command Pattern there is no reason and you could have this class perform work directly. However, doing the decoupling as in your design makes sense if your action/command/request must travel some distance. For example, across, sockets or pipes, or between domain and infrastructure. Or maybe in your architecture your commands need to be persistent (e.g. command handler can do 1 command at a time, due to some system events, 200 commands arrives and after first 40 process gets shutdown).  In that case, having a simple message-only class it becomes very simple to serialize just the message part into JSON/XML/binary/whatever and pass it down the pipeline until its command handler is ready to process it.

Another advantage of decoupling Command from CommandHandler is that now you have the option of parallel inheritance hierarchy. For example, all your commands could derive from a base command class that supports serialization.  And maybe you have 4 out of 20 command handlers that have a lot of similarity, now you can derive those from the came handler base class.  If you were to have data and command handling in one class, this type of relationship would quickly spiral out of control.

Another example for the decoupling would be if your command required very little input (e.g. 2 integers and a string) yet its handling logic was complex enough where you would want to store data in the intermediate member variables.  If you queue up 50 commands, you don't want to allocate memory for all that intermediate storage, so you separate Command from CommandHandler.  Now you queue up 50 light-weight data structures and more complex data storage is allocated only once (or N times if you have N handlers) by the CommandHandler that is processing the commands.

Title: Why separate class CommandHandler with Handle() instead of handling method in Command itself

Body:
I have a part of CQRS pattern implemented using S#arp Architecture like this:

```<code>public class MyCommand
{
    public CustomerId { get; set; }

    // some other fields
}

public class MyCommandHandler<MyCommand> : ICommandHandler<MyCommand, CommandResult>
{
    Handle(MyCommand command)
    {
        // some code for saving Customer entity

        return CommandResult.Success;
    }
}
</code>```

I wonder why not just have class Command containing both data and handling method? Is it a kind of testability benefit, where you need to test command handling logic separately from command properties? Or is it some frequent business requirement, where you need to have one command handled by different implementations of ICommandHandler<MyCommand, CommandResult>?

UPDATE:

Looking at it after 6 years, I say making a handler class for each command type is definitely an overkill with a lot of syntactic noise. Nowadays I would have a single class to handle a bunch of commands related to the same topic (akin to Sum Types in more functional languages). If each of them requires a gigantic handler, than they should be split into simpler steps, managed by finer grained commands. Or use a different pattern altogether.


问:
Auto Transaction Failsafe's, Third Party API's, Coldfusion Schedule Files
I have an automated invoicing web app and I'm trying to build in some failsafes and a structure that will, under no circumstance, allow an invoice to be double charged.

All things working perfectly, the scheduled task runs and everything charges as it's supposed to. But there are a few scenarios we know of that can cause problems.

I've had a DB server go down in the middle of a process, which lead to a number of duplicate charges. Also if for whatever reason, the file needs to be checked in a browser, a developer hits refresh before the file is done processing, duplicate charges will occur.

There are a few similar scenarios to protect against, so you can see the need for a way to handle this given the sensitivity of the transactions (imaging seeing your power company auto charging you twice on your bank statement).

Current configuration:

Query

API POST For Transaction

```<code><!--- Parse Reply String --->
if response = "1"

 - Insert Into Payments

 - Update Invoice Amount Due

 - Insert Into Transactions

 - Email Accepted Notification

else

 - Email Declined Notification
</code>```

There's a few more smaller processes that happen between a few of these, as well as quite a few if statements but those are the heavy lifting parts.

What I would like to learn and hear about are what would be the best way to handle safeguarding this with considering the Third Party API for the gateway being there?

How would you break it up?

One idea I had was flagging each process after it ran to give a record of where it was when it failed, and build out the query to handle it accordingly. Not sure how efficient or more likely how inefficient it would be.

答:
In complex ERP systems when a record needs to be protected there is usually a locking mechanism in place somewhere. In most systems this involves either a DB table or a flag on the table itself.

So one way of doing this is to have an table (say, InvEdit) that contains the invoice ID. The first thing you do is to put the invoice id's of the invoices you wish to edit in the table. Next you do the work on a per invoice basis as a single transaction. The last act of the transaction would be to remove the invoice from your invEdit table. You would naturally also want to change something about the invoice so that it would not be put in the invEdit table again (but you are probably already doing that - updating a status or a date or whatever).

If a transaction fails (because the DB goes down or whatever) that data is not commited and the Invoice ID remains in the invEdit table. If it succeeds it is removed. If the DB goes down OR if the item is refreshed or the Web server crashes or whatever you can pick up where you left off - from the "queue" provided by your invEdit table.

This is just one approach of course. I'm sure that others can think of more.

OwnerDisplayName: Mark A Kruger


问:
The real difference between web and native apps in mobile and smart devices
I still don't understand the difference between a native app and web or hybrid apps from the interface point of view. Now, apps such as Twitter, Facebook, etc. Are they native? or web? or hybrid apps? In those apps what is the most code was used? is it HTML and JS? or is it a language such as Objective C or Java?

I'm still confused.

答:
Native applications use Objective C or Java.  Web applications use HTML5, CSS3, and Javascript, running in a browser.

Native applications may have to be written more than once, to satisfy the native platform's specific demands, such as programming language.

Web applications may have limited access to the underlying native platform, and may not perform as well as their native counterparts.

Some vendors provide toolchains that allow you to create native applications once, and run them on multiple platforms.  In some cases, they do this by creating a web application and providing a common underlying API to target.


问:
Best way to keep large amounts of data (no relational database needed)
I would like to know what should be the best way to keep data on a server related to the following points:

Chat logs

Heavy text content

User references like amounts of ids (1,4,14,524,23220,...)

I'm using PHP and a mysql database but as obvious I know the topics above don't go well into mysql at large scale and maneuvering. So I would like to know how (no, i'm not asking for your work, just your 3-line orientation) exactly should I keep the data :)

Ok basically I keep my users in a sql table and another only for their friendships in which I have a field containing references related, allegedly, to chat logs. Now the thing is I don't actually understand whether I should have that content in a file, keep the file path in that sql field and then retrieve the file when needed, parse it and display it to the user or keep it in a database such as mongodb, raven, couch because I've never used no-sql database and wanted to know of experienced people on it. Same goes for the heavy text content and user references. For example, in my users table I have a field containing its friends in the following manner 1,4,5,6,14,51,... and since I've been told this is bad practice and certainly should be used whilst dealing with large amounts of data that would need to be changed constantly I came here in a hopeful act of guidance and enlightment.

答:
So here's an example. An item processing system at a bank will need to store the front and rear images of the check, but a single bank can process 6,000 items in a day (12,000) images. These images do not need to be retrieved very often, only in a research case.

From the storage perspective it makes more sense to store these on the file system rather than the disk because the data is not constantly changing, access can be slower and the database size does not grow by a few hundred gigabytes a day which affects time to restore backups.

The application needs separate logic to write and load images as opposed to metadata stored in the database and this is an additional cost to develop and a separate file system must be maintained.

Storing large blocks of text in the database is probably going to be cheaper to develop and manage than writing it out to a file system, but depending on the rate of change, retrieval needs, cost of storage vs. capital to purchase it you could make a case for storing it outside the database.

As a side note, storing lists in a single column of a database creates nightmares of  programmers who have to parse them when they need a single value. Use the R in relational database management system to preserve sanity.


答:
Having data in the structure "1,4,5,6,14,51,..." as one data value is a denormalized value.

Lets say you've got something that looks like:

```
Person2's friends are: 1, 4, 5, 7, 14, 51
Person3's friends are: 1, 5, 7, 15, 50
```

And so on.  Now, lets ask the question "How many people consider person 5 to be their friend?"  Well, in a denormalized structure, you're going to fetch every person's friends and then break it apart on the delimiter, and then see if 5 is in that list, increment the count and move on.

With a relational database, you've got a structure that looks like:

```
  +--------+     +----------+
  | user   |     | friends  |
  |--------|     |----------|
  | id (pk)|&lt-+--| from (fk)|
  | name   |  +--| to   (fk)|
  | ...    |     +----------+
  +--------+
```

And your query to answer this question is: select count(1) from friends where to = 5  And, well... you're done.  You've looked over one small table that can be queried very quickly.

You've also got things if you want to cascade a delete to properly clean up the references in other tables (you've deleted user 5, make sure 5 is deleted from all the users).  There's things like consistency, isolation and durability (part of ACID) that help ensure that your data maintains the proper structure.

NoSQL has its place.  But its not a relational database and doesn't pretend to be.  It also throws away the guarantees of ACID as a trade off for speed and ease of clustering (part of speed).  There are times you don't care about ACID and instead want the API that is provided by a nosql database (i.e. you are creating an offline instance of an application and cache all web requests - your couchdb, being accessed as a web request means that the off line one doesn't need another database).

I would suggest reading the nosql tag on Martin Fowler's bliki (blog + wiki).

There are solutions where nosql fits quite well.  LDAP is an ancient protocol that could be thought of as one of the earliest nosql databases that exists today.  You don't access it via sql, but you do for storing data... hierarchal data.  It really works well for such data, and very fast.  Its got clustering and eventual consistency and all the things you think of when you hear about of nosql.

I wouldn't want to implement a chat system in ldap - its not the right structure.  Trying to make relational databases do what ldap does is also not a fun process.

If you are thinking of doing this as a learning experience.  Something to understand how nosql works, yea... go ahead.  Try implementing a chat system in mongo or couch.  Many people have.  I wouldn't be surprised if SE's chat isn't backed by such a data store... though I'm not sure if its couch, or mongo... the domain of noSQL is quite large in that two nosql databases may share more in common with mySQL than with each other in design.  Do chose a key-value database? or a column oriented one? or a documented oriented one? or a graph database? or... Wikipedia lists 10 different flavors of NoSQL with 5 different sub flavors of the key-value store.

I would suggest reading from SO SQL (MySQL) vs NoSQL (CouchDB) and chase the links and related links on that page.

If the data is relational... well, its likely a relational database that you are looking for (and you should make sure you learn about database normalization).

Title: Best way to keep large amounts of data (no relational database needed)

Body:
I would like to know what should be the best way to keep data on a server related to the following points:

Chat logs

Heavy text content

User references like amounts of ids (1,4,14,524,23220,...)

I'm using PHP and a mysql database but as obvious I know the topics above don't go well into mysql at large scale and maneuvering. So I would like to know how (no, i'm not asking for your work, just your 3-line orientation) exactly should I keep the data :)

Ok basically I keep my users in a sql table and another only for their friendships in which I have a field containing references related, allegedly, to chat logs. Now the thing is I don't actually understand whether I should have that content in a file, keep the file path in that sql field and then retrieve the file when needed, parse it and display it to the user or keep it in a database such as mongodb, raven, couch because I've never used no-sql database and wanted to know of experienced people on it. Same goes for the heavy text content and user references. For example, in my users table I have a field containing its friends in the following manner 1,4,5,6,14,51,... and since I've been told this is bad practice and certainly should be used whilst dealing with large amounts of data that would need to be changed constantly I came here in a hopeful act of guidance and enlightment.

Body:
Having data in the structure "1,4,5,6,14,51,..." as one data value is a denormalized value.

Lets say you've got something that looks like:

Person2's friends are: 1, 4, 5, 7, 14, 51
Person3's friends are: 1, 5, 7, 15, 50

And so on.  Now, lets ask the question "How many people consider person 5 to be their friend?"  Well, in a denormalized structure, you're going to fetch every person's friends and then break it apart on the delimiter, and then see if 5 is in that list, increment the count and move on.

With a relational database, you've got a structure that looks like:

  +--------+     +----------+
  | user   |     | friends  |
  |--------|     |----------|
  | id (pk)|&lt-+--| from (fk)|
  | name   |  +--| to   (fk)|
  | ...    |     +----------+
  +--------+

And your query to answer this question is: select count(1) from friends where to = 5  And, well... you're done.  You've looked over one small table that can be queried very quickly.

You've also got things if you want to cascade a delete to properly clean up the references in other tables (you've deleted user 5, make sure 5 is deleted from all the users).  There's things like consistency, isolation and durability (part of ACID) that help ensure that your data maintains the proper structure.

NoSQL has its place.  But its not a relational database and doesn't pretend to be.  It also throws away the guarantees of ACID as a trade off for speed and ease of clustering (part of speed).  There are times you don't care about ACID and instead want the API that is provided by a nosql database (i.e. you are creating an offline instance of an application and cache all web requests - your couchdb, being accessed as a web request means that the off line one doesn't need another database).

I would suggest reading the nosql tag on Martin Fowler's bliki (blog + wiki).

There are solutions where nosql fits quite well.  LDAP is an ancient protocol that could be thought of as one of the earliest nosql databases that exists today.  You don't access it via sql, but you do for storing data... hierarchal data.  It really works well for such data, and very fast.  Its got clustering and eventual consistency and all the things you think of when you hear about of nosql.

I wouldn't want to implement a chat system in ldap - its not the right structure.  Trying to make relational databases do what ldap does is also not a fun process.

If you are thinking of doing this as a learning experience.  Something to understand how nosql works, yea... go ahead.  Try implementing a chat system in mongo or couch.  Many people have.  I wouldn't be surprised if SE's chat isn't backed by such a data store... though I'm not sure if its couch, or mongo... the domain of noSQL is quite large in that two nosql databases may share more in common with mySQL than with each other in design.  Do chose a key-value database? or a column oriented one? or a documented oriented one? or a graph database? or... Wikipedia lists 10 different flavors of NoSQL with 5 different sub flavors of the key-value store.

I would suggest reading from SO SQL (MySQL) vs NoSQL (CouchDB) and chase the links and related links on that page.

If the data is relational... well, its likely a relational database that you are looking for (and you should make sure you learn about database normalization).


问:
Are for loops supposed to be read inward or outward?
```<code> for (i = 0; i < 3; i++)
 {
    for (j = 0; j < 4; j++)
    {
        cout << arr2d[i][j] << "\t";
    }
    cout << endl;
    .....
</code>```

Like that for example. Do you read the for loop inward-out (starting from for (j = 0; j < 4; j++)) or outward-in (starting from for (i = 0; i < 3; i++)) Just wondering. :D

答:
This is a bit of a difficult question to answer. I would READ the loops from the top down. I'll assume then that you are referring to the order the code is executed in. When you see a loop structure, such as the one in your code, the outermost loop is the first thing that runs.

```<code> for (i = 0; i < 3; i++) //This indicates that whatever is in between the braces that
                         //follow will be run 3 times.
  {
     for (j = 0; j < 4; j++)
     {
       cout << arr2d[i][j] << "\t";
     }
   cout << endl;
  }
</code>```

The next line of code is what is run. In your case, that's another loop. Rinse and repeat.

```<code> for (i = 0; i < 3; i++)
  {
     for (j = 0; j < 4; j++) //This loop will execute 4 times for each iteration
                             //of the outer loop
     {
       cout << arr2d[i][j] << "\t";   //Therefore, this statement is executed
                                      //12 times in total
     }
   cout << endl; //and this one only 3, as it is outside of the inner loop.
  }
</code>```

So how to read them? From the top down. Trace your braces, and remember that the first line of code that happens after the braces will be the one to run first.  To put it in your words, "outward-in", just be sure you don't think that loops take a higher precedence than other code. If we were to insert a cout between the first and second loop, the outer loop would begin execution, then the cout, and finally the inner loop (and it's contents) followed by any statements after it.

Body:
This is a bit of a difficult question to answer. I would READ the loops from the top down. I'll assume then that you are referring to the order the code is executed in. When you see a loop structure, such as the one in your code, the outermost loop is the first thing that runs.

 for (i = 0; i < 3; i++) //This indicates that whatever is in between the braces that
                         //follow will be run 3 times.
  {
     for (j = 0; j < 4; j++)
     {
       cout << arr2d[i][j] << "\t";
     }
   cout << endl;
  }

The next line of code is what is run. In your case, that's another loop. Rinse and repeat.

 for (i = 0; i < 3; i++)
  {
     for (j = 0; j < 4; j++) //This loop will execute 4 times for each iteration
                             //of the outer loop
     {
       cout << arr2d[i][j] << "\t";   //Therefore, this statement is executed
                                      //12 times in total
     }
   cout << endl; //and this one only 3, as it is outside of the inner loop.
  }

So how to read them? From the top down. Trace your braces, and remember that the first line of code that happens after the braces will be the one to run first.  To put it in your words, "outward-in", just be sure you don't think that loops take a higher precedence than other code. If we were to insert a cout between the first and second loop, the outer loop would begin execution, then the cout, and finally the inner loop (and it's contents) followed by any statements after it.


答:
You can't really read loops inward or outward, it's a bit more complex than that.

The loops start with the outer loop, but for each iteration in that loop, the inner loop goes through a complete cycle.

If you would print out the counters inside the inner loop, you would see:

```<code> i   j
--- ---
 0   0
 0   1
 0   2
 0   3
 1   0
 1   1
 1   2
 1   3
 2   0
 2   1
 2   2
 2   3
</code>```

Title: Are for loops supposed to be read inward or outward?

Body:
```<code> for (i = 0; i < 3; i++)
 {
    for (j = 0; j < 4; j++)
    {
        cout << arr2d[i][j] << "\t";
    }
    cout << endl;
    .....
</code>```

Like that for example. Do you read the for loop inward-out (starting from for (j = 0; j < 4; j++)) or outward-in (starting from for (i = 0; i < 3; i++)) Just wondering. :D

Body:
You can't really read loops inward or outward, it's a bit more complex than that.

The loops start with the outer loop, but for each iteration in that loop, the inner loop goes through a complete cycle.

If you would print out the counters inside the inner loop, you would see:

 i   j
--- ---
 0   0
 0   1
 0   2
 0   3
 1   0
 1   1
 1   2
 1   3
 2   0
 2   1
 2   2
 2   3


问:
How do I recreate this Access Control/Group/ whatever methodology in OO/MVC
I am looking at trying to rewrite an application that is mostly procedural to an MVC/OO approach in order to teach myself a deeper understanding of both.

BUT, I am having some conceptual issues with the current group/access control that is used.

We have Groups (Businesses) that have role based users (Manager, salespersons, customers).
They can have customers either assigned to a salesperson, or not. The manager sees everything, the salesperson only those customers assigned to him.

```<code>Business
  |
  ---Manager
       |
       ---Salespersons
            |
            ---Customers
  |
  ---Customers
</code>```

The table structure for this currently is something like this:

```<code>users (userID [demographic info])
business (businessID, userID, et al [demographic info])
salespeople (salesID, businessID, userID [just foreign keys])
customers (customerID, businessID, userID, et al [demographic info])
salesAssignments (salesID, customerID [just foreign keys])
</code>```

The Manager can affect everyone within that businesses group (everyone has a businessID that links them to that business and no other). The customers can login and make minor changes to their profiles or interact via messaging to their salesperson or the businesses manager.

Added Spice to the mix: (comment on any of these if they apply to your insights to the above question) Is there a better way to have similar user access and control?
I want to rebuild the site with an API that can be used by both the web app and mobile apps.

EDIT
My main conceptual hangup at the moment relates to how to recreate this structure in a user object for the OO part of the application. Now everything is accessible via session variables, or queried from the DB via procedural functions.
Again my understanding of OO is limited, and this is an attempt to figure it out.

答:
Create a user class, and then a class that inherits from it for each kind of user. Add a collection of type as appropriate to each of these classes for the child relationships e.g.

```<code>class User {}

class Manager : User
{
    Collection<SalesPerson> SalesPeople { get; set; }
}

class SalesPerson : User {}
</code>```

Now, when you have a manager, you can navigate into the related sales people (assuming the list is correctly populated)

Body:
Create a user class, and then a class that inherits from it for each kind of user. Add a collection of type as appropriate to each of these classes for the child relationships e.g.

class User {}

class Manager : User
{
    Collection<SalesPerson> SalesPeople { get; set; }
}

class SalesPerson : User {}

Now, when you have a manager, you can navigate into the related sales people (assuming the list is correctly populated)


问:
Sequence Diagram. UML "Use Case Ends"
I have a couple of questions about UML.

Firstly, how would you show "Use Case Ends" on a sequence diagram.

Secondly, if you have an alt in a sequence diagram for "Variable == false", would you need to show what would happen if the variable is true, even if nothing would happen other than moving onto the next method call?

Third, isn't the last arrow on the diagram always going to be asynchronous, because it can continue and does not have to wait?

答:
A sequence diagram ends at the bottom. It's read top left with the next function call placed lower in the diagram. There's no need to explicitly mark the end of the diagram, since there's no more function calls and the activation boxes and lifelines end. If, at the end of the part of the application that you are showing, delete resources, you can add an "X" to the end of the lifelines to denote this, but it's often not required.

When you have an alternative path in a sequence diagram, you only need to indicate the "true" and "false" path if they are mutually exclusive. For example, if you have a series of calls that only happen when the variable is false, include those in an box labeled as such. If there are branches, I've typically seen a dotted horizontal line through the alt box and a new condition labeled right below the line.

I'm not sure what exactly you mean with your last question. It doesn't have to be asynchronous. It all depends on what you are showing in your sequence diagram.

You may be interested in this page, by Scott Ambler on UML sequence diagrams, as well.

Title: Sequence Diagram. UML "Use Case Ends"

OwnerDisplayName: Thomas Owens


问:
I need advice for a subsystem design?
I'm doing it in C++, I can't post the entire thing, because it's gigantic, I'll just sum it up with a simple example.I have:

```<code>class B;

class A
{
 //Members and methods...
  void DoSomething(B* owningSystem);
};

class B
{
 //Members and methods
A memberA;
}
</code>```

So the problem is, A needs to know about B to use its DoSomething method and A is actually a member of B.I have an array of B's, who's number is determined at run-time.This might sound like overdoing it, but I need extreme optimization in this specific project and I was wondering - is it better to pass B* owningSystem or to just store a pointer of each B inside its A member?I don't think DoSomething will ever be inlined, since their count and pointer locations are determined at run-time, but I can chose storing a pointer vs. passing it in the function.I need to minimize the overhead at this point by as much as I can, it's critical.I'm open to any suggestions, please

答:
If the B* is a member of A, then I think you'll have two dereferences every time you use it since m_b->Action(); is really this->m_b->Action();.   If you pass the pointer as an argument, there's only one dereference.

It's possible that passing the argument might slightly slow the function call to A::DoSomething() but passing a single pointer must have nearly zero overhead.

Title: I need advice for a subsystem design?


答:
What I found from all kinds of trial an error is that when you have components with circular dependency on each other (more so in C++ than in dynamic languages like python), you are asking for trouble, so I always make it a point of always defining a strict hierarchical relationship between classes.

In this case it seems that B is a higher level class than A, so let's keep it that way.  How about something like this:

```<code>typedef interface struct;             // in MSVC this is built into compiler

interface IOwnerOfA {
    virtual int someFunctionCall() = 0;
}

class A {
    IOwnerOfA*  m_pOwner;

    void DoSomething() { .... bunch of code; m_pOwner->someFunctionCall(); .... }
}

class B : private IOwnerOfA {
    // yeah, cast is optional but I like them in these cases
    B() : m_a( static_cast< IOwnerOfA* >( this ) {}

    virtual int someFunctionCall() {
        ... provide specific functionality A needs;
        and nothing else;
    }

    A        m_a;
}
</code>```

So now the hierarchy is IOwnerOfA <-- A <--- B. Everyone knows about the interface, B knows of A, A knows nothing about B, so tomorrow you could have C using A without having to make any changes in A.

As far as your question about storing a member variable vs. pass in as parameter into DoSomething(), that's really up to you.  If it is only one isolated place, I'd probably pass into a parameter.  If the relationship between classes really is that B is an "owner" of A and in A needs to call back into B (via IOwnerOfA interface) in a number of places, then store as a member.

Another alternative for you to consider (if you are doing a one off in one place) is instead of using interfaces and class pointers, you can take a functional approach and have DoSomething() accept std::function as a parameter type.  Then use std::bind() to pass in a bound member function.  Might sound a bit crazy, but it's actually somewhat straightforward (except for the compiler errors if you get something wrong) and very flexible (once you get past the compiler errors)

To add to what @JTrana, commented on. There are definitely cases where B owns A and for whatever reason A needs to callback into B. If you need to do this, the only two options I see are using interface (yes one extra level of indirection) and using direct types (circular dependency). Between those 2 choices, extra complexity of the interface is a winner for me.  However, these true cases are few and far between.  Most of the time you might be able to refactor your app so you don't need to do this circular loop.

Consider if part of B that A needs could be switched out into a smaller C class:

```<code>class C {   // contains some commonly used functionality
}

class A {
    DoSomething( C* pCommonGuy) { .... }
}

class B {
    A  m_a;
    C  m_c;
}
</code>```

Title: I need advice for a subsystem design?

Body:
I'm doing it in C++, I can't post the entire thing, because it's gigantic, I'll just sum it up with a simple example.I have:

```<code>class B;

class A
{
 //Members and methods...
  void DoSomething(B* owningSystem);
};

class B
{
 //Members and methods
A memberA;
}
</code>```

So the problem is, A needs to know about B to use its DoSomething method and A is actually a member of B.I have an array of B's, who's number is determined at run-time.This might sound like overdoing it, but I need extreme optimization in this specific project and I was wondering - is it better to pass B* owningSystem or to just store a pointer of each B inside its A member?I don't think DoSomething will ever be inlined, since their count and pointer locations are determined at run-time, but I can chose storing a pointer vs. passing it in the function.I need to minimize the overhead at this point by as much as I can, it's critical.I'm open to any suggestions, please

Body:
What I found from all kinds of trial an error is that when you have components with circular dependency on each other (more so in C++ than in dynamic languages like python), you are asking for trouble, so I always make it a point of always defining a strict hierarchical relationship between classes.

In this case it seems that B is a higher level class than A, so let's keep it that way.  How about something like this:

typedef interface struct;             // in MSVC this is built into compiler

interface IOwnerOfA {
    virtual int someFunctionCall() = 0;
}

class A {
    IOwnerOfA*  m_pOwner;

    void DoSomething() { .... bunch of code; m_pOwner->someFunctionCall(); .... }
}

class B : private IOwnerOfA {
    // yeah, cast is optional but I like them in these cases
    B() : m_a( static_cast< IOwnerOfA* >( this ) {}

    virtual int someFunctionCall() {
        ... provide specific functionality A needs;
        and nothing else;
    }

    A        m_a;
}

So now the hierarchy is IOwnerOfA <-- A <--- B. Everyone knows about the interface, B knows of A, A knows nothing about B, so tomorrow you could have C using A without having to make any changes in A.

As far as your question about storing a member variable vs. pass in as parameter into DoSomething(), that's really up to you.  If it is only one isolated place, I'd probably pass into a parameter.  If the relationship between classes really is that B is an "owner" of A and in A needs to call back into B (via IOwnerOfA interface) in a number of places, then store as a member.

Another alternative for you to consider (if you are doing a one off in one place) is instead of using interfaces and class pointers, you can take a functional approach and have DoSomething() accept std::function as a parameter type.  Then use std::bind() to pass in a bound member function.  Might sound a bit crazy, but it's actually somewhat straightforward (except for the compiler errors if you get something wrong) and very flexible (once you get past the compiler errors)

To add to what @JTrana, commented on. There are definitely cases where B owns A and for whatever reason A needs to callback into B. If you need to do this, the only two options I see are using interface (yes one extra level of indirection) and using direct types (circular dependency). Between those 2 choices, extra complexity of the interface is a winner for me.  However, these true cases are few and far between.  Most of the time you might be able to refactor your app so you don't need to do this circular loop.

Consider if part of B that A needs could be switched out into a smaller C class:

class C {   // contains some commonly used functionality
}

class A {
    DoSomething( C* pCommonGuy) { .... }
}

class B {
    A  m_a;
    C  m_c;
}


问:
How to test a website?
I found it's really hard to divide the task of developing a website to a team of people.

The problem is a website should have consistent looking and be integrated in users' view. The style and page template need to be shared by all parts. Most of the website is access restricted, the access control system is dependent of all modules. Some modules need data from other modules (you can never ask user the same question again). Although these modules may run independently. The test data have to be generated by other ones.

With the increase of code, the website becomes harder and harder to test. Although we are maintaining a script to automate the deployment. But if anything goes wrong, a developer cannot solve the problem by himself, for he is not familiar with others' work.

What makes things worse is the configuration. Server settings are highly machine dependent. Some functions need to schedule tasks, so there are some crontab configurations. Some modules need other daemons running in the backend. Some applications require URL rewriting. To test the website, we need to configure all dependencies of all modules on all machines.

Is there any suggestion about how to test a website?

答:
You have three separate, unrelated issues here, which both are opportunities to improve the management of your website team.  In order of difficulty for implementation, you need (1) a test server, (2) an improved architecture for your site, and (3) some coding standards your team can be compelled to follow.

(1): Implement a Test Server

If your website is important enough to have more than a single programmer work on it, then it's important enough to create a dedicated test server.  The server can be a virtual machine if appropriate, but it SHOULD NOT be administered by your programmers, and it SHOULD be as identical to your production environment as practicable while not being the same machine.

Your developers can program on their desktops or on a third "development" machine, but code that goes on the test server should be there only for testing, and should be in a state such that it can be copied entirely either to or from the production server without any changes beyond perhaps a process reboot.

(2) Improve your site's architecture

It sounds like you may have a serious lack of separation between design, code, and content.  Ensuring that your various components all have the same look and feel is NOT the same job as writing sensitive data-handling components, and even if they are performed by the same team they should be written in entirely different work sessions and stored in entirely different files.

Even if that was a miscommunication, your team both thinking that they need to fix problems in a deployment and not being confident on how to make those fixes is a huge red flag that a re-architecture would do.  As you make your changes, you can also implement better test practices, such as a full battery of unit, integration, and system tests that can be ran on the test server after each change is committed.

(3) Adopt some mandatory coding standards

While it's absurd to think that you could force everyone to write their code always the same, whomever owns the site should be able to insist that all future work adheres to at least a basic level of standardization and clarity, sufficient that the code will not have to be abandoned if any particular member of the team leaves.

Documentation and comments are a good start, while clean code would be better, and a process of continuous improvement and depersonalized code ownership would be best of all.  But, even moreso than the previous, this is a management question and not a programmer question.

Oh, and just in case you're looking for the more concrete answer of "how do i test a website", the best answer is "automatically, by either adopting a framework like QUnit, buying some contractor's test software, or writing your own."

Ideally, your test mechanism would be something that is stored in the website code itself, and can be called even on the production server (when invoked locally).

Title: How to test a website?


问:
What is the best way to build a static page web site from a JSON API?
I have a JSON API that includes some discusssions. I want to build a static html site on another server, pages that are built from data on that API. I am more comfortable using Rails than Node. The API is done in Node. The idea is that I periodically call the JSON api to get the data, and dynamically build the html pages on the Rails server. This way the web pages would be super fast, wouldn't have to call the JSON API. One technology that looks like it would do the job is http://middlemanapp.com/, but I haven't used it before.

Anybody done this before and have any suggestions?

My preference is to use Rails, and Heroku.

答:
The good replacement of the JSON could be the so called websockets, they allow you sending, and receiving the messages between client and server, or two client, or two servers in a persist connection. You can also read about it on Wiki.

There are set of websocket modules for ruby: em-websocket, faye-websocket, websocket. They utilizes useful Rack, EventMachine technoligies.

Here is a document on how to use the websocket on Heroku.


问:
What intermediate representations can be used to reason about concurrency?
I am trying to better understand what would be required for a compiler to be able to make intelligent choices regarding concurrency on behalf of the programmer. I realize that there are many difficult aspects of this problem for instance:

Ensuring that there are no race conditions

Ensuring that the code to be run concurrently won't have side effects that impact the semantic meaning of the code

Deciding whether the overhead from spinning up threads is worthwhile given the degree of parallelism available in the code

My understanding is that the two major intermediate representations used in modern compilers are static single assignment for procedural and object oriented languages and continuations passing style for functional languages. Reasoning about any of the problems listed above seems difficult using these intermediate forms. Even languages that should in theory have the best chance at automatic parallelization (pure functional languages like Haskell with a guarantee of no side effects) have made limited progress on this front.

So my question is really what intermediate representations have been used to try and tackle this problem? Are there other representations that have been used in academic research that I am not aware of that are better suited to this task? Is this problem one that fundamentally has to be resolved by the compiler front end by manipulating the abstract syntax tree before compilation reaches an intermediate representation?

答:
One would assume that modeling concurrency explicitly in the intermediate representation (IR) was a necessary requirement.  So one answer would be, "any IR used for sequential programs with the addition of some concurrency operations", e.g., "fork and join", "parallel x y".   Adding these makes it possible to reason about some kinds of concurrency, but not necessarily easily.  Nor is it obvious how to ensure certain properties (data-race freeness) without going all the way to a fully functional representation (which makes it hard to model parallelism usefully).

Arguably Colored Petri Nets (CPNs) are a good choice for representing programs with concurrency. (Tokens in CPNs are "colored" [have a type] and can carry values; "transitions" into states can perform arbitrary arithmetic on incoming tokens to produce a possibly differently colored token with computed value in the "place").   If you think about places as being computed results and transitions as modelling operators (including a special one to access memory), this gives you what amounts to a data flow graph with which to model programs.  You can easily use this to give a formal interpretation to classic compiler representations such as triples [operator,input1,input2,output].

There are lots of tools to analyze such CPN graphs, including computing properties such as deadlock-freeness, boundedness of token counts in places, etc. Heirarchical CPNs let you model functions and procedures and the notion of "calls".

What these representations do not clearly do, is make it easy to reason about where one could parallelize an application.   Trivially, two subcomputations can be parallel if they side-effect no shared operands ( which is why some folks love functional programs/representations). If your program representation models a shared memory, you can model it as monolith and get the usual set of troubles about reasoning about interactions on the shared memory, including aliased addressing, etc.   One way to avoid this is to treat memory as isolated chunks with the larger program state being some (tree-like) assemblage of these; you can arguably pass these chunks around in your intermediate representation.  There is no interaction between two parallel computations if they don't share chunks (e.g., memory subtrees).

OwnerDisplayName: Samsdram


问:
Terminalogy "Controller" in MVC and "ViewController" in IOS
While studying IOS, i generally come across viewcontroller. That gives me, confusion, if this "ViewController" has to do something with controller ( in MVC ) ? But how come both "view" and "controller" are combined in this terminology. What does it actually mean ?</p>

答:
ViewController is, as the name suggests, a single object that provides both a View and a Controller. Since mobile apps tend to have much tighter interaction models than desktop or web applications, there is usually a 1:1 coupling between views and controllers, and as such not as much of a reason to separate them out.

If you have a case for multiple views that share a single controller, you should still keep the controller separate, but otherwise it is okay to have single objects that provide both roles in MVC.


问:
Deployment: Best Practices (and real practices)
One thing that I've learnt in my short dev career is that there are best practices (like TDD) and then there are actual practices that occur under pressure, or through budgetary/time constraints.

I'm working in a small PHP dev team on a project using Zend framework. The project has the potential to demand a lot of scalability, and so we are trying to establish a good development environment to promote ease of development long term. Architectural patterns/practices aside, I'm looking at trying to automate deployment, checking code quality through svn hooks, possibly even setting up a CI environment.

So I'm interested in hearing people's experience of deployment practices. I've checked other examples as they pertain to other languages - but I'm ideally looking to hear from people who have worked in a PHP/Zend environment

To make the question less vague:
What are people's experiences of using deployment systems like phpUnderControl and rSync?

答:
If you are setting up the development processes for a team, you need to make the official way to do it so easy that no one would even conceive of doing it any other way.

When the pressure is on, automated builds that run the unit tests, create the release disks, set up the QA environments just make life easier for everyone, and make it that much harder for a bug to slip through, and for bugs to appear late in the product development.


问:
How can I automatically test a large, complex spreadsheet?
So, I've inherited one of those "Engineer's Special" spreadsheets -- the kind developed by Mort the Engineer, with lots of hairy VBA and WTF, complicated calculations, and no documentation.

Fortunately, most of the primary inputs and outputs are on a single page. Maybe not enough for full test coverage, but a start.

I'd like to create a quick, poor-man's regression test framework for Excel, but I haven't quite figured out the best method.

My gut tells me to create some code that:

Has a macro that "saves" a the "main" I/O spreadsheet's values to another workbook, basically creating a user-named, value-only copy of the main input sheet. This "scenario" workbook would have, as its first tab, a list of all of the saved sheets, with metadata.

Has a separate macro that "loads" a given set of inputs from said sheets, but does not overwrite the cells used for output, headers, instructions, etc.

Has a third macro which is run from the scenario summary table. It would, in turn, load each scenario's inputs into the main workbook, compare each saved output to the current output, and record whether everything matches or not. It would run unattended until it reached a failure to match, then stop so the user can go look at the differences (which would be highlighted).

The two caveats: (1) this requires manual synching of the master sheet and scenario sheets when the design of the master changes enough to reposition/add/remove inputs or outputs, and (2) this doesn't scale well if each scenario includes inputs/outputs to test on a multitude of workbooks. Saving/loading named ranges for each I/O cell rather than entire sheets might help with both situations, but has its own drawbacks.

Has anyone come up with some other novel way to effectively regression test arbitrary spreadsheets?

答:
To (1): the layout of your scenario sheet should be independent from the layout of the master sheet. The save and load routines should do the mapping between them. So when the input areas in the master sheet changes, you don't have to change all of your scenarios sheets, you only have to change your save and load routines.

Same can be achieved for the output areas by letting the comparer map between master sheet and "expected value" sheets.

It may be also a good idea to add some safety checks especially to your "load" routine which make sure nothing in your master sheet gets accidentally overwritten when copying the scenario data into the master, and that all data is placed in the correct cells.

(2): I admit, I do not understand exactly what issue you see here, but I guess running such tests automatically will always scale much better than doing the tests manually. So better first test your performance, and optimize when you see real performance problems, not the other way round.


问:
How can I solve this potential security exploit (concerning the saving of REST resources)?
I have a File database table with the following columns:

Id (PK), Filename

And a Document database table with the following columns:

Id (PK), Name, Description, FileId (FK)

When a user wants to "save" a Document, my client-side JavaScript does it in two quick AJAX calls (in an attempt to be RESTful and save each resource individually):

Uploads the file they have selected. This will create a File record in the database, and the client will receive its Id in response.

Saves the Document with the given data (Name, FileId, etc.). This will create/update a Document record in the database.

I have a service set up that allows a user to download a file, provided they specify its Id.  However, there is some security logic in the service that checks whether a user has permission to download the file, by checking whether there is at least one database "entity" associated with it that the user has access to. For example, a Document would be one such entity. So if a user can access a particular Document (determined by some business rules - but let's just say multiple users can access the same Document), they can download its file.

This all seems fine on the surface, but there is a problem. The 2-step save process for a Document is all client-side Javascript, so a hacker could easily modify step 2 so that any arbitrary FileId is sent to the server. This would then associate that file with the Document, meaning afterwards the user will have permission to download it!

What are some ways I can solve this problem?

答:
Couple different options as I see it

Does this really need to be 2 calls from the client for 1 workflow?

Instead of returning the id by itself, return an encrypted version of the id that can be validated in the second call (say the key is stored in the users session on the server)

Response to comment:

If you want to provide a 'preview' mode, my recommendation is an action that takes a file from the client (javascript cannot access the local file system) and writes it to disk, or stores it in session on the server-side and returns a view to the user with that item embedded for confirmation. Until they 'confirm' the preview I don't see the need to write any data about the file to the database as it does not need to be persisted. By writing to disk or saving in session state (only if it's small) you avoid the user having to re-upload the file and you can re-access it and the temporary storage is cheaper than the database storage on their confirmation.

I don't have a full view of the scenario so I'm only making educated guesses as to your intent


答:
I think you need to think in terms of building blocks, rather than reading in or out.  First off add the trailing brace as follows:

```<code>for (i = 0; i < 3; i++)
 {
    for (j = 0; j < 4; j++)
    {
        cout << arr2d[i][j] << "\t";
    }
    cout << endl;
  }
</code>```

Your first block is this:

```<code>cout << arr2d[i][j] << "\t";
</code>```

It's what will get executed again and again by the for statements.

The next block is this:

```<code>for (j = 0; j < 4; j++) { <something here> }
</code>```

This is the looping function.  And the outer for block (at top) is similar.  The two blocks together can also be written like this without the braces since it's just one statement that you need to loop on, which give you another way to look at it:

```<code>for (j = 0; j < 4; j++) cout << arr2d[i][j] << "\t";
</code>```

Body:
I think you need to think in terms of building blocks, rather than reading in or out.  First off add the trailing brace as follows:

for (i = 0; i < 3; i++)
 {
    for (j = 0; j < 4; j++)
    {
        cout << arr2d[i][j] << "\t";
    }
    cout << endl;
  }

Your first block is this:

cout << arr2d[i][j] << "\t";

It's what will get executed again and again by the for statements.

The next block is this:

for (j = 0; j < 4; j++) { <something here> }

This is the looping function.  And the outer for block (at top) is similar.  The two blocks together can also be written like this without the braces since it's just one statement that you need to loop on, which give you another way to look at it:

for (j = 0; j < 4; j++) cout << arr2d[i][j] << "\t";


问:
How to publish my application as open source software?
Recently I wrote some (I hope) useful application. I would like to share it with every person on the world, making it open source. I would like to publish the source code as well as binary files (both for Windows and Linux).

I used only free tools to write my application: Code::Blocks, MinGW, gcc/g++, Linux Ubuntu/Linux Mint, Windows 7 with the license I bought. I read about different types of licences but still have some doubts. I looked into the source code of some open source software, for example, here: https://polarssl.org/aes-source-code or here: http://qt-project.org/doc/qt-5/qtnetwork-blockingfortuneclient-blockingclient-h.html.

Those files have some header, where you can find the license as a comment.

Here are my questions:

Is there any place in the internet where I can read about these things? Licensing, how to publish my code?

Should I copy the license to every file of my source code when I want to publish it? From where I can take the license to copy it? (meaning should I copy it both in *.h and *.cpp file?)

For Windows version of my application I used Visual Studio Express Edition and Qt. To make an *.exe which will run out of the box with no additional installations, I need to redistribute with my *.exe file some files from Qt and Visual (*.dll files). How and where can I check if its free to redistribute those files with my application?

Which license would be the best for my needs?

I did a little research and found that license: http://opensource.org/licenses/BSD-3-Clause. Is it 100% good for my needs, any advices?

答:
Is there any place in the internet where I can read about these things? Licensing, how to publish my code?  Sure - lots of them. You can start with the Free Software Foundation's "How to choose a license for your own work", but remember that they have a strong bias towards a certain form of software sharing.  The Open Source Initiative also has a nice list of licenses, and while they also have a bias, it's in a different direction from the FSF.

Should I copy the license to every file of my source code when I want to publish it? From where I can take the license to copy it?  That will vary depending on which license you choose.  Most licenses suggest that you include at least a single line saying that the file is covered by that license, and mentioning where (in the code base) to find the full text.

For Windows version of my application I used Visual Studio Express Edition and Qt. ... How and where can I check if its free to redistribute those files with my application?  Most development environments, including Visual Studio, are quite explicit about which of their run-time components you may or may not re-distribute with your application.  Thus, for example, the Microsoft Visual C++ 2010 Redistributable Package is a freely-redistributable set of run-time code to enable use of Visual C++ applications without needing a licensed copy of Visual Studio.

Which license would be the best for my needs? You haven't really said what your needs are, besides "shar[ing] it with every person on the world".  You haven't said whether you want those people to share their changes to your application with you and/or others (an FSF goal).  You haven't said whether you want to let those people sell your application or incorporate parts of it into applications they sell (more of a BSD/MIT goal).

But since you looked at the BSD 3-clause license and find it meets your needs, then yes, by all means, use it.  The BSD license is one of the first Free/Open Source licenses, and has stood the test of time very well.  It conveys rights to use the code in any way the receiver desires, denies them the right to claim you created their version without your permission, and holds you harmless for their use of it.


问:
How important is to initialize a variable
How important is it to initialize variables?

Does proper initializing avoid memory leaks or have performance advantages?

答:
Initializing a variable as Telastyn pointed out can prevent bugs. If the variable is a reference type, initializing it can prevent null reference errors down the line.

A variable of any type that has a non null default will take up some memory to store the default value.


问:
Violating SQL principles
I have  to write a decent size database, 1GB more or less.

I have only taken an introductory semester regarding SQL databases. During the course we learned that the relational model under SQL has no implied order and that therefore when querying we should always have a variable that sets the correspondant order in the table.

However, when doing practical work I find 'convenient' to make already ordered small, infinite number of tables.

For example, lets say that you have 5 clients and that their info will never join their data together. Is it admissible to have a potentially infinite number of tables with a table per client?

For example, I append new rows already ordered to the database. The database is already ordered. Is it admissible to make an unordered query and just assume that is implicitly ordered?

All this violates the principles that I know. My boss, who does not know about databases says that if it works it works and that speed is important. What shall answer to him?

答: I think it is always important to have enough humility to say that I'm in over my head and get professional help.</p>

Title: Violating SQL principles


答: This is what server-side state is for.  One correct way to approach this is to record, in a server-side session state collection, the recently-uploaded files' Id values, and to restrict the SaveADocument operation to using a FileId from that collection (and, of course, removing it from the collection upon success).  As a side effect, your session-cleanup logic now will have a definitive list of orphaned files, which you can delete at session cleanup.

Title: How can I solve this potential security exploit (concerning the saving of REST resources)?

Body:
I have a File database table with the following columns:

Id (PK), Filename

And a Document database table with the following columns:

Id (PK), Name, Description, FileId (FK)

When a user wants to "save" a Document, my client-side JavaScript does it in two quick AJAX calls (in an attempt to be RESTful and save each resource individually):

Uploads the file they have selected. This will create a File record in the database, and the client will receive its Id in response.

Saves the Document with the given data (Name, FileId, etc.). This will create/update a Document record in the database.

I have a service set up that allows a user to download a file, provided they specify its Id.  However, there is some security logic in the service that checks whether a user has permission to download the file, by checking whether there is at least one database "entity" associated with it that the user has access to. For example, a Document would be one such entity. So if a user can access a particular Document (determined by some business rules - but let's just say multiple users can access the same Document), they can download its file.

This all seems fine on the surface, but there is a problem. The 2-step save process for a Document is all client-side Javascript, so a hacker could easily modify step 2 so that any arbitrary FileId is sent to the server. This would then associate that file with the Document, meaning afterwards the user will have permission to download it!

What are some ways I can solve this problem?


问:
How to trace logical errors in algorithms
I am beginner in algorithms. Last year I participated in Google Code Jam. One of the major issues I faced during the competition was my code was working fine on my test cases, but when I submitted on a large number of test cases, I failed to pass them causing some logical error.

So, my question is basically how can I trace logical errors in my code in such situation where it fails to match some test cases?

答:
It's always a good idea before you begin code to first write a clear data description, evaluating the full scope of what can be in the data.  The once you have that it's much easier to get your code to work the first time, and to have it work on the data it will be presented with in the future.

You can also write a program to inspect and validate the incoming data.  This is a good step to make sure the data is what you think it is.


答:
Initializing, implies that the initial value matters.  If the initial value matters, then yes, clearly you must make sure it is initialized.  If it doesn't matter, that implies that it will get initialized later.

Unnecessary initialization causes wasted CPU cycles.  While these wasted cycles might not matter in certain programs, in other programs, every single cycle is important as speed is of primary concern.  So it's very important to understand what one's performance goals are and if variables need to be initialized or not.

Memory leaks are a completely different issue which typically involve a memory allocator function to issue and later recycle blocks of memory.  Think of a post office.  You go and ask for a mailbox.  They give you one.  You ask for another one.  They give you another one.  The rule is that when you are done using a mail box that you need to give it back.  If you forget to give it back they still think you have it, and the box can't be re-used by anyone else.  So there is a chunk of memory tied up and not being used, and this is what is referred to as a memory leak.  If you keep asking for boxes at some point you will run out of memory.  I've oversimplified this, but this is the basic idea.

Title: How important is to initialize a variable

Body:
How important is it to initialize variables?

Does proper initializing avoid memory leaks or have performance advantages?