问:
VB.Net vs C# debate
I've been in workplaces where, at the start of a project, the "Should we use VB.Net or C#" question has been raised.

Granted, it's probably less common to have to make that decision now than it was in the early days of .Net, particularly given the trend towards language convergence, but it can still be a heated debate.

So, between VB.Net and C#, Which language do you prefer and why?

答:
I'm familiar with both, but did a lot of my early programming work in VB4, VB5, and VB6. Now that both languages in .NET have gone through a few iterations and converged quite a bit in their capabilities I think the debate is downright silly, much akin to "what's your favorite color."

Personally, I like both of them for different reasons.

VB.NET

A lot of people talk about how the C# syntax is more intuitive, but that is very subjective and based heavily on what you started out knowing. I would argue that if you were completely objective VB.NET syntax is probably more intuitive if you don't assume prior knowledge in another language. For example, given the same program in C# and VB.NET which do you think would be more decipherable to someone who has no knowledge of programming. Seems pretty clear to me.

The other thing that is nice about this syntax, is that is is much more explicit about closing structures (END IF, END WHILE, NEXT X) compared to the bracketing model. It makes the code a bit more readable and often allows the compiler to be more precise in what line number exactly is causing compile errors. If you've ever gone on a missing bracket/semi-colon hunt because of a compiler error 50 lines away from the problem you know what I mean.

Also, in the VB.NET win column in my opinion is lack of ==/= as comparison/assignment operators. The rare benefits of having a distinct operator for each is never going to offset all the (sometimes) hard to discover foibles that it helps create.

Finally, I hate case sensitivity in programing languages. One of the complaints about VB is that it has so much baggage, but C# carried forward the albatross of C's case sensitivity. I have never been in a situation where I wanted two identifiers in the same scope to differ only by case. It just makes for busy work and slows me down. VB.NET gets some points over C# in this regard to me.

C#

Programmers love to be concise, which is why I think they generally favor this syntax. It just has a certain aesthetic appeal. However, from a completely practical perspective I like it because it is so similar to languages like Java, JavaScript, and C++.

Since I do a lot of web development that requires both server and client side programming, I find it easier to mentally switch between C# and JavaScript as I am frequently required to do.

Also I like the fact that, for the most part, that if I ever had to transition to doing Java or C++ programming, I would have a bit of a head start if I were using C# most of the time.

Title: VB.Net vs C# debate


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
Ability to choose own rig/chair

Ability to choose own software, withing reason IDE etc

Plenty of Tea/Coffee and Water (very important)

No stupid internet policies (no streaming etc)

Time to work on own projects

ContentLicense: CC BY-SA 2.5


问:
What are the roles of singletons, abstract classes and interfaces?
I am studying OOP in C++ and, even though I am aware of the definitions of these 3 concepts, I cannot really realize when or how to use it.

Let's use this class for the example:

```<code>class Person{
    private:
             string name;
             int age;
    public:
             Person(string p1, int p2){this->name=p1; this->age=p2;}
             ~Person(){}

             void set_name (string parameter){this->name=parameter;}
             void set_age (int parameter){this->age=parameter;}

             string get_name (){return this->name;}
             int get_age (){return this->age;}

             };
</code>```

1.Singleton

HOW does the restriction of the class to have only one object work?

CAN you design a class that would have ONLY 2 instances? Or maybe 3?

WHEN is using a singleton recommended/necessary? Is it good practice?

2.Abstract Class

As far as i know, if there's only one pure virtual function, the class becomes abstract.
So, adding

```<code>virtual void print ()=0;
</code>```

would do it, right?

WHY would you need a class whose object is not required?

3.Interface

If an interface is an abstract class in which all the methods are pure virtual functions, then

WHAT is the main difference between the 2 of them?

Thanks in advance!

答:
Most people already explained what singletons/abstract classes are. Hopefully, I'll provide a little different perspective and give some practical examples.

Singletons - When you want all calling code to use a single instance of variables, for whatever reasons, you have the following options:

Global variables - obviously no encapsulation, most of the code coupled to globals... bad

A class with all static functions - a little better than simple globals, but this design decision still leads you towards a path where code relies on global data and could be very hard to change later.  Also you can't take advantage of OO things like polymorphism if all you have is static functions

Singleton - Even though there's only one instance of the class, the actual implementation of the class doesn't have to know anything about the fact that it is global. So today you can have a class that's a singleton, tomorrow you can simply make its constructor public and let clients instantiate multiple copies.  Most client code that references the singleton wouldn't have to change and implementation of the singleton itself won't have to change. The only change is how the client code acquires singleton reference in the first place.

Of all the evil and bad options out there, if you do have a need for global data, singleton is a MUCH better approach than either of the previous two. It also allows you keep your options open if tomorrow you change your mind and decide to use inversion of control instead of having global data.

So where would you use a singleton? Here's few examples:

Logging - if you want your entire process to have a single log, you could create a log object and pass it around everywhere. But what if you have 100,000k lines of legacy application code? modify all of them?  Or you could simply introduce the following and start using it anywhere you please:

```<code>CLog::GetInstance().write( "my log message goes here" );
</code>```

Server connection cache - This was something I had to introduce in our application. Our code base, and there was a lot of it, used to connect to servers whenever it pleased. Most of the time this was ok, unless there was any kind of latency in the network.  We needed a solution and redesign of a 10 year old application wasn't really on the table.  I wrote a singleton CServerConnectionManager.  Then I searched through the code and replaced CoCreateInstanceWithAuth calls with identical signature call that invoked my class. Now after the first attempt connection was cached and the rest of the time "connect" attempts were instantaneous. Some say singletons are evil. I say they saved my butt.

For debugging, we often find global running object table to be very useful. We have some classes we would like to keep track of. They all derive from the same base class. During instantiation, they call the object table singleton and register themselves. When they are destroyed, they unregister. I can walk up to any machine, attach to a process and create a list of running objects. Been in the product for over half a decade and I never felt that we ever had a need for 2 "global" object tables.

We have some relatively complex string parser utility classes which rely on regular expressions. Regular expression classes needs to be initialized before it can perform matches. The initialization is somewhat expensive because that's when an FSM is generated based on parse string. However after that, regular expression class can be safely accessed by 100 threads because once built FSM never changes. These parser classes internally use singletons to make sure this initialization happens only once.  This significantly improved performance and never caused any problems due to "evil singletons".

Having said all this, you do need to keep in mind when and where to use singletons. 9 out of 10 times there's a better solution and by all means, you should use that instead. However, there are times when singleton is absolutely the right design choice.

Next topic... interfaces and abstract classes.  First as others have mentioned, interface IS an abstract class but it goes beyond that by enforcing that it has absolutely NO implementation. In some languages interface keyword is part of the language. In C++ we simply use abstract classes. Microsoft VC++ took one step to define this somewhere internally:

```<code>typedef struct interface;
</code>```

... so you can still use the interface keyword (it'll even be highlighted as a 'real' keyword), but as far as the actual compiler is concerned, it's just a struct.

So where would you use this? Let's go back to my example of a running object table.  Let's say the base class has...

virtual void print() = 0;

There's your abstract class. Classes that use runtime object table will all derive from the same base class. Base class contains common code for registering/unregistering. But it will never be instantiated by itself. Now I can have deriving classes (e.g. requests, listeners, client connection objects...), each one will implement print() so that when attach to the process and ask it, what is running, each object will report it's own state.

Examples of abstract classes/interfaces are countless and you definitely use (or should use) them much, much more frequently that you would use singletons.  In short, they allow you to write code that works with base types and isn't tied to actual implementation. This allows you to modify implementation later without having to change too much code.

Here's another example. Let's say I have a class that implements a logger, CLog. This class writes to the file on local disk. I start using this class in my legacy 100,000 lines of code. All over the place. Life is good until someone says, hey let's write to the database instead of a file.  Now I create new class, let's call it CDbLog and writes to the database. Can you imaging the hassle of going through 100,000 lines and changing everything from CLog to CDbLog?  Alternatively, I could have:

```<code>interface ILogger {
    virtual void write( const char* format, ... ) = 0;
};

class CLog : public ILogger { ... };

class CDbLog : public ILogger { ... };

class CLogFactory {
    ILogger* GetLog();
};
</code>```

If all of the code was using ILogger interface, all I would have to change is internal implementation of CLogFactory::GetLog(). The rest of the code would just automagically work without me having to lift a finger.

For more information on interfaces and good OO design, I would strongly recommend Uncle Bob's Agile Principles, Patterns, and Practices in C#. The book is filled with examples that use abstractions and provides plain language explanations of everything.

ContentLicense: CC BY-SA 3.0

Body:
Most people already explained what singletons/abstract classes are. Hopefully, I'll provide a little different perspective and give some practical examples.

Singletons - When you want all calling code to use a single instance of variables, for whatever reasons, you have the following options:

Global variables - obviously no encapsulation, most of the code coupled to globals... bad

A class with all static functions - a little better than simple globals, but this design decision still leads you towards a path where code relies on global data and could be very hard to change later.  Also you can't take advantage of OO things like polymorphism if all you have is static functions

Singleton - Even though there's only one instance of the class, the actual implementation of the class doesn't have to know anything about the fact that it is global. So today you can have a class that's a singleton, tomorrow you can simply make its constructor public and let clients instantiate multiple copies.  Most client code that references the singleton wouldn't have to change and implementation of the singleton itself won't have to change. The only change is how the client code acquires singleton reference in the first place.

Of all the evil and bad options out there, if you do have a need for global data, singleton is a MUCH better approach than either of the previous two. It also allows you keep your options open if tomorrow you change your mind and decide to use inversion of control instead of having global data.

So where would you use a singleton? Here's few examples:

Logging - if you want your entire process to have a single log, you could create a log object and pass it around everywhere. But what if you have 100,000k lines of legacy application code? modify all of them?  Or you could simply introduce the following and start using it anywhere you please:

CLog::GetInstance().write( "my log message goes here" );

Server connection cache - This was something I had to introduce in our application. Our code base, and there was a lot of it, used to connect to servers whenever it pleased. Most of the time this was ok, unless there was any kind of latency in the network.  We needed a solution and redesign of a 10 year old application wasn't really on the table.  I wrote a singleton CServerConnectionManager.  Then I searched through the code and replaced CoCreateInstanceWithAuth calls with identical signature call that invoked my class. Now after the first attempt connection was cached and the rest of the time "connect" attempts were instantaneous. Some say singletons are evil. I say they saved my butt.

For debugging, we often find global running object table to be very useful. We have some classes we would like to keep track of. They all derive from the same base class. During instantiation, they call the object table singleton and register themselves. When they are destroyed, they unregister. I can walk up to any machine, attach to a process and create a list of running objects. Been in the product for over half a decade and I never felt that we ever had a need for 2 "global" object tables.

We have some relatively complex string parser utility classes which rely on regular expressions. Regular expression classes needs to be initialized before it can perform matches. The initialization is somewhat expensive because that's when an FSM is generated based on parse string. However after that, regular expression class can be safely accessed by 100 threads because once built FSM never changes. These parser classes internally use singletons to make sure this initialization happens only once.  This significantly improved performance and never caused any problems due to "evil singletons".

Having said all this, you do need to keep in mind when and where to use singletons. 9 out of 10 times there's a better solution and by all means, you should use that instead. However, there are times when singleton is absolutely the right design choice.

Next topic... interfaces and abstract classes.  First as others have mentioned, interface IS an abstract class but it goes beyond that by enforcing that it has absolutely NO implementation. In some languages interface keyword is part of the language. In C++ we simply use abstract classes. Microsoft VC++ took one step to define this somewhere internally:

typedef struct interface;

... so you can still use the interface keyword (it'll even be highlighted as a 'real' keyword), but as far as the actual compiler is concerned, it's just a struct.

So where would you use this? Let's go back to my example of a running object table.  Let's say the base class has...

virtual void print() = 0;

There's your abstract class. Classes that use runtime object table will all derive from the same base class. Base class contains common code for registering/unregistering. But it will never be instantiated by itself. Now I can have deriving classes (e.g. requests, listeners, client connection objects...), each one will implement print() so that when attach to the process and ask it, what is running, each object will report it's own state.

Examples of abstract classes/interfaces are countless and you definitely use (or should use) them much, much more frequently that you would use singletons.  In short, they allow you to write code that works with base types and isn't tied to actual implementation. This allows you to modify implementation later without having to change too much code.

Here's another example. Let's say I have a class that implements a logger, CLog. This class writes to the file on local disk. I start using this class in my legacy 100,000 lines of code. All over the place. Life is good until someone says, hey let's write to the database instead of a file.  Now I create new class, let's call it CDbLog and writes to the database. Can you imaging the hassle of going through 100,000 lines and changing everything from CLog to CDbLog?  Alternatively, I could have:

interface ILogger {
    virtual void write( const char* format, ... ) = 0;
};

class CLog : public ILogger { ... };

class CDbLog : public ILogger { ... };

class CLogFactory {
    ILogger* GetLog();
};

If all of the code was using ILogger interface, all I would have to change is internal implementation of CLogFactory::GetLog(). The rest of the code would just automagically work without me having to lift a finger.

For more information on interfaces and good OO design, I would strongly recommend Uncle Bob's Agile Principles, Patterns, and Practices in C#. The book is filled with examples that use abstractions and provides plain language explanations of everything.


问:
Alternatives to the singleton pattern
I have read different opinions about the singleton pattern.
Some maintain that it should be avoided at all costs and others
that it can be be useful in certain situations.

One situation in which I use singletons is when I need a factory
(let's say an object f of type F) to create objects of a certain class A.
The factory is created once using some configuration parameters and then
is used each time an object of type A is instantiated. So every part of
the code that wants to instantiate A fetches the singleton f and create
the new instance, e.g.

```<code>F& f                   = F::instance();
boost::shared_ptr<A> a = f.createA();
</code>```

So the general my scenario is that

I need only one instance of a class either for optimization reasons (I do not need multiple factory objects) or for sharing common state (e.g. the factory knows how many instances of A it can still create)

I need a way to have access to this instance f of F in different places of the code.

I am not interested in the discussion whether this pattern is good or bad,
but assuming I want to avoid using a singleton, what other pattern can I use?

The ideas I had were (1) to get the factory object from a registry or
(2) to create the factory at some point during program start up and then
pass the factory around as a parameter.

In solution (1), the registry itself is a singleton, so I have just shifted
the problem of not using a singleton from the factory to the registry.

In case (2) I need some initial source (object) from which the factory object
comes so I am afraid that I would again fall back to another singleton
(the object that provides my factory instance).
By following back this chain of singletons I can maybe reduce the problem
to one singleton (the whole application) by which all other singletons
are directly or indirectly managed.

Would this last option (using one initial singleton that creates all other
unique objects and injects all other singletons at the right
places) be an acceptable solution?
Is this the solution that is implicitly suggested when one advises not to
use singletons, or what are other solutions, e.g. in
the example illustrated above?

EDIT

Since I think the point of my question has been misunderstood by some,
here is some more information. As explained e.g. here, the word
singleton can indicate (a) a class with a single instance object and
(b) a design pattern used to create and access such an object.

To make things clearer let us use the term unique object for (a) and
singleton pattern for (b). So, I know what the singleton pattern
and dependency injection are (BTW, lately I've been using DI heavily
to remove instances of the singleton pattern from some code I am working on).

My point is that unless the whole object graph is instantiated from
a single object living on the stack of the main method, there will always be
the need to access some unique objects through the singleton pattern.

My question is whether having the complete object graph creation and
wiring depend on the main method (e.g. through some powerful DI framework
that does not use the pattern itself) is the only
singleton-pattern free solution.

答:
The purpose of a singleton is to enforce that only one instance can ever exists within a certain realm. This means that a singleton is useful if you have strong reasons to enforce singleton behavior; in practice, this is seldom the case though, and multi-processing and multi-threading certainly blur the meaning of 'unique' - is it one instance per machine, per process, per thread, per request? And does your singleton implementation take care of race conditions?

Instead of singleton, I prefer using either of:

short-lived local instances, e.g. for a factory: typical factory classes have minimal amounts of state, if any, and there is no real reason to keep them alive after they have served their purpose; the overhead of creating and deleting classes is nothing to worry about in 99% of all real-world scenarios

passing an instance around, e.g. for a resource manager: these have to be long-lived, because loading resources is expensive and you want to keep them in memory, but there is absolutely no reason to prevent further instances from being created - who knows, maybe it will make sense to have a second resource manager a few months down the road...

The reason being that a singleton is global state in disguise, which means it introduces a high degree of coupling throughout the application - any part of your code can grab the singleton instance from anywhere with minimal effort. If you use local objects or pass instances around, you have a lot more control, and you can keep your scopes small and your dependencies narrow.

Title: Alternatives to the singleton pattern


问:
Standardized code documentation format, where is it?
I'm currently looking into API documentation generation tools and I noticed that apparently there are no efforts going on in standardization.

Javadoc style is kind of an ubiquitous convention... it is used for Java (duh), PHP (PHPDocumentor, doxygen, Stubbles), C/C++ (doxygen again)... and there is even IDE support for it even in other languages that are not java.

Even NaturalDocs which has a completely different syntax for documentation has some compatibility for it.

So my question is: are there any efforts going on in standardizing in-code documentation syntax?, which can in turn be used for documentation generators or language metadata across different languages?.

答: I am going to go out on a limb and say that there are none, and even if there was one, it would be ignored because the programming community is too diverse and opinionated to all agree on something. That being said, the JavaDoc/Doxygen family is as close as we are likely to get. We might see a few large camps develop, but that's it.</p>

ContentLicense: CC BY-SA 4.0


答:
Your second option is a fine way to go -- it's a kind of dependency injection, which is the pattern used to share state across your program when you want to avoid singletons and global variables.

You can't get around the fact that something has to create your factory. If that something happens to be the application, so be it. The important point is that your factory shouldn't care what object created it, and the objects that receive the factory shouldn't depend on where the factory came from. Don't have your objects get a pointer to the application singleton and ask it for the factory; have your application create the factory and give it to those objects that will need it.

Title: Alternatives to the singleton pattern

Body:
I have read different opinions about the singleton pattern.
Some maintain that it should be avoided at all costs and others
that it can be be useful in certain situations.

One situation in which I use singletons is when I need a factory
(let's say an object f of type F) to create objects of a certain class A.
The factory is created once using some configuration parameters and then
is used each time an object of type A is instantiated. So every part of
the code that wants to instantiate A fetches the singleton f and create
the new instance, e.g.

```<code>F& f                   = F::instance();
boost::shared_ptr<A> a = f.createA();
</code>```

So the general my scenario is that

I need only one instance of a class either for optimization reasons (I do not need multiple factory objects) or for sharing common state (e.g. the factory knows how many instances of A it can still create)

I need a way to have access to this instance f of F in different places of the code.

I am not interested in the discussion whether this pattern is good or bad,
but assuming I want to avoid using a singleton, what other pattern can I use?

The ideas I had were (1) to get the factory object from a registry or
(2) to create the factory at some point during program start up and then
pass the factory around as a parameter.

In solution (1), the registry itself is a singleton, so I have just shifted
the problem of not using a singleton from the factory to the registry.

In case (2) I need some initial source (object) from which the factory object
comes so I am afraid that I would again fall back to another singleton
(the object that provides my factory instance).
By following back this chain of singletons I can maybe reduce the problem
to one singleton (the whole application) by which all other singletons
are directly or indirectly managed.

Would this last option (using one initial singleton that creates all other
unique objects and injects all other singletons at the right
places) be an acceptable solution?
Is this the solution that is implicitly suggested when one advises not to
use singletons, or what are other solutions, e.g. in
the example illustrated above?

EDIT

Since I think the point of my question has been misunderstood by some,
here is some more information. As explained e.g. here, the word
singleton can indicate (a) a class with a single instance object and
(b) a design pattern used to create and access such an object.

To make things clearer let us use the term unique object for (a) and
singleton pattern for (b). So, I know what the singleton pattern
and dependency injection are (BTW, lately I've been using DI heavily
to remove instances of the singleton pattern from some code I am working on).

My point is that unless the whole object graph is instantiated from
a single object living on the stack of the main method, there will always be
the need to access some unique objects through the singleton pattern.

My question is whether having the complete object graph creation and
wiring depend on the main method (e.g. through some powerful DI framework
that does not use the pattern itself) is the only
singleton-pattern free solution.


问:
Are optional parameters helpful or a hindrance to application maintenance?
As stated in the title, are optional parameters, such as those used in C# helpful or are they a hindrance to application maintenance and should be avoided as they can make the code harder to understand?</p>

答: One of the problems with default parameters in C# ( I'm thinking void DoSomething(int x = 1) ) is they are constants. That means if you change the default you will have to recompile any consumers of that method call. While this is easy enough to do there are occasions where this is dangerous.</p>


问:
Is there a way to track data structure dependencies from the database, through the tiers, all the way out to a web page?
When we design applications, we generally end up with the same tiered sets of data structures:

A persistent data structure that is described using DDL and implemented as RDBMS tables and columns.

A set of domain objects that consist primarily of data structures, usually combined with business-rule level logic, that are implemented in a programming language such as Java.

A set of service layer interfaces that directly support use case implementations (which use the domain data structures as parameters), implemented as EJBs or something equivalent in another programming language.

UI screens that allow users to C reate, R etrieve, U pdate, and (maybe) D elete all manner of data structures and graphs of data structures, with numerous screens and with multiple UI widgets, all structured to support the same data structures.

But if you want to change the data structures in any of these tiers, it always seems extremely difficult to assess the impact(s) the change will have across the application. UML can help, but tracing through diagram after diagram is not a real solution to this problem. The best I have ever seen was a homespun data tracking spreadsheet document that listed all of the data structures and walked the relationships from tier-to-tier.

Is there a tool or accepted approach that makes it easy to identify a data structure in any tier and easily obtain a list of all dependent:

database table and column data structures

domain object data structures

service layer interface methods and parameter data structures

screen & UI component data structures

答:
I don't know of a general tool for such a task, but I suspect that there are specialized ones that can get you partway there, especially if you stay within a popular introspective language like Java.

I must say this is an extremely thorny problem, especially because each layer is typically written in a different language, and the tendency is to code the data structure natively in each layer, perhaps with the aid of a code generation tool. Any tool that could cut through that would have to be able to parse several languages and tease out the related data structures. To make that tractable, I would imagine that either special markers would need to be embedded in the code for the tool to find, or else each layer would be generated dynamically from a master data definition language (not necessarily a traditional DDL).


问:
Are trees organised by a "firstchild, nextsibling" structure? If not, why not?
Usually, tree data structures are organised in a way that each node contains pointers to all its children.

```<code>       +-----------------------------------------+
       |        root                             |
       | child1            child2         child3 |
       +--+------------------+----------------+--+
          |                  |                |
+---------------+    +---------------+    +---------------+
|    node1      |    |     node2     |    |     node3     |
| child1 child2 |    | child1 child2 |    | child1 child2 |
+--+---------+--+    +--+---------+--+    +--+---------+--+
   |         |          |         |          |         |
</code>```

This seems natural, but it comes with some problems. For example, when the number of child nodes varies, you need something like an array or list to manage the childs.

By using only (first)child and (next)sibling pointers instead, we get something that looks like that:

```<code>       +-------------------+
       |        root       |
       | child    sibling  +--->NULL
       +--+----------------+
          |
+----------------+    +----------------+    +----------------+
|    node1       |    |     node2      |    |     node3      |
| child  sibling +--->| child  sibling +--->| child  sibling +--->NULL
+--+-------------+    +--+-------------+    +--+-------------+
   |                     |                     |
</code>```

Oviously, this kind of structure can represent trees just as well, but it also offers some advantages. Most important is that we don't have to worry about the number of child nodes any more. When used for a parse tree, it offers a natural representation for a term like "a+b+c+d+e" without becoming a deep tree.

Do collection libraries offer tree structures like that? Do parsers use such a structure? If not, what are the reasons?

答:
I don't know of any container library that directly supports your second case, but most container libraries can easily support that scenario. For example, in C++ you could have:

```<code>class Node;  // forward reference to satisfy the compiler
typedef std::list<Node*> NodeList;
class Node : public NodeList { /* . . . */ };  // a node is also a list

Node* n = new Node;
n->push_back(new Node);
Node* tree = new Node;
tree->push_back(new Node);
tree->push_back(n);
</code>```

Parsers probably use a structure similar to this, because it efficiently supports nodes with variable numbers of items and children. I don't know for certain because I usually don't read their source code.

Body:
I don't know of any container library that directly supports your second case, but most container libraries can easily support that scenario. For example, in C++ you could have:

class Node;  // forward reference to satisfy the compiler
typedef std::list<Node*> NodeList;
class Node : public NodeList { /* . . . */ };  // a node is also a list

Node* n = new Node;
n->push_back(new Node);
Node* tree = new Node;
tree->push_back(new Node);
tree->push_back(n);

Parsers probably use a structure similar to this, because it efficiently supports nodes with variable numbers of items and children. I don't know for certain because I usually don't read their source code.


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
Gloves

This post from the Daily WTF has kept me on the right path. I'll admit to several times having started developing something where a pair of "gloves" were the appropriate solution.


问:
What is the Bible of Hashing?
Is there a Cormen-like reference on Hashes and Hashing? This particular structure has seen little attention in my CS education for some reason but I'd like to learn more as they seem to be everywhere. I know Cormen covers it but I'm looking for something more specialized and in-depth.</p>

答:
Cormen is a little out of date these days. The wikipedia page has a good collection and discussion, but the leader these days for fast, non-cryptographic data access is murmur hash.

p.s. One might argue that new bibles aren't being created anymore these days. There are just very good pages on Wikipedia and Stack Overflow. :)

Title: What is the Bible of Hashing?


答:
Trees, like lists, are "abstract data types" which can be implemented in different ways. Each way has it's advantages and disadvantages.

In the first example, the main advantage of this structure is that you can access any child in O(1). The disadvantage is that appending a child might sometimes be a little more expensive when the array has to be expanded. This cost is relatively small though. It is also one of the simplest implementation.

In the second example, the main advantage is that you always append a child in O(1). The main disadvantage is that random access to a child costs O(n). Also, it may be less interesting for huge trees for two reasons: it has a memory overhead of one object header and two pointers per node, and the nodes are randomly spread over memory which may cause a lot of swapping between the CPU cache and the memory when the tree is traversed, making this implementation less appealing for them. This is not a problem for normal trees and applications though.

One last interesting possibility which was not mentioned is to store the whole tree in a single array. This leads to more complex code, but is sometimes a very advantageous implementation in specific cases, especially for huge fixed trees, since you can spare the cost of the object header and allocate contiguous memory.

Title: Are trees organised by a "firstchild, nextsibling" structure? If not, why not?

Body:
Usually, tree data structures are organised in a way that each node contains pointers to all its children.

```<code>       +-----------------------------------------+
       |        root                             |
       | child1            child2         child3 |
       +--+------------------+----------------+--+
          |                  |                |
+---------------+    +---------------+    +---------------+
|    node1      |    |     node2     |    |     node3     |
| child1 child2 |    | child1 child2 |    | child1 child2 |
+--+---------+--+    +--+---------+--+    +--+---------+--+
   |         |          |         |          |         |
</code>```

This seems natural, but it comes with some problems. For example, when the number of child nodes varies, you need something like an array or list to manage the childs.

By using only (first)child and (next)sibling pointers instead, we get something that looks like that:

```<code>       +-------------------+
       |        root       |
       | child    sibling  +--->NULL
       +--+----------------+
          |
+----------------+    +----------------+    +----------------+
|    node1       |    |     node2      |    |     node3      |
| child  sibling +--->| child  sibling +--->| child  sibling +--->NULL
+--+-------------+    +--+-------------+    +--+-------------+
   |                     |                     |
</code>```

Oviously, this kind of structure can represent trees just as well, but it also offers some advantages. Most important is that we don't have to worry about the number of child nodes any more. When used for a parse tree, it offers a natural representation for a term like "a+b+c+d+e" without becoming a deep tree.

Do collection libraries offer tree structures like that? Do parsers use such a structure? If not, what are the reasons?


问:
Where are null values stored, or are they stored at all?
I want to learn about null values or null references.

For example I have a class called Apple and I created an instance of it.

```<code>Apple myApple = new Apple("yummy"); // The data is stored in memory
</code>```

Then I ate that apple and now it needs to be null, so I set it as null.

```<code>myApple = null;
</code>```

After this call, I forgot that I ate it and now want to check.

```<code>bool isEaten = (myApple == null);
</code>```

With this call, where is myApple referencing? Is null a special pointer value? If so, if I have 1000 null objects, do they occupy 1000 object memory space or 1000 int memory space if we think a pointer type as int?

答:
In your example myApple has the special value null (typically all zero bits), and so is referencing nothing. The object that it originally referred to is now lost on the heap. There is no way to retrieve its location. This is known as a memory leak on systems without garbage collection.

If you originally set 1000 references to null, then you have space for just 1000 references, typically 1000 * 4 bytes (on a 32-bit system, twice that on 64). If those 1000 references originally pointed to real objects, then you allocated 1000 times the size of each object, plus space for the 1000 references.

In some languages (like C and C++), pointers always point to something, even when "uninitialized". The issue is whether the address they hold is legal for your program to access. The special address zero (aka null) is deliberately not mapped into your address space, so a segmentation fault is generated by the memory management unit (MMU) when it is accessed and your program crashes. But since address zero is deliberately not mapped in, it becomes an ideal value to use to indicate that a pointer is not pointing to anything, hence its role as null. To complete the story, as you allocate memory with new or malloc(), the operating system configures the MMU to map pages of RAM into your address space and they become usable. There are still typically vast ranges of address space that are not mapped in, and so lead to segmentation faults, too.


答:
One of the cases when having the array of children is preferable is when you need random access to the children. And this usually is when the children is sorted. For example, the file-like hierarchy tree can use this for faster path search. Or DOM tag tree when index access is very natural  </p>

<p>Another example is when having the "pointers" to all children allows more convenient usage. For instance both types you described can be used when implementing tree relations with relational database. But the former (master-detail from parent to children in this case) will allow querying with general SQL for useful data, while the latter will limit you significantly.  </p>

Body:
One of the cases when having the array of children is preferable is when you need random access to the children. And this usually is when the children is sorted. For example, the file-like hierarchy tree can use this for faster path search. Or DOM tag tree when index access is very natural

Another example is when having the "pointers" to all children allows more convenient usage. For instance both types you described can be used when implementing tree relations with relational database. But the former (master-detail from parent to children in this case) will allow querying with general SQL for useful data, while the latter will limit you significantly.


答:
A pointer is simply a variable which is mostly of an integer type. It specifies a memory address where the actual object is stored.

Most languages allow to access object members via this pointer variable:

```<code>int localInt = myApple.appleInt;
</code>```

The compiler knows how to access the members of an Apple. It "follows" the pointer to myApple's address and retrieves the value of the appleInt

If you assign the null pointer to a pointer variable, you make the pointer point to no memory address. (Which makes member access impossible.)

For every pointer you need memory to hold the memory address integer value (mostly 4 Bytes on 32 bit systems, 8 bytes on 64 bit systems). This is also true for null pointers.

Title: Where are null values stored, or are they stored at all?

Body:
I want to learn about null values or null references.

For example I have a class called Apple and I created an instance of it.

```<code>Apple myApple = new Apple("yummy"); // The data is stored in memory
</code>```

Then I ate that apple and now it needs to be null, so I set it as null.

```<code>myApple = null;
</code>```

After this call, I forgot that I ate it and now want to check.

```<code>bool isEaten = (myApple == null);
</code>```

With this call, where is myApple referencing? Is null a special pointer value? If so, if I have 1000 null objects, do they occupy 1000 object memory space or 1000 int memory space if we think a pointer type as int?

Body:
A pointer is simply a variable which is mostly of an integer type. It specifies a memory address where the actual object is stored.

Most languages allow to access object members via this pointer variable:

int localInt = myApple.appleInt;

The compiler knows how to access the members of an Apple. It "follows" the pointer to myApple's address and retrieves the value of the appleInt

If you assign the null pointer to a pointer variable, you make the pointer point to no memory address. (Which makes member access impossible.)

For every pointer you need memory to hold the memory address integer value (mostly 4 Bytes on 32 bit systems, 8 bytes on 64 bit systems). This is also true for null pointers.


答: Optional parameters are basically a different way of overloading a function. So this basically comes down to: "is overloading a function bad"?</p>

Title: Are optional parameters helpful or a hindrance to application maintenance?

Body: As stated in the title, are optional parameters, such as those used in C# helpful or are they a hindrance to application maintenance and should be avoided as they can make the code harder to understand?</p>


问:
How to include database changes during application publish
I am maintaining a WinForms application, which talks to a SQL Server database. Sometimes I have to change database schema (for example to alter a sql procedure or add new one). For this purpose I have a SchemaChange.sql file, where I put the corresponding sql code.

When I create an installer for my project, the msi package is created. It contains my application, referenced assemblies, COM+ assemblies,... Alongside the msi package I provide an SchemaChange.sql file, which has to be run on the production sql server.

But sometimes I forget to add something to SchemaChange.sql file during development or I forget to execute it on production server after upgrading my application on client machines. Any advice how to automate this to avoid further problems?

答:
I can tell you what's worked for me.   There may be reasons why it does not work for you.

First, I wrote a schema diff tool.    It was based on a physical database design reporting tool I also wrote which examines a database and prints a report of all the tables, columns, relationships, indexes, constraints, etc.   The diff tool simply runs this on two database instances and reports any differences.   This diff tool allows me to detect differences between things that should be the same.

The next important piece is hygiene.  Changes are never made ad-hoc to the production database.   They are made with an SQL file which performs the "update" once we know it is safe to apply the update.   We know that because we already ran it on the pre-production instance of the database and did some testing.

How many databases you hav apart from production and pre-production is really an issue of how your project is organised, and isn't so relevant apart from to maintain the discipline of not making ad-hoc changes (apart from adding users or storage devices, for example).

The next important piece of the system is the development database.   By this I mean the database used to test code during development immediately prior to release.   This is typically shared by the developers (who may also have their own database for making private changes and experiments).

During development. every time a database change is made, update the build-from-scratch SQL and also make a stand-alone SQL file which applies just this change.

To make a release I would do this:

Create a blank database (I will call this PREV)

Apply the database setup script for the previous release

Load test data into it (perhaps data sampled from production).   This is important for correctly testing things like constraints and column types.

Apply the SQL scripts for performing the upgrade (i.e. the stand-alone files I mentioned above)

Do any release testing you need on this, but in parallel:

Create a second blank database (I will call this NEXT)

Run the install-from-scratch SQL to build he database in NEXT

Run the comparison tool to compare PREV and NEXT.   Apart from the fact that NEXT has no data, they should be identical.

If all is OK, export the data from PREV because you will need it next time (as step 3).

Following this proces means you always have two things handy:
1. A create-from-scratch script which can be used to build new database instances for new uses (e.g. for support reasons, for clients, etc.)
2. Upgrade scripts which are guaranteed to work to bring the production system to an exact match with the development and pre-production systems (to avoid unexpected differences in the databases).

To summarise using the terminology from your question, the key thing is to make sure that even the development database is only changed by running SchemaChange.sql scripts, and also to ensure that you have a sufficiently robust testing regime that your tests will tell you when this didn't happen for any reason.


答:
The answer depends on the language you're using.

C/C++

In C and C++, the keyword was NULL, and what NULL really was was 0.  It was decided that "0x0000" was never going to be a valid pointer to an object, and so that is the value which gets assigned to indicate that it is not a valid pointer.  However, it's completely arbitrary.  If you attempted to access it like a pointer, it would behave exactly like a pointer to an object which no longer exists in memory, causing a invalid pointer exception to be thrown.  The pointer itself occupies memory, but no more than an integer object would.  Hence, if you have 1000 null pointers, it is the equivalent of 1000 integers.  If some of those pointers point to valid objects, then the usage of memory would be the equivalent of 1000 integers plus the memory contained in those valid pointers.  Remember that in C or C++, if a pointer no longer points to its object, that does not imply memory has been released, so you must explicitly delete that object using dealloc (C) or delete (C++).

Java

Unlike in C and C++, in Java null is merely a keyword.  Rather than managing null like a pointer to an object, it is managed internally and treated like a literal.  This eliminated the need to tie in pointers as integer types and allows Java to abstract away pointers entirely.  However even if Java hides it better, they are still pointers, meaning 1000 null pointers still consume the equivalent of 1000 integers.  Obviously when they point to objects, much like C and C++, memory is consumed by those objects until no more pointers reference them, however unlike in C and C++, the garbage collector picks up on it on its next pass and frees up the memory, without requiring that you have to keep track of what objects are freed up and which objects are not, in most cases (unless you have reasons to weakly reference objects for example).


问:
How to go about training IComparable to a team?
I (am just a developer) am tasked with training my team on a technique or technology. I zeroed upon System Interfaces, IComparable and IEquatable to be specific. How does one go about teaching (even if it is 1 hour), what an IComparable is and where we can use it by giving them an example.

However, I am not entirely sure whether that would make my team to understand and start using IComparable.

In my project, however, I do have a Discount class and there are instances where I have to merge two lists of Discounts. Now, that would be a really good instance of where IEquatable would be helpful when I do the merge wouldn't it?

I had the following template for training.

Introduction: Why does one need IComparable? (And, I could not get an answer that I can use for teaching).

Structure of IComparable (Again, what else can I talk about other than CompareTo method).

Sample Code

Where we can use that in our project

Questions.

答:
Personally I always prefer to implement an IComparer rather than ICompare. ICompare is great in simple cases, but sometimes IComparer will give you more flexibility. One instance that springs to mind is a flight comparer I had to write, in some scenarios just being the same route was enough, in others you had to fly the same route on the same day and in a third example it needed to be the same flight.

You could use this flight example as an example, I think it's a real world solution that most people would understand.


问:
Best way to parse a file
I'm trying to find a better solution for making a parser to some of the famous file formats out there such as: EDIFACT and TRADACOMS.

If you aren't familiar with these standards then check out this example from Wikipedia:

See below for an example of an EDIFACT message used to answer to a
  product availability request:-

```<code>UNA:+.? '
UNB+IATB:1+6XPPC+LHPPC+940101:0950+1'
UNH+1+PAORES:93:1:IA'
MSG+1:45'
IFT+3+XYZCOMPANY AVAILABILITY'
ERC+A7V:1:AMD'
IFT+3+NO MORE FLIGHTS'
ODI'
TVL+240493:1000::1220+FRA+JFK+DL+400+C'
PDI++C:3+Y::3+F::1'
APD+714C:0:::6++++++6X'
TVL+240493:1740::2030+JFK+MIA+DL+081+C'
PDI++C:4'
APD+EM2:0:130::6+++++++DA'
UNT+13+1'
UNZ+1+1'
</code>```

The UNA segment is optional. If present, it specifies the special characters that are to be used to interpret the remainder of the message. There are six characters following UNA in this order:

component data element separator (: in this sample)

data element separator (+ in this sample)

decimal notification (. in this sample)

release character (? in this sample)

reserved, must be a space

segment terminator (' in this sample)

As you can see it's just some data formatted in a special way waiting to be parsed (much like XML files).

Now my system is built on PHP and I was able to create parser using regular expressions for each segment, but the problem is not everybody implements the standard perfectly.

Some suppliers tend to ignore optional segments and fields entirely. Others may choose to send more data than others. That's why I was forced to create validators for segments and fields to test if the file was correct or not.

You can imagine the nightmare of regular expressions I'm having right now. In addition each supplier needs many modifications to the regular expressions that I tend to build a parser for each supplier.

Questions:

1- Is this the best practice for parsing files (using regular expressions)?

2- Is there a better solution for parsing files (maybe there are ready made solution out there)? Will it be able to show what segment is missing or if the file is corrupted?

3- If I have to build my parser anyway what design pattern or methodology should I use?

Notes:

I read somewhere about yacc and ANTLR, but I don't know if they match my needs or not!

答:
Have you tried googling for "PHP EDIFACT"? This is one of the first results that popped up: http://code.google.com/p/edieasy/

While it may not be sufficient for your use case, you may be able to get some ideas from it. I don't like the code with its many nested for loops and conditions, but it may be a start.

Title: Best way to parse a file


答:
Most people (including you) completely misunderstand what the Singleton pattern actually is. The Singleton pattern only means that one instance of a class exist and there is some mechanism for code all over the application to get a reference to that instance.

In the GoF book, the static factory method that returns a reference to a static field was just an example how that mechanism might look like, and one with severe drawbacks. Unfortunately, everyone and their dog latched onto that mechanism and thought it was what Singleton is all about.

The alternatives you cite are in fact also Singletons, just with a different mechanism for getting the reference. (2) clearly results in too much passing around, unless you need the reference in only a few places near the root of the call stack. (1) sounds like a crude dependency injection framework - so why not use one?

The advantage is that existing DI frameworks are flexible, powerful and well-tested. They can do much more than just manage Singletons. However, to fully use their capabilities, they work best if you to structure your application in a certain way, which is not always possible: ideally, there are central objects which are acquired through the DI framework and have all their dependencies transitively populated and are then executed.

Edit:
Ultimately, everything depends on the main method anyway. But you're right: the only way to avoid the use of global/static completely is by having everything set up from the main method. Note that DI is most popular in server environments where the main method is opaque and sets up the server and application code consists basically of callbacks which are instantiated and called by the server code. But most DI frameworks also allow direct access to their central registry, e.g. Spring's ApplicationContext, for "special cases".

So basically the best thing people have come up so far is a clever combination of the two alternatives you mentioned.

Title: Alternatives to the singleton pattern


问:
Backtracking with Killer Sudoku
I'm developing a Killer Sudoku solver for a school project. I've programmed 10 human strategies showing what they are doing in order to be the most educational possible.

It can solve hard Killer Sudokus right now but my teacher proposed that I use backtracking to solve every possible grid.

I've been trying for one week searching for general resources on backtracking or resources based on Sudoku... The fact is that with Killer Sudoku, you can't just say a cell has a solution without relying on zones and on what the previously written cells imply on zones and possibilities everywhere.

What I'd like to do is something which applies all my strategies everytime it suggests a number to be more efficient and return the only solution.

But to apply strategies, we need a copy of the grid right ? So I can clone my objects totally using some methods and I can apply my strategies using another method.

What would be the structure for this function ?

PS: I've tried several times to write some code and everytime the solution returned was incorrect. (The grid can easily be checked for validity)

It was something like this :

```<code>def bt(sudoku)
  if sudoku.valid? then
    true
  else
    sudoku2 = sudoku.clone
    sudoku2.first_cell_not_solved.possibilities.each do |p|
      sudoku2.first_cell_not_solved.solution = p
    end
    sudoku2.apply_all_strategies
    if sudoku.completed?
      return sudoku.valid?
    else
      bt(sudoku2)
    end
  end
end
</code>```

答:
An alternative to cloning would be to use the memento pattern.</p>

```<code>def bt(sudoku)
  if !sudoku.valid?
    throw Exception()
  if sudoku.completed? then
    true
  else
    memento = sudoku.dump
    sudoku.first_cell_not_solved.possibilities.each do |p|
      sudoku.first_cell_not_solved.solution = p
      sudoku.apply_all_strategies
      if sudoku.valid? and bt(sudoku)
        return true
      sudoku.restore(memento)
    end
    false
  end
end
</code>```

Title: Backtracking with Killer Sudoku

Body:
An alternative to cloning would be to use the memento pattern.

def bt(sudoku)
  if !sudoku.valid?
    throw Exception()
  if sudoku.completed? then
    true
  else
    memento = sudoku.dump
    sudoku.first_cell_not_solved.possibilities.each do |p|
      sudoku.first_cell_not_solved.solution = p
      sudoku.apply_all_strategies
      if sudoku.valid? and bt(sudoku)
        return true
      sudoku.restore(memento)
    end
    false
  end
end


答: There is no magic except probably documentation as you are already doing. The thing is to keep it updated once this doc exists and make this mandatory during code review or QA. There are Enterprise Architecture tools like Mega etc. where if you set thing properly you can trace from DB to even business process. But these tools are expensive, heavy and requires dedicated architecture team to manage which may be overkill for smaller organisations.</p>

Title: Is there a way to track data structure dependencies from the database, through the tiers, all the way out to a web page?

Body:
When we design applications, we generally end up with the same tiered sets of data structures:

A persistent data structure that is described using DDL and implemented as RDBMS tables and columns.

A set of domain objects that consist primarily of data structures, usually combined with business-rule level logic, that are implemented in a programming language such as Java.

A set of service layer interfaces that directly support use case implementations (which use the domain data structures as parameters), implemented as EJBs or something equivalent in another programming language.

UI screens that allow users to C reate, R etrieve, U pdate, and (maybe) D elete all manner of data structures and graphs of data structures, with numerous screens and with multiple UI widgets, all structured to support the same data structures.

But if you want to change the data structures in any of these tiers, it always seems extremely difficult to assess the impact(s) the change will have across the application. UML can help, but tracing through diagram after diagram is not a real solution to this problem. The best I have ever seen was a homespun data tracking spreadsheet document that listed all of the data structures and walked the relationships from tier-to-tier.

Is there a tool or accepted approach that makes it easy to identify a data structure in any tier and easily obtain a list of all dependent:

database table and column data structures

domain object data structures

service layer interface methods and parameter data structures

screen & UI component data structures


问:
The Box Model: Internet Explorer vs. W3C
Today, the Internet Explorer Box Model problem is mostly a non-issue.  Most web developers place a <!DOCTYPE> tag to enforce standards compliance, and nobody really cares about supporting Internet Explorer 5.5 anymore.

However, some developers have come up with subjective, conceptual arguments in defense of the IE box model.  They've claimed that the IE box model is more "intuitive" than the W3C model, because the W3C model measures the content of the box, whereas the IE model measures the box itself:

I can see their point of view, but it's basically a subjective argument, and the most important thing is standards compliance.

However, recently I've come to prefer the IE box model for serious practical reasons.  The W3C box model makes it difficult to dynamically resize an element to the exact onscreen pixel width of another element.  The reason is that the style.width property of an element doesn't account for the total onscreen size of the element: you also need to take into account any additional border and padding.  This isn't a problem if both elements use the same CSS class - but if they have different CSS classes, this can become incredibly challenging.

Suppose we have two divs: A and B.  A is hard-coded in the html as a 400px div, whereas B is dynamically created using Javascript.  Visually, we want B to be the exact width of A.  Under the old IE Box model, this is trivial.  We simply say: B.style.width = A.style.width, or even B.style.width = A.offsetWidth + "px".

But with the W3C box model, this isn't so simple.  Now we also have to worry about style sheets.  If B has the same CSS class as A, we can just say B.style.width = A.style.width.  But if it doesn't - and we might not want it to for aesthetic reasons - we're in trouble.  Now we have to take into account the total pixels in the border and padding of both A and B.  This can be particularly difficult if the border and padding are specified in inconsistent units (a common occurrence since border is often a 1px line, whereas padding might be specified in ems).  Then we're faced with the quasi-impossible task of converting to a common unit (em to px or px to em).  All of this just to get two divs to line up exactly on screen.

So basically, the W3C box model forces us to take into account CSS border and padding issues when we set the size of an element, whereas the IE box model doesn't, since the width measures the entire size of the box (end-to-end), rather than the content of the box.  This makes it a lot easier to dynamically size elements in relation to each other.

All of this seems like a pretty powerful reason to favor the IE box-model over the W3C model (at least conceptually - of course in practice the IE box-model is dead).

Question: Why did the W3C choose this box model?  Are there some advantages of the W3C box model that I'm simply not seeing?  Or am I simply exaggerating the problem here?

答:
The choice whether to include padding and border into the width or not was arbitrary. The only thing where it mattered was building multi-column layouts. However, you should pay into account the fact that people used tables for layouts at that time anyway. So to them that concern didn't seem important enough and they considered that being able to specify the exact width that the content itself would occupy in CSS seemed  a lot more valuable.

For today's developers the situation seem totally different as they use CSS for layouts and they have to deal with CSS boxing model. Thankfully we've got an ability to override boxing rules so in most cases simple rule at the top of your stylesheet  works fabulously:

```<code>* {
    -mox-box-sizing: border-box;
    box-sizing: border-box;
}
</code>```

To quote Jeff Kaufman on the subject:

Given that the spec defined it the other way, though, the signal it would have sent to Microsoft to adopt their misinterpretation would have been bad for the web. Microsoft was already using an embrace, extend, and extinguish approach, where they intentionally made products that acted differently from competitors' in order to lock users into the Microsoft versions. They came very close to succeeding with the web: from approximately 2000 to 2005 IE was so popular that many sites designed just for it. Adopting IE's approach here then might have told Microsoft "you can do whatever you want with IE and we'll adjust the standards to make it legal".

So box model fell the victim of power-struggling between W3C and Microsoft.

Body:
The choice whether to include padding and border into the width or not was arbitrary. The only thing where it mattered was building multi-column layouts. However, you should pay into account the fact that people used tables for layouts at that time anyway. So to them that concern didn't seem important enough and they considered that being able to specify the exact width that the content itself would occupy in CSS seemed  a lot more valuable.

For today's developers the situation seem totally different as they use CSS for layouts and they have to deal with CSS boxing model. Thankfully we've got an ability to override boxing rules so in most cases simple rule at the top of your stylesheet  works fabulously:

* {
    -mox-box-sizing: border-box;
    box-sizing: border-box;
}

To quote Jeff Kaufman on the subject:

Given that the spec defined it the other way, though, the signal it would have sent to Microsoft to adopt their misinterpretation would have been bad for the web. Microsoft was already using an embrace, extend, and extinguish approach, where they intentionally made products that acted differently from competitors' in order to lock users into the Microsoft versions. They came very close to succeeding with the web: from approximately 2000 to 2005 IE was so popular that many sites designed just for it. Adopting IE's approach here then might have told Microsoft "you can do whatever you want with IE and we'll adjust the standards to make it legal".

So box model fell the victim of power-struggling between W3C and Microsoft.


问:
Company wants to write custom project management tool, rather than use third party product
At the company I work, we are really wanting to get into the agile methodology for developing software. One thing that I'm not excited about is the fact that management wants us to build a custom project management feature inside the company's Intranet.

I think this is a total waste of time. There are many great third party tools available (e.g. Axosoft OnTime) that can do everything we need, and more. For how much development time it would cost us to build our own project management module, we could buy numerous licenses for a third party product.

One concern is that, whilst we are writing code for a client, and using our custom Intranet project management module, we find bugs in the module that need fixing ASAP. That means having to stop work on the client code to fix the Intranet. That just puts shivers down my spine.

Another worry I have is lack of functionality. This custom module is going to be so basic, that it will just feel really crap to use. That might sound a bit snooty, but for goodness sake, many third party tools are so feature rich, that the idea of having to write our own tool makes feel very uneasy. In fact, I can't be bothered.

What do you guys think?

I'm going to raise this issue with my boss, since I feel it's such an important topic to talk about.

EDIT:

Thanks for the great responses, much appreciated. To summarize some of them:

Money

Naturally my boss does want to save money, by not forking out a few hundred £'s for licenses. However, for us to write a custom tool, it will take x number of days, multiplied by approx £500, which is our costs. I don't see the business value in this.

Management have mentioned that they want to sell the Intranet as a product in the future, but it's so custom to our needs (and downright basic), that in order to give it to another client, I can see us having to fork a version of the code and rebuild the majority of it anyway. So it's not like we're gaining anything there in reuse.

Features

Having our own custom module means not feature bloat - only the functionality we require will be in the product. My issue is that there are plenty of free, open-source project management tools out there with minimal features already. So even if cost is an issue, we could look into open-source. Again it all boils down to the fact that I don't see the point in writing a project management tool in this day and age. It's a bit like writing your own web browser - why?, what's the point?

Although management are asking for this tool, just because they are, it does not mean I'm going to please them and do it just because they asked for it. If something does not make sense, then I will raise it as a concern.

At the end of the day, it's the developers who write the code, it's the developers who make money for a business. Thus, as far I'm concerned, the devs have a very big role in deciding how a company should manage projects and what tools are used. "I am Spartan, argh!" :)

Hmm, I've not been able to make this question a wiki for some reason, thus I'm going to have to pick an answer to accept.

Edit:

I had a meeting with my boss today. I told about my concerns on us writing a custom tool from scratch. I even showed him OnTime 2010, plus I ran an OnTime SDK example project which showed we could write our own custom code to interact with the data and do whatever we want. I showed all the lists, features, I could think of.

But he wasn't convinced. Un-f@king-believable! :(

So we will have to write everything from scratch, knowing full well that we could just buy a tool of the shelf to do the job. There's a lot of swear words I could use right now to describe how I'm feeling!

EDIT:

Responding to recent comments:

1) A developer who says he "can't be bothered".

There were three devs in the team, including myself. One dev was full time on a client project, myself and the remaining dev were working on a big client project. That means myself and the other dev would have to work on the client project, as well as the custom management module - at the same time.

The end result was that we ended up a management module, written in ASP.NET MVC by a dev with minimal MVC experience (I was only able to provide a small chunk of time to this module, as I was full time on the big client project). It wouldn't be unfair to say it was pretty crap (no fault of the dev). So yeah, I've no shame in saying I couldn't be bothered to split my time writing a pointless management module, whilst trying to also write a system for a client that were actually going to pay us.

2) A developer who doesn't have confidence in his team to build even a simple application to be relatively polished and free of significant bugs (and this is a shop that accepts contract work?

The company did great work, we delivered good software to clients - the devs were capable, as a team, to deliver good work. You've put words in my mouth there. I did have confidence in the team, but I wasn't confident they could build client systems on time, and to quality, whilst being distracted with this custom waste of time.

3) The one everyone picked up on already, dictatorial management.

Our director was pretty set in ways - he wanted the custom module regardless of the fact there were better options. It felt like a lost situation for us. Didn't feel great knowing that he didn't care what alternatives were available.

EDIT:

To put more context on the situation at the time - our boss wanted us to write the client app and the management module at the same time. They also wanted us to actually use the management module (user stories, tasks, etc) whilst it was being built i.e. dog fooding, with tasks related to the client project.

So imagine building TFS, and developing a new version of Visual Studio, but using the in-development TFS to store your work items, user stories, notes, etc relating to the Visual Studio development project. Not cool.

答:
As I read the post, I intuited the correct course of action for myself.

As I finished the post, my intuition was confirmed, along with some other facts.

My thoughts are that you should acknowledge that the intranet will also need rebuilding.  This was confirmed, when you said that management have a view to sell the intranet, in the future.

I am interested in Agile, along with UML.  From your attitude, I would guess that you are not in favour of UML, or feature-driven development.  If you were, it might occur to you that the management view is eminently sensible and achievable, under the right process.

Your attitude towards your bosses is appalling.  That line about 'just because they asked for it...'.  It's not something that I would put up with although, it doesn't sound as though you are treated as a stakeholder (i.e. somebody that has an interest, or gets an opinion).

I am looking to develop a system to manage an iterative development process.  With regard to task management, process management and billing, it's perfectly obvious that a custom tool is  required. Your bosses may have the same view, but have failed to share any of it with you.

Why pay for a single feature, that you do not need, that does not reflect your business?

My suggestion:

get your bosses to consider that the intranet will require investment, in order to become commercially viable;

consider the intranet rebuild as part of the requirement of delivering PM features; then

Agile the whole thing, which is what your job; but, above all

stop bitching and whining!  Your negativity isn't what they pay you for.  They are paid to be management, not you.

They steer, you row.


答:
Your manager is either playing with other people's money or he has more of his own than he knows what to do with. You did the right thing by informing him of other options and giving insight into the pros and cons, but you are not in a position to make a decision.

Since building your own is inevitable, why don't you take the opportunity to build something that may make your life easier in areas you don't enjoy? There has to be some task that you can automate or integrate with another system.

I'd rather spend 10hrs of comapany time writing an app that did my expense reports than 1 hour writing the report myself. Programming is what I prefer. Obviously, it's not the best use of company time, but that decision is out of you hands. Make the best of it.

Title: Company wants to write custom project management tool, rather than use third party product

Body:
At the company I work, we are really wanting to get into the agile methodology for developing software. One thing that I'm not excited about is the fact that management wants us to build a custom project management feature inside the company's Intranet.

I think this is a total waste of time. There are many great third party tools available (e.g. Axosoft OnTime) that can do everything we need, and more. For how much development time it would cost us to build our own project management module, we could buy numerous licenses for a third party product.

One concern is that, whilst we are writing code for a client, and using our custom Intranet project management module, we find bugs in the module that need fixing ASAP. That means having to stop work on the client code to fix the Intranet. That just puts shivers down my spine.

Another worry I have is lack of functionality. This custom module is going to be so basic, that it will just feel really crap to use. That might sound a bit snooty, but for goodness sake, many third party tools are so feature rich, that the idea of having to write our own tool makes feel very uneasy. In fact, I can't be bothered.

What do you guys think?

I'm going to raise this issue with my boss, since I feel it's such an important topic to talk about.

EDIT:

Thanks for the great responses, much appreciated. To summarize some of them:

Money

Naturally my boss does want to save money, by not forking out a few hundred £'s for licenses. However, for us to write a custom tool, it will take x number of days, multiplied by approx £500, which is our costs. I don't see the business value in this.

Management have mentioned that they want to sell the Intranet as a product in the future, but it's so custom to our needs (and downright basic), that in order to give it to another client, I can see us having to fork a version of the code and rebuild the majority of it anyway. So it's not like we're gaining anything there in reuse.

Features

Having our own custom module means not feature bloat - only the functionality we require will be in the product. My issue is that there are plenty of free, open-source project management tools out there with minimal features already. So even if cost is an issue, we could look into open-source. Again it all boils down to the fact that I don't see the point in writing a project management tool in this day and age. It's a bit like writing your own web browser - why?, what's the point?

Although management are asking for this tool, just because they are, it does not mean I'm going to please them and do it just because they asked for it. If something does not make sense, then I will raise it as a concern.

At the end of the day, it's the developers who write the code, it's the developers who make money for a business. Thus, as far I'm concerned, the devs have a very big role in deciding how a company should manage projects and what tools are used. "I am Spartan, argh!" :)

Hmm, I've not been able to make this question a wiki for some reason, thus I'm going to have to pick an answer to accept.

Edit:

I had a meeting with my boss today. I told about my concerns on us writing a custom tool from scratch. I even showed him OnTime 2010, plus I ran an OnTime SDK example project which showed we could write our own custom code to interact with the data and do whatever we want. I showed all the lists, features, I could think of.

But he wasn't convinced. Un-f@king-believable! :(

So we will have to write everything from scratch, knowing full well that we could just buy a tool of the shelf to do the job. There's a lot of swear words I could use right now to describe how I'm feeling!

EDIT:

Responding to recent comments:

1) A developer who says he "can't be bothered".

There were three devs in the team, including myself. One dev was full time on a client project, myself and the remaining dev were working on a big client project. That means myself and the other dev would have to work on the client project, as well as the custom management module - at the same time.

The end result was that we ended up a management module, written in ASP.NET MVC by a dev with minimal MVC experience (I was only able to provide a small chunk of time to this module, as I was full time on the big client project). It wouldn't be unfair to say it was pretty crap (no fault of the dev). So yeah, I've no shame in saying I couldn't be bothered to split my time writing a pointless management module, whilst trying to also write a system for a client that were actually going to pay us.

2) A developer who doesn't have confidence in his team to build even a simple application to be relatively polished and free of significant bugs (and this is a shop that accepts contract work?

The company did great work, we delivered good software to clients - the devs were capable, as a team, to deliver good work. You've put words in my mouth there. I did have confidence in the team, but I wasn't confident they could build client systems on time, and to quality, whilst being distracted with this custom waste of time.

3) The one everyone picked up on already, dictatorial management.

Our director was pretty set in ways - he wanted the custom module regardless of the fact there were better options. It felt like a lost situation for us. Didn't feel great knowing that he didn't care what alternatives were available.

EDIT:

To put more context on the situation at the time - our boss wanted us to write the client app and the management module at the same time. They also wanted us to actually use the management module (user stories, tasks, etc) whilst it was being built i.e. dog fooding, with tasks related to the client project.

So imagine building TFS, and developing a new version of Visual Studio, but using the in-development TFS to store your work items, user stories, notes, etc relating to the Visual Studio development project. Not cool.


问:
How to set up a one-man research in the difference between BDD and Waterfall?
Earlier, I asked a question about how to measure the quality of a project. The outcome of that question was that the quality of the project can be divided into two parts:

Internal quality (code quality, measurable by code quality metrics)

External quality (Acceptance test, how well the software meets the requirements)

So based on that, I want to set up some research and validate the outcome of the project. The problem is, I will conduct this research on my own, so it's not possible to run the project once in BDD style and the other one in waterfall by myself. It's also not possible to compare BDD and waterfall projects on a larger scale, due to the fact that there are not enough BDD projects that can be measured because of the age of BDD.

So, my question is: did anybody face this problem? How could I execute my experiment in such a way that it is of scientific value?

答:
The real value of BDD is in discovering the tricky situations where scenarios aren't obvious - the unknown unknowns of a project.

Since every project involves doing something new (otherwise you'd be able to just buy it off the shelf or use open-source) there are usually a few of these discoveries. They're the thing which take up the most time on projects. ("If a project has no risks, don't do it" - Waltzing with Bears).

I therefore despair of ever comparing one project to another, especially if you use BDD to help you make those discoveries, because they'll be radically different for each project - and if you try to redo a project, you'll have found all the discoveries already and be biased accordingly. (Those discoveries are why Waterfall doesn't work so well, by the way.)

Instead, I'd ask the main stakeholders how happy they were with the internal and external quality of the software they got from a bunch of BDD and Waterfall projects on a scale of 1 to 10, and compare the results. That's about as objective as you're likely to be able to get, and should work across multiple projects.


答:
Well since Yacc/Bison+Flex/Lex got mentioned, I might as well throw in one of the other major alternatives: parser combinators.  These are popular in functional programming like with Haskell, but if you can interface to C code you can use them and, what do you know, somebody wrote one for PHP too.  (I have no experience with that particular implementation, but if it works like most of them, it should be pretty nice.)

The general concept is that you start with a set of small, easy to define parsers, usually tokenizers.  Like you'd have one parser function for each of the 6 data elements you mentioned.  Then you use combinators (functions that combine functions) to make larger parsers that grab larger elements.  Like an optional segment would be the optional combinator operating on the segment parser.

Not sure how well it works in PHP, but it's a fun way to write a parser and I very much enjoy using them in other languages.

Title: Best way to parse a file

Body:
I'm trying to find a better solution for making a parser to some of the famous file formats out there such as: EDIFACT and TRADACOMS.

If you aren't familiar with these standards then check out this example from Wikipedia:

See below for an example of an EDIFACT message used to answer to a
  product availability request:-

```<code>UNA:+.? '
UNB+IATB:1+6XPPC+LHPPC+940101:0950+1'
UNH+1+PAORES:93:1:IA'
MSG+1:45'
IFT+3+XYZCOMPANY AVAILABILITY'
ERC+A7V:1:AMD'
IFT+3+NO MORE FLIGHTS'
ODI'
TVL+240493:1000::1220+FRA+JFK+DL+400+C'
PDI++C:3+Y::3+F::1'
APD+714C:0:::6++++++6X'
TVL+240493:1740::2030+JFK+MIA+DL+081+C'
PDI++C:4'
APD+EM2:0:130::6+++++++DA'
UNT+13+1'
UNZ+1+1'
</code>```

The UNA segment is optional. If present, it specifies the special characters that are to be used to interpret the remainder of the message. There are six characters following UNA in this order:

component data element separator (: in this sample)

data element separator (+ in this sample)

decimal notification (. in this sample)

release character (? in this sample)

reserved, must be a space

segment terminator (' in this sample)

As you can see it's just some data formatted in a special way waiting to be parsed (much like XML files).

Now my system is built on PHP and I was able to create parser using regular expressions for each segment, but the problem is not everybody implements the standard perfectly.

Some suppliers tend to ignore optional segments and fields entirely. Others may choose to send more data than others. That's why I was forced to create validators for segments and fields to test if the file was correct or not.

You can imagine the nightmare of regular expressions I'm having right now. In addition each supplier needs many modifications to the regular expressions that I tend to build a parser for each supplier.

Questions:

1- Is this the best practice for parsing files (using regular expressions)?

2- Is there a better solution for parsing files (maybe there are ready made solution out there)? Will it be able to show what segment is missing or if the file is corrupted?

3- If I have to build my parser anyway what design pattern or methodology should I use?

Notes:

I read somewhere about yacc and ANTLR, but I don't know if they match my needs or not!


问:
Where would I typically use a Deque in production software?
I'm fairly familiar with where to use Stacks, Queues, and Trees in software applications but I've never used a Deque (Double Ended Queue) before. Where would I typically encounter them in the wild? Would it be in the same places as a Queue but with extra gribbilies?</p>

答: One way a deque is used is to "age" items.  It is typically used as an undo or history feature.  A new action is inserted into the deque.  The oldest items are at the front.  A limit on the size of the deque forces the items at the front to be removed at some point as new items are inserted (aging the oldest items).  It then provides a fast way to access both ends of the structure because you instantly know the oldest and the newest items to either remove the front and commit the oldest action in O(1) or undo in O(1) time.</p>


答:
I'm purely going on what I read here. Why don't you compare BDD to TDD? Take a group of first year CS majors and compare their ability to use unit testing with and without BDD. Do they develop a better understanding of the process?

There is merit in trying to get some data on agile to waterfall methods, but that's beyond a graduate thesis IMHO.

Title: How to set up a one-man research in the difference between BDD and Waterfall?

Body:
Earlier, I asked a question about how to measure the quality of a project. The outcome of that question was that the quality of the project can be divided into two parts:

Internal quality (code quality, measurable by code quality metrics)

External quality (Acceptance test, how well the software meets the requirements)

So based on that, I want to set up some research and validate the outcome of the project. The problem is, I will conduct this research on my own, so it's not possible to run the project once in BDD style and the other one in waterfall by myself. It's also not possible to compare BDD and waterfall projects on a larger scale, due to the fact that there are not enough BDD projects that can be measured because of the age of BDD.

So, my question is: did anybody face this problem? How could I execute my experiment in such a way that it is of scientific value?


问:
CSV file generation using Java
We have a requirement in our project to generate a big CSV file every 2 hours using a Java program.

This file will have around 60,000 lines (around 120 characters per line). I am not sure about the size yet.

I would like to know if I would run into any memory issues because I will open the file using FileWriter and then keep writing and then finally close the file.

Should I worry about the size of the file? If yes, are there any other good techniques to write into a big file in Java other than using FileWriter?

We are using Java 5.

答: No, you shouldn't. The point of a file is to store things outside random access memory; the FileWriter's size is constant, and likely to be pretty small, all things considered, even if it's a buffered FileWriter. The constant rewriting might cause I/O load or CPU spikes, but almost certainly not memory shortage. </p>

Title: CSV file generation using Java


答:
As Killian Foth wrote it, you should have no problem at all, 60000 lines is not at all that big. I just wanted to suggest you to use any of the free CSV parsers provided here under the "Commons CSV" initiative at
http://commons.apache.org/csv/ instead of writing your own implementation.

I've used Super CSV for a few projects and I certainly did not have any problem with it.

Title: CSV file generation using Java

Body:
We have a requirement in our project to generate a big CSV file every 2 hours using a Java program.

This file will have around 60,000 lines (around 120 characters per line). I am not sure about the size yet.

I would like to know if I would run into any memory issues because I will open the file using FileWriter and then keep writing and then finally close the file.

Should I worry about the size of the file? If yes, are there any other good techniques to write into a big file in Java other than using FileWriter?

We are using Java 5.


答:
You might consider using BufferedWriter, though that probably won't help significantly with performance, it's a best practice in any case, since I imagine the number of lines won't always be 60,000.

Have you considered zipping the file afterwards?  If you intend on having a lot of these files laying around, might be in your best interest to zip it up after it's been written to, especially if you're going to be creating these files once every couple hours.

For what concerns memory, you probably have nothing to worry about unless you're working on a system with very little memory, in which case you should use BufferedWriter and explicitly set the buffer size.

Title: CSV file generation using Java


答:
Do not use FileWriter. Not because of performance concerns (Java's IO classes do not keep everything in memory, ut 60k lines is nothing even if they did), but because it does not allow you to choose the character encoding. It will implicitly use the platform default encoding, which means text outside ASCII can get corrupted.

Instead, use an OutputStreamWriter wrapping a FileOutputStream. Or, even better, a CSV library, which should handle all these issues.

Title: CSV file generation using Java


答:
Excellent question. I can’t remember our CS 102 course mentioning a single application for the double-ended queue.

To this day, the only application I know is the work-stealing scheduler mentioned in the Wikipedia article.

It works essentially as follows:

In a normal, single-threaded procedural model, every function call pushes an activation record on a so-called call stack. An activation record contains the local variables and parameters of that call. Once the call to the method is completed (“returns”), the last activation record is popped from the call stack.

This is particularly important because that’s how recursion is implemented: the structure of the recursion is represented in the current state of the call stack.

When parallelising a recursive algorithm, we can exploit this property by replacing the call stack with a call queue. Every thread in the computation gets its own call queue and pushes and pops activation records like in a sequential execution.

But once a thread has finished its work (= its call queue is empty), it steals work from another thread by removing an activation record from that thread’s call queue by removing from the “wrong” end.

Basically, the call queue acts as two call stacks which now serve two threads.

Title: Where would I typically use a Deque in production software?

Body: I'm fairly familiar with where to use Stacks, Queues, and Trees in software applications but I've never used a Deque (Double Ended Queue) before. Where would I typically encounter them in the wild? Would it be in the same places as a Queue but with extra gribbilies?</p>


答: Simple, never make changes to a database in any way except through a source controlled script.  If you make changes using the GUI you are likely to forget them. If you write a script, it is code, that you save in your source control just like any other code. So basically, stop treating database changes as if they aren't code.</p>

Title: How to include database changes during application publish

Body:
I am maintaining a WinForms application, which talks to a SQL Server database. Sometimes I have to change database schema (for example to alter a sql procedure or add new one). For this purpose I have a SchemaChange.sql file, where I put the corresponding sql code.

When I create an installer for my project, the msi package is created. It contains my application, referenced assemblies, COM+ assemblies,... Alongside the msi package I provide an SchemaChange.sql file, which has to be run on the production sql server.

But sometimes I forget to add something to SchemaChange.sql file during development or I forget to execute it on production server after upgrading my application on client machines. Any advice how to automate this to avoid further problems?


问:
Would you show your production code to candidates at the interview?
I have seen this happen multiple times:

The candidate likes the company, succeeds at the interview. Then comes to work and at the end of the first day he is sure the codebase/project is not what he would like to spend time with. So he leaves quickly.

I think that introducing candidates to the codebase at the interview could potentially solve this problem. Maybe even better: mixing this with interview questions like "how would you improve this part of the code?" This way, it would be obvious if the candidate is a "good fit for the codebase".

Have you seen this approach applied anywhere? Would you show your own codebase to the candidates at the interview: if they asked/as part of the interview process?

答: as long as your not violating those NDA's I think it would be a Good Thing(TM). This way you get to size up the candidate and the candidate gets to size up you.</p>


答:
I think rrufai's 2nd option might be the best one to pursue.  However, I would change it up a bit.

Find some mid to senior level programming classes and split the students into two groups - waterfall and BDD.  Depending upon the size of the class, you could easily have multiple teams for each approach.

Next, take specific challenges from Google's CodeJam project.  Assign the teams so that you have at least one waterfall and one BDD team per challenge.  Add additional requirements such as documentation, progress indicators, tracing / logging, etc... to increase the number of features that have to be designed and built into the project.

The benefit of using the Jams is that you have a built in validation for their code.  You'll have to determine the evaluation criteria for the additional requirements.

Ideally, you'll have each team address a few of the challenges in their assigned style.  Then you can switch design methodologies and have them address a few more challenges.


答:
Waterfall is an ALM, BDD-1/BDD-2 is a method for ongoing acceptance testing they way TDD is a method for ongoing unit testing.

The two cover different aspects and are not mutually exclusive.

E.g. You could any of these ALMs {Waterfall, UP, SCRUM} with or without BDD.


问:
Which user-story estimation technique is better?
I found two techniques for estimating user stories:

by the size of the story, which is unit-less

by the time estimate, which is measured by days

The first uses relative comparison between stories to infer time, and it should be independent on developer experience, while the second depends on developer experience.

I tried the first which is good, but I believe the second is more developer-friendly, and I want to see the pros and cons of each of them from practical experience. Any idea?

答:
If you estimate in terms of hours, and run over or under, what does that say about your other estimates?  How do you then adjust the schedule?  Everything has to shift, and it's ugly.

If you estimate in terms of complexity, there is no over and under.  It's really just a case of saying this seems more complex than that, and about the same as the other thing.  You can then build a track record on how much effort something of that relative complexity takes.  This is one of the basic premises for time-boxing in Scrum.

If you are wrong about the complexity of an item, and something that seemed simple turns out to be complex, you can adjust it without serious repercussions on other estimates.