答:
See also:

Lower-bounded wildcards

the answers to the question java generics super keyword on Stackoverflow.

A digression. Feel free to skip.

For programmers who are also familiar with C#, a similar feature exists:

Covariance and Contravariance in Generics

The terms, covariance and contravariance, can be traced back to the early discussions coming from the Liskov substitution principle (LSP).

The design goal of lower-bounded wildcard (LBWC) is to ensure the type safety of the following piece of code.

(This is just one example; one of the very simple example among others.)

```<code>List<? super RationalNumber> containerOne = new ArrayList<RationalNumber>();
List<? super RationalNumber> containerTwo = new ArrayList<Number>();
List<? super RationalNumber> containerThree = new ArrayList<Object>();

RationalNumber itemValue = new RationalNumber(22, 7);

containerOne.add(itemValue);
containerTwo.add(itemValue);
containerThree.add(itemValue);
</code>```

In short, LBWC allows the "handles" - generic classes having an LBWC (containerOne, containerTwo, containerThree in the above sample) to:

Be assigned instances of the generic class (of type parameter T) whenever it is known that RationalNumber can be safely up-cast to T.

Now, we use this knowledge and try to answer the question: can we pass in a Number to such a "handle" - a generic class having an LBWC of RationalNumber?

Given that

It is valid to assign an instance of new List<RationalNumber>() to a handle of List<? super RationalNumber> varGeneric.

Of course it is valid to do something entirely different; but the design of LBWC is that this is the situation that it needs to deal with.

We obtain this corollary question:

Can we call new List<RationalNumber>().add(new Number(...)) ?

Of course not.

Seeing that it is LBWC's design goal to prevent this from happening, one can derive this conclusion:

If LBWC is designed to be enforceable at all (by the compiler, or language police), it must prevent this assignment (passing in a Number for a type ? for which the LBWC is RationalNumber) from happening.

This answers the question from a design perspective. The matter of enforcement can only be answered by senior members of the community who are familiar with the construction of the Java language and its compiler tools. Comments from the general crowd will only provide speculations, or "hypotheses" or "theories".

Title: Understanding JAVA generic keyword 'super'

Body:
Recently some people said that I was wrong when I explained why one cannot insert a Number object into a list declared as List<? super RationalNumber>.
(This assumes that RationalNumber is a subclass of Number)

My explanation was that in List<? super RationalNumber> the <? super RationalNumber> stands for an unknown super class of RationalNumber. This means that <? super RationalNumber> indicates that a valid object for List<? super RationalNumber> is an object that extends an unknown super class of RationalNumber.

Since an unknown super class of RationalNumber is really unknown (e.g. it can be an interface X instead of Number), there is not guarantee that Number is a sub-class of X i.e. implements X, so Number is not a valid substitution of <? super RationalNumber>.

What is wrong with this explanation?
Edit: Note that I am asking for what wrong with the way I explain, my explanation. Not another explanation for the original question.

Thanks.

Body:
See also:

Lower-bounded wildcards

the answers to the question java generics super keyword on Stackoverflow.

A digression. Feel free to skip.

For programmers who are also familiar with C#, a similar feature exists:

Covariance and Contravariance in Generics

The terms, covariance and contravariance, can be traced back to the early discussions coming from the Liskov substitution principle (LSP).

The design goal of lower-bounded wildcard (LBWC) is to ensure the type safety of the following piece of code.

(This is just one example; one of the very simple example among others.)

List<? super RationalNumber> containerOne = new ArrayList<RationalNumber>();
List<? super RationalNumber> containerTwo = new ArrayList<Number>();
List<? super RationalNumber> containerThree = new ArrayList<Object>();

RationalNumber itemValue = new RationalNumber(22, 7);

containerOne.add(itemValue);
containerTwo.add(itemValue);
containerThree.add(itemValue);

In short, LBWC allows the "handles" - generic classes having an LBWC (containerOne, containerTwo, containerThree in the above sample) to:

Be assigned instances of the generic class (of type parameter T) whenever it is known that RationalNumber can be safely up-cast to T.

Now, we use this knowledge and try to answer the question: can we pass in a Number to such a "handle" - a generic class having an LBWC of RationalNumber?

Given that

It is valid to assign an instance of new List<RationalNumber>() to a handle of List<? super RationalNumber> varGeneric.

Of course it is valid to do something entirely different; but the design of LBWC is that this is the situation that it needs to deal with.

We obtain this corollary question:

Can we call new List<RationalNumber>().add(new Number(...)) ?

Of course not.

Seeing that it is LBWC's design goal to prevent this from happening, one can derive this conclusion:

If LBWC is designed to be enforceable at all (by the compiler, or language police), it must prevent this assignment (passing in a Number for a type ? for which the LBWC is RationalNumber) from happening.

This answers the question from a design perspective. The matter of enforcement can only be answered by senior members of the community who are familiar with the construction of the Java language and its compiler tools. Comments from the general crowd will only provide speculations, or "hypotheses" or "theories".


问:
Freeing Memory: Observer Pattern?
I am building a scientific application in matlab which handles several hundred large matrices (large as in 'very few of these will fit into ram'). Each matrix is contained within a dedicated object to handle its metadata (the property's name is .data).

I use the getter method to load the data from file into ram as soon as it is needed.

How do I decide when to unload? Most access to the object's data will be bundled, thus I don't want to unload every time I am done with getting data. Furthermore, I might need to use one or two more often than others. I do not think I can solve this within each object, so I thought I could implement a public function to clear the matrix from ram, called by an external object that decides when (and possibly, which) object is too much right now.

Does this make sense or is it a recipe for disaster? Does this count as observer, or is there something else I could use? How to identify 'good' decision criteria?

Thanks!

答:
I can try to answer your question on a generic level.

You can create a centralized repository object which contains all currently loaded matrix objects and also records accesses to them. It loads the matrix objects on first access and stores them internally. All requests for these matrix objects must go through this repository object to record them correctly.

Then, the repository uses an aging algorithm such as FIFO or LRU to decide which matrix objects to unload. Once it reaches some defined threshold (such as max memory size), it finds the next candidate for removal using the selected algorithm and then unloads it.

You can tweak the threshold and the algorithm as per your requirements and the configuration of the system.

ContentLicense: CC BY-SA 3.0

Title: Freeing Memory: Observer Pattern?


问:
Charles Barkley syndrome
Charles Barkley was an excellent basketball player, a hall of fame, and a dream team member.  He played for the 76ers, Suns, and Rockets.  Yet he never won an NBA championship.  Some might argue this was because he was never surrounded by other players of his caliber, and in the NBA, you can't win on your own.

So what does this have to do with programming?

How many of you out there feel like Sir Charles?  Leading your team in every category, KLOCs, bugs fixed, systems configured...  Always the one pushing for improvements, upgrading systems, negotiating with customers...  Feeling like you are carrying the team.  Anger just under the surface.

Only to retire eventually, without "the ring"1.

1: Keep in mind, Charles never blamed his team.  He just performed at his best.

答:
I have had this, but only during my non-programming related job during university but I don't think it would matter too much. It is obvious that there is always going to be one person who is better than everyone else: Its impossible to find a dev team of 10 people who have equal skills. And why would you want to? If everyone has equal skills, then no one will learn anything.

I only entered the world of work 2 years ago, but I have used the smarter people in my team to learn and to expand my own knowledge and I would hope that by learning from them, I can catch them up and take away some of the things they are better at. If one person has to carry the team, I would hope it would be to a better place where the whole team improve to (nearer) the standard of the better person. Its a big responsibility but one that is important in any dev team

ContentLicense: CC BY-SA 2.5

Title: Charles Barkley syndrome


问:
Is serialization better done in instance methods or static methods
Say I have a class workStockItem, that I wish to serialize.

Which is the better style?

using a static method

or

using a non-static method (maybe even implemented as a property as seen below)

Example implementations:

```<code>internal static byte[] serialiaze(workStockItem toSer)
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();
        formatter.Serialize(stream, toSer);
        return stream.ToArray();
    }

internal byte[] binaryRepresentation
    {
        get
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, this);
            return stream.ToArray();
        }
    }
</code>```

Again:

Which is better style and why?

答:
tl;dr

I suggest static methods, or even instance methods can be alright depending on the objects you're working with and how long lived they are as well as how stateful they are.

Do not use properties for this. Properties should be as idempotent as possible (repeated access should return the same result constantly). If A property needs to execute logic to divine its state, that's not always terrible, but properties should never be changing state on a Get.

Usually when you're dealing with an underlying set of data to deserialize something you'll have a current position in that set, and the act of deserializing will move that position thus causing a Get to change state.

I once wrote a bunch of binary serialization for some simple objects we had, and found it quite helpful to just make the methods extension methods on the BinaryReader and BinaryWriter classes. If you look at these classes, they already have methods for turning binary data into data types with ReadInt and ReadString etc, so the static methods relied on these to reconstruct the objects.

It as as such:

```<code>public class FunnyAnimal
{
    public int NumberOfLegs { get; set; }
    public string Name { get; set; }
    public Tuple<int, int> EarHearingSensitivity { get; set; }
}

public static class BinaryWriterExtensions
{
    public FunnyAnimal WriteFunnyAnimal(this BinaryWriter writer, FunnyAnimal animalToBeWritten)
    {
        writer.WriteInt(animalToBeWritten.NumberOfLegs);
        writer.WrinteString(animalToBeWritten.Name);
        writer.WriteInt(animalToBeWritten.EarHearingSensitivity.Item1);
        writer.WriteInt(animalToBeWritten.EarHearingSensitivity.Item2);
    }
}

public static class BinaryReaderExtensions
{
    public FunnyAnimal ReadFunnyAnimal(this BinaryReader reader)
    {
        return new FunnyAnimal()
        {
            NumberOfLegs = reader.ReadInt(),
            Name = reader.ReadString(),
            EarHearingSensitivity = Tuple.Create(reader.ReadInt(), reader.ReadInt())
        };
    }
}
</code>```

Then the use is:

```<code>//To write it out to a stream
using (var writer = new BinaryWriter(someUnderlyingStreamToWriteTo))
{
    writer.WriteFunnyAnimal(yourFunnyAnimalObject);
}

//To read it in from a stream
FunnyAnimal deserializedFunnyAnimal = null;
using (var reader = new BinaryReader(someUnderlyingStreamToReadFrom))
{
    deserializedFunnyAnimal = reader.ReadFunnyAnimal();
}
</code>```

The same approach could be applied to any type of serializer you're working with, if you're just using straight BinaryFormatter you can make your extensions on a MemoryStream and make the methods utilize a BinaryFormatter to read and write from the stream, but the use is then clear and simple, construct a MemoryStream and ReadFunnyAnimal or WriteFunnyAnimal on it, and the extension methods will create and operate the BinaryFormatter

Last thoughts

When dealing with binary serialization/deserialization you'll find the most convenient stream underlying a lot of times may just be a MemoryStream with an array backing it so you can just grab the byte array when you're done, unless you have a file or other resource you're specifically serializing across.

If you have complex objects inside that need serializing, this technique is helpful because the implementation for the writer and reader extensions will have access to the reader/writer so the extension methods for your embedded complex objects will also be in scope to be used as:

```<code>return new FunnyAnimal() { ComplexTailMember = reader.ReadTail(); }
</code>```

Additionally it's worth recognizing when dealing with serialization/deserialization implementations who's going to own the stream. Your extensions shouldn't own it in a sense that they should not open/move/dispose of it after they're done, rather that should be on the ownus of the code that creates the reader/writer, so rule of thumb dealing with streams and streamreader/writers:

If your Stream/StreamReader/StreamWriter are parameters to your method, you should not dispose of them. If you create the Stream it's your responsibility to dispose of it.

The one sniglet to be careful of there is sometimes a StreamReader/StreamWriter's dispose method will dispose of the underlying stream, just beware that you don't therefore dispose of your reader/writer before you are completely finished with your stream.

Body:
tl;dr

I suggest static methods, or even instance methods can be alright depending on the objects you're working with and how long lived they are as well as how stateful they are.

Do not use properties for this. Properties should be as idempotent as possible (repeated access should return the same result constantly). If A property needs to execute logic to divine its state, that's not always terrible, but properties should never be changing state on a Get.

Usually when you're dealing with an underlying set of data to deserialize something you'll have a current position in that set, and the act of deserializing will move that position thus causing a Get to change state.

I once wrote a bunch of binary serialization for some simple objects we had, and found it quite helpful to just make the methods extension methods on the BinaryReader and BinaryWriter classes. If you look at these classes, they already have methods for turning binary data into data types with ReadInt and ReadString etc, so the static methods relied on these to reconstruct the objects.

It as as such:

public class FunnyAnimal
{
    public int NumberOfLegs { get; set; }
    public string Name { get; set; }
    public Tuple<int, int> EarHearingSensitivity { get; set; }
}

public static class BinaryWriterExtensions
{
    public FunnyAnimal WriteFunnyAnimal(this BinaryWriter writer, FunnyAnimal animalToBeWritten)
    {
        writer.WriteInt(animalToBeWritten.NumberOfLegs);
        writer.WrinteString(animalToBeWritten.Name);
        writer.WriteInt(animalToBeWritten.EarHearingSensitivity.Item1);
        writer.WriteInt(animalToBeWritten.EarHearingSensitivity.Item2);
    }
}

public static class BinaryReaderExtensions
{
    public FunnyAnimal ReadFunnyAnimal(this BinaryReader reader)
    {
        return new FunnyAnimal()
        {
            NumberOfLegs = reader.ReadInt(),
            Name = reader.ReadString(),
            EarHearingSensitivity = Tuple.Create(reader.ReadInt(), reader.ReadInt())
        };
    }
}

Then the use is:

//To write it out to a stream
using (var writer = new BinaryWriter(someUnderlyingStreamToWriteTo))
{
    writer.WriteFunnyAnimal(yourFunnyAnimalObject);
}

//To read it in from a stream
FunnyAnimal deserializedFunnyAnimal = null;
using (var reader = new BinaryReader(someUnderlyingStreamToReadFrom))
{
    deserializedFunnyAnimal = reader.ReadFunnyAnimal();
}

The same approach could be applied to any type of serializer you're working with, if you're just using straight BinaryFormatter you can make your extensions on a MemoryStream and make the methods utilize a BinaryFormatter to read and write from the stream, but the use is then clear and simple, construct a MemoryStream and ReadFunnyAnimal or WriteFunnyAnimal on it, and the extension methods will create and operate the BinaryFormatter

Last thoughts

When dealing with binary serialization/deserialization you'll find the most convenient stream underlying a lot of times may just be a MemoryStream with an array backing it so you can just grab the byte array when you're done, unless you have a file or other resource you're specifically serializing across.

If you have complex objects inside that need serializing, this technique is helpful because the implementation for the writer and reader extensions will have access to the reader/writer so the extension methods for your embedded complex objects will also be in scope to be used as:

return new FunnyAnimal() { ComplexTailMember = reader.ReadTail(); }

Additionally it's worth recognizing when dealing with serialization/deserialization implementations who's going to own the stream. Your extensions shouldn't own it in a sense that they should not open/move/dispose of it after they're done, rather that should be on the ownus of the code that creates the reader/writer, so rule of thumb dealing with streams and streamreader/writers:

If your Stream/StreamReader/StreamWriter are parameters to your method, you should not dispose of them. If you create the Stream it's your responsibility to dispose of it.

The one sniglet to be careful of there is sometimes a StreamReader/StreamWriter's dispose method will dispose of the underlying stream, just beware that you don't therefore dispose of your reader/writer before you are completely finished with your stream.


问:
What is selection and what is projection
I am working on Android with the query() method of the ContentResolver class and it accepts 6 parameters, (uri,projection,selection,selectionArgs,sortOrder,cancellationSignal) for selection and projection parameters.

I am little bit confused with the selection and projection part of query.

In below example, what is selection and project part in the query?

```<code>select * from Person
where name='zeus';
</code>```

答:
The projection refers to the columns you want back (the bit after SELECT and before FROM), the selection refers to the limiting of the records (the bit after WHERE and before ORDER BY). For Android, the projection variable should be something like:

new String[] {"name", "age"}

The selection variable should have the WHERE clause with the values replaced by question marks. The values go in the selectionArgs. So selection in your example would be:

"name=?"

and selectionArgs would be:

new String[] {"zeus"}


问:
Does parallel mergesort run differently on mesh vs linear array of processors?
I'm currently taking course on introduction to algorithm and I came across the parallel mergesort algorithm.
My question is: Is there any differences in the algorithm plan if it runs on a 2d mesh instead of infinite linear proccessors ?

Thank you,

答:
Please define the terms mesh and linear array of processors, and/or provide online references to such definitions.

There are different flavors of mergesort algorithms. One remarkable difference is:

For merging two sorted halves of size N/2 arrays into a fully sorted N array, does it take exactly one stage (performing exactly N or O(N) comparisons), or does it take multiple stages, most commonly O(log(N)) as many stages (for a total number of O(N*log(N)) comparisons)?

The single-threaded mergesort, the one typically taught in the introduction to programming classes, relies on scanning the two halves, "dequeuing" the smaller value of the two front values out of the two halves. This takes exactly N-1 comparisons. Because it is sequential, it takes O(N) time steps.

The parallel mergesort, which is most likely a parallel bitonic mergesort, such as

http://en.wikipedia.org/wiki/Bitonic_sorter

http://pages.cs.wisc.edu/~tvrdik/17/html/Section17.html

Requires log(N) stages;

Inside each stage, O(N) comparisons are performed - one comparison per processing element - and all processing elements do this simultaneously.

Therefore, it requires O(log(N)) time, despite having performed vastly many more total number of comparisons of N*log(N)

There are other flavors of parallelized merge sort. I can't answer them unless you clarify what flavor of merge sort you're learning.


问:
An algorithm for finding converse duplicates of ordered pairs
Given an array of ordered pairs of values, what algorithm will find converse duplicates? [Converse meaning the same values, but in the opposite order.]

That is, given [ab,ac,ad,bc,bd,ca,db] is there an efficient way to find ca and db, being the converse duplicates for ac and bd?

The application is simple enough: the ordered pairs are edges in a directed graph and if there is a converse edge then a single double-ended edge is to be drawn rather than one edge in each direction. The values are strings, being node names.

It can be viewed as a lookup in a sparse array. Given coordinates (a,b), check whether (b,a) exists. However, common programming languages do not (appear to) provide sparse 2d arrays.

I have written a solution in ruby using hash-of-hash, but it's about 20 lines of awkward code and an unsatisfying outcome. Writing the same code in a language like C# or Java would be longer. A better solution is sought, in pseudocode or a description (steps) of the algorithm. Either way, I am seeking an answer that describes how to find the solution as well as the benefits and drawbacks of the particular algorithm.

I haven't attempted to define 'efficient' or 'better', and performance is not an overriding consideration for a drawing of a few hundred nodes.

The nodes are not sorted, so the default algorithm would be, for each pair, to form the converse and brute-force search the preceding half. A binary search would require a prior sort. A solution based on hash indexing should be much faster.

答:
This is the code for my ruby implementation. The output is in a format intended for Graphviz.

```<code>  graph_edges = {}
  fmap.keys.sort.each do |srckey|
    forms = fmap[srckey]
    fsrc = $1 if srckey =~ /---/
    forms.keys.each do |fkey|
      fdest = $1 if fkey =~ /---/
      if fdest
        if graph_edges[fdest] && graph_edges[fdest][fsrc]
          graph_edges[fdest][fsrc] = :both
        else
          graph_edges[fsrc] ||= {}
          graph_edges[fsrc][fdest] ||= :only
        end
      end
    end if fsrc
  end
  fout3.puts "digraph {"
  graph_edges.each do |fsrc,h|
    h.each_pair do |fdest,dir|
      dirs = " [dir = both]" if dir == :both
      fout3.puts "  #{fsrc} -> #{fdest}#{dirs};"
    end
  end
  fout3.puts "}"
</code>```

Hopefully there is something useful here. I shall be working on something better based on a tuple value hash.

Body:
This is the code for my ruby implementation. The output is in a format intended for Graphviz.

  graph_edges = {}
  fmap.keys.sort.each do |srckey|
    forms = fmap[srckey]
    fsrc = $1 if srckey =~ /---/
    forms.keys.each do |fkey|
      fdest = $1 if fkey =~ /---/
      if fdest
        if graph_edges[fdest] && graph_edges[fdest][fsrc]
          graph_edges[fdest][fsrc] = :both
        else
          graph_edges[fsrc] ||= {}
          graph_edges[fsrc][fdest] ||= :only
        end
      end
    end if fsrc
  end
  fout3.puts "digraph {"
  graph_edges.each do |fsrc,h|
    h.each_pair do |fdest,dir|
      dirs = " [dir = both]" if dir == :both
      fout3.puts "  #{fsrc} -> #{fdest}#{dirs};"
    end
  end
  fout3.puts "}"

Hopefully there is something useful here. I shall be working on something better based on a tuple value hash.


问:
How can I close my Open Source project and what is required from me in order to make it closed source?
Let's say I wanted to close my "GPL v 2.0 (or similar)" licensed project, to which I'm the only contributor, and make it closed source.

Do I still need to make the existing "GPL v 2.0 (or similar)" licensed code available after closing the project or can I refuse giving out the source code for old revisions that was previously "GPL v 2.0 (or similar)" licensed?

Can I theoretically keep the the code "GPL v 2.0 (or similar)" licensed even after removing the public source code or do I have to distribute the source code if I'm using a "GPL v 2.0 (or similar)" license?

答:
There are two cases in which it is possible to effectively change the copyright license on existing code.

The existing copyright license gives you the right to change the license or to sub-license the code. The GPL licenses do not fall in this category of licenses.

You are one of the copyright holders on the code and all copyright holders explicitly agree to the license change. If you ever accepted contributions from others without an explicit re-assignment of the copyright, then you the copyright on those contributions belongs to the person that wrote the contribution and you are bound by the license terms that were in effect when the contribution was made.

If you want to change the license, you must get permission from all contributers. If any one of them refuses permission, then you must either remove their contributions entirely or forget about the license change.

In both cases, the license change only applies to future versions.

If you don't fall in any of the two categories above, then you can not change the license.

There is one additional possibility to keep your code secret:

Copyright licenses govern what others can do with code you own. They are only relevant when you distribute the code (either in binary or source code form). If you don't distribute your own code, you don't need to bother to think about copyright licenses and if you use code owned by others but you don't redistribute it, then you only need to pay attention to the right to modify or make derived works. In all open-source licenses, any requirements on providing the source code is tied to distribution of your changes and don't apply if you don't distribute.

The key here thus is distribution of the program/library. Different licenses have different notions of what constitutes distribution, ranging from giving out copies to allowing remote access to the program.

But in all cases, if an organization makes tools for internal use, then allowing employees to use those tools is not considered distribution under copyright law. This means that you don't need to release the code for internal tools, even if those tools make use of GPL-licensed code.


问:
Let applications share a database or keep them in sync with web services?
We have decided to build separate applications for user authentication and user management.  The reason is that the the former is a "this just needs to always work, and do so instantly" style service, and the latter includes a much-larger user-interface component with many requirements and features.

Unfortunately, while white-boarding, prototyping, and getting more information about required features, we discovered that they need to share several types of information. For example, both apps need to know whether a user is locked out or needs to reset their password.

We are considering connecting the applications to the same database.  We considered using web services for communication, but that has a higher up-front cost, is more complex, and will have worse performance (assuming the same query will be made in either case). We'd have to keep some pieces of information in sync across two database instances, which is obviously not an optimal setup.

On the other hand, sharing the database instance would require the ORM's entity schemas to stay in sync somewhat (even if we weren't using one, we'd still need to make sure our queries still worked in both apps whenever the database schema changed).  It creates a shared dependency. In addition, the database becomes a single-point of failure/poor performance. In addition, I'm not sure it would be possible to hide irrelevant data from either app, so encapsulation is reduced.

Has anyone here worked this dilemma before and gained any insights? I'm sure there are other considerations here that I haven't thought of yet.  It's not exactly unusual to have different applications connect to a central database.

Edit (much later):

The outcome of this story almost two years later is that we ended up merging the applications into one (which thankfully was easy because they were both just modules using the same framework). The reasoning for splitting them into two made sense at the time, but in retrospect they shared too many responsibilities to make it practical.

答:
Long story short: all in one.

If you consider one of these as "master" and the other as an augmented replica, that updates are replicated one way only, and you can survive large latencies in synchronisation (and I'll let you define "large") then two separate DBs will work.  For anything else I'd suggest a single DB.

If you have two-way updates will they be synchronous or async?  The former and you have closely coupled the two DBs.  The latter and you must have conflict resolution measures in place, adding complexity.  With a single DB you have the whole weath of concurrency technology to support you.

With any copy process there will be latency, even if it is only milli- or micro-seconds.  That's all it takes to introduce inconsistency between the source's and replica's data, however, and then you have the whole reconciliation & resolution thing again.

How will you handle DR?  How will you ensure a common sync point across two DBs, potentially on different servers (or data centres)?  How do you ensure you get the two matching tapes back from the off-site vault first time, every time?

Any schema change which adds tables or columns will be transparent to the other application. (You're not writing SELECT *, are you?  ARE YOU?)  Removing objects should only affect modules which use then, which you'd want to change anyway.  (Two DBs with a redundant table in one but removed from the other smells like a potential source of great confusion to me.)  Changing schema because business rules have changed may cause some duplication of work; but it seems to me if one application isn't implementing that business rule it had no call to be in that part of the DB anyway.

Could you store the ORM-implementing code files in way that made them common to both applications?  Then schema changes will affect only one set of code.

"Database as single point of failure."  Well, fair point.  But then it has been on absolutely every application I've ever worked on since they've all had a DB.  That's why we have cluster/ mirror/ high-availability built into the DBMS products.  If you have two DBs and one fails, what then?  Back to the reconciliation/ conflict resolution cycle.  It is also a single point of tuning; fix it one place and it's fixed everywhere!

I would have thought views, stored procedures, the ORM itself, and limiting the items in any SELECT query would have been able to isolate any part of the application from data in which it has no interest.

My reading of your question is that your two applications are actually quite closely coupled.  My response is coloured by that.  I've written plenty of systems where we bulk copy or two-way replicate data and deal with the consequences.


问:
Why shouldn't an object reference have access to a static member in C#
Context of my question:

I am reading C#.

Trying to understand Static keyword.

I understand that when Static is applied to a member of a class, it can only be modified by the class and not the class object references.

I will take an example here.

```<code>public class BluePrint
{
   public static string BluePrintCreatorName;
}
</code>```

If I need to know the BluePrintCreator's Name, I can call

```<code>BluePrint.BluePrintCreatorName;
</code>```

But if a house that is created from the blueprint wants to know the BluePrintCreator's Name, it does not have access.

```<code>BluePrint NewHouse = new BluePrint();
NewHouse.BluePrintCreatorName; //This is not accessible
</code>```

Compiler error says:

Member 'AccessModifier.BluePrint.BluePrintCreatorName' cannot be accessed
with an instance reference; qualify it with a type name instead
```

I understand this is the way it works. But I want to know the basic concept to why Static keyword was required at all?

What will go wrong if a class object reference would have access to the static member?

答:
Nothing go wrong for accessing a static member from an instance, in fact this is perfectly possible in other languages like java, your example code compiles and runs ok if its in java.

It's a check the compiler designers have introduced because they thought that this will help programmers to write clear code with this language. On this way only looking at the code you can always know if you are accessing a static or an instance member, in languages where this access is allow (like java) sometimes its a little confusing when someone decides to access a static member throughout an instance variable, in fact normally when you see this access in java code its more a mistake than a programmer really using this "language feature".

In my opinion limiting this access its a good decision in C# to avoid some mistakes and bad interpretations.

Although  it's legal in Java to refer static members that way, it's recommended against in Code Conventions (10.2 Referring to Class Variables and Methods):

"Avoid using an object to access a class (static) variable or method.
  Use a class name instead..."


答:
What will go wrong if a class object reference would have access to the static member?

It is not the reference that matters, a reference is for you to know what instances your dealing with. static members work like this; they are part of a class, but they are not part of an instance derived from that class.

I understand this is the way it works. But I want to know the basic concept to why Static keyword was required at all?

Before OOP was mature, there were no runtime environments that allowed the initialization of individual objects. Programs were basically a collection of subroutines which would call each other cohesively. You can think of this as "static" to get the right idea. Even when OOP became mature, the idea of independent classes still appealed because they are accessible unconditionally. On a runtime level static classes are like instances too, but thats not how they appeal from the language. Now there is also such thing as static members, but having those in conjunction with a non-static class is unusual because it could cause unexpected behavior with asynchronous operations, note that this doesn't apply for static readonly members.

Title: Why shouldn't an object reference have access to a static member in C#

Body:
Context of my question:

I am reading C#.

Trying to understand Static keyword.

I understand that when Static is applied to a member of a class, it can only be modified by the class and not the class object references.

I will take an example here.

```<code>public class BluePrint
{
   public static string BluePrintCreatorName;
}
</code>```

If I need to know the BluePrintCreator's Name, I can call

```<code>BluePrint.BluePrintCreatorName;
</code>```

But if a house that is created from the blueprint wants to know the BluePrintCreator's Name, it does not have access.

```<code>BluePrint NewHouse = new BluePrint();
NewHouse.BluePrintCreatorName; //This is not accessible
</code>```

Compiler error says:

Member 'AccessModifier.BluePrint.BluePrintCreatorName' cannot be accessed
with an instance reference; qualify it with a type name instead
```

I understand this is the way it works. But I want to know the basic concept to why Static keyword was required at all?

What will go wrong if a class object reference would have access to the static member?


问:
Is it OK to let invalid arguments slip to another method?
For example lets take this method:

public List<string[]> ReadAll(int listCapacity)
{
    List<string[]> list = new List<string[]>(listCapacity);

    while (Read())
    {
        list.Add(GetCurrentRow());
    }

    return list;
}
```

If listCapacity is less than zero, an ArgumentException will be thrown by the constructor of List<T>. Does it make sense to double check this? Passing the argument to List<T> immediately seems careless, but checking it seems silly because List<T> will definitely check it.

Important note: the code snippet is not just a copy-paste method, its part of a full utility.

答:
Short answer: no, it's not OK. Because even calling the constructor of List means, from the compiller's perspective: memory allocation for the new object, writing references for it in the reference table, accessing other subroutines just to create the new List object, just to have it basically blow up in your face by throwing an exception.

I know it doesn't seem like much with all these available resources on the system, but it's still not something I would do - if I can avoid it with just one extra line of code.


问:
System state design composition
Consider the following Java code:

```<code>public class HumanStateImpl implements HumanState {
    private boolean alive;
    private Color skinColor;

    // getters and setters, other state fields

    @Override
    public boolean isAlive() {
        return alive;
    }
}
</code>```

Now imagine I want to have a class that represents HandState, and a corresponding HandController. Is it better to inject the state objects of each level of state separately, or compose them into one most-specific state object? If it depends, what does it depend on?

To clarify what I mean, here is an implementation of both sides, respectively:

```<code>public class HandState {
    private final Side handSide;
    private boolean closed;
}

public class HandController {
    private final HumanState humanState;
    private final HandState handState;

    public HandController(HumanState humanState, HandState handState) {
        this.humanState = humanState;
        this.handState = handState;
    }
}
</code>```

Versus:

```<code>public class HandState implements HumanState {
    private final HumanState outerState;
    private final Side handSide;

    public HandState(HumanState outerState, Side handSide) {
        this.outerState = outerState;
        this.handSide = handSide;
    }

    @Override
    public boolean isAlive() {
        return outerState.isAlive();
    }
}

public class HandController {
    private final HandState handState;

    public HandController(HandState handState) {
        this.handState = handState;
    }
}
</code>```

答:
tl;dr - I think you're going to want to inject state objects at each level of state as appropriate.

Reason being, as your application scales and you add in more controllers you're going to want to control which controllers talk with which other ones.  And the first approach you suggested will position you better to support that.

To help illustrate things, let's draw out your example quite a bit further.

We've got a Human who has decided to go shopping (aka "gone to market"). To make things fun, we're going to go to one of those super-crazy, open market bazaars where savvy folk can participate in both buying and selling as they stroll along.

While at the market, the Eyes are taking in all the items available for purchase or consumption.  They're constantly scouting out deals - any situation where you might be able to buy or sell and make some money.

The Brain is keeping track of the prices that it sees as well as any goods that have been purchased so far.

The Brain is smart enough that it knows it has to offload some of its work.  So it relies on the Wrists in order to determine if a particular deal is good or not.

But even the Wrists know that they've got too much to do, so they rely upon the Fingers to determine how much should be picked up or offered for sale.  In stock market parlance, this would be akin to determining the spread.

Finally, we'll need some sort of Basket to carry the inventory.

A sample data flow might be:

```<code>Eyes --> Brain <--> Wrists <--> Fingers       Basket
</code>```

In other domains, we may want a non-linear graph, but I think that in this case you don't.  With just 5 elements, we have a huge number of communication paths if every component can talk with every other component.

Part of what makes this model manageable is when you cut down on those numbers of interactions.  For example, the Eyes shouldn't really know what's in the Basket and absolutely shouldn't be responsible for making buy or sell decisions.  It's the same reasoning behind the colloquialism "your eyes were bigger than your stomach" when someone is super hungry and has a meal.

And note that the Basket is off by itself.  The Brain may need to ask the Basket to see if an item is in there or to see how much money is available1.  Likewise, the Fingers may need to access the Basket to place or remove items into the Basket's inventory.

1 If the Basket shouldn't know how much money is available, then just create a Wallet or similar object.

Getting back to state injection...

The Brain will need to inject some measure of state into the Wrists.  The Brain needs to say what it thinks the current market price is and potentially what's already in the basket.  The Wrists can assume that if the Brain called them that the market is open.

But the Brain shouldn't be talking directly to the Fingers since they really don't talk about the same things.  The Fingers are there to determine how much to pick up or place down based upon what the Wrists told them.  If the Fingers need additional approval before finalizing the decision, then the approval should be routed to the Wrists and then back to the Brain.

By controlling which objects talk to the others, you limit the amount of state that has to be injected throughout your model.

If you look at the alternative that you suggested, having a single state object could easily get out of hand quite quickly.  And it muddies the waters since you're injecting or exposing states to controllers that simply don't care about those particular states.  For example, the Fingers don't care if the market is open, they just figure out how much to pick up.

Likewise, let's really extend your example and say that you're modeling a human with multiple arms so multiple (buy | sell) decisions can be made at the same time.  Think of how large a single state controller would have to expand out into while keeping track of 10 sets of Wrists and 10 more sets of Fingers.

So to summarize all of that up: You want to inject state objects at each level of state as appropriate, which means that you also limit which controllers can talk with which other controllers.

Title: System state design composition

Body:
tl;dr - I think you're going to want to inject state objects at each level of state as appropriate.

Reason being, as your application scales and you add in more controllers you're going to want to control which controllers talk with which other ones.  And the first approach you suggested will position you better to support that.

To help illustrate things, let's draw out your example quite a bit further.

We've got a Human who has decided to go shopping (aka "gone to market"). To make things fun, we're going to go to one of those super-crazy, open market bazaars where savvy folk can participate in both buying and selling as they stroll along.

While at the market, the Eyes are taking in all the items available for purchase or consumption.  They're constantly scouting out deals - any situation where you might be able to buy or sell and make some money.

The Brain is keeping track of the prices that it sees as well as any goods that have been purchased so far.

The Brain is smart enough that it knows it has to offload some of its work.  So it relies on the Wrists in order to determine if a particular deal is good or not.

But even the Wrists know that they've got too much to do, so they rely upon the Fingers to determine how much should be picked up or offered for sale.  In stock market parlance, this would be akin to determining the spread.

Finally, we'll need some sort of Basket to carry the inventory.

A sample data flow might be:

Eyes --> Brain <--> Wrists <--> Fingers       Basket

In other domains, we may want a non-linear graph, but I think that in this case you don't.  With just 5 elements, we have a huge number of communication paths if every component can talk with every other component.

Part of what makes this model manageable is when you cut down on those numbers of interactions.  For example, the Eyes shouldn't really know what's in the Basket and absolutely shouldn't be responsible for making buy or sell decisions.  It's the same reasoning behind the colloquialism "your eyes were bigger than your stomach" when someone is super hungry and has a meal.

And note that the Basket is off by itself.  The Brain may need to ask the Basket to see if an item is in there or to see how much money is available1.  Likewise, the Fingers may need to access the Basket to place or remove items into the Basket's inventory.

1 If the Basket shouldn't know how much money is available, then just create a Wallet or similar object.

Getting back to state injection...

The Brain will need to inject some measure of state into the Wrists.  The Brain needs to say what it thinks the current market price is and potentially what's already in the basket.  The Wrists can assume that if the Brain called them that the market is open.

But the Brain shouldn't be talking directly to the Fingers since they really don't talk about the same things.  The Fingers are there to determine how much to pick up or place down based upon what the Wrists told them.  If the Fingers need additional approval before finalizing the decision, then the approval should be routed to the Wrists and then back to the Brain.

By controlling which objects talk to the others, you limit the amount of state that has to be injected throughout your model.

If you look at the alternative that you suggested, having a single state object could easily get out of hand quite quickly.  And it muddies the waters since you're injecting or exposing states to controllers that simply don't care about those particular states.  For example, the Fingers don't care if the market is open, they just figure out how much to pick up.

Likewise, let's really extend your example and say that you're modeling a human with multiple arms so multiple (buy | sell) decisions can be made at the same time.  Think of how large a single state controller would have to expand out into while keeping track of 10 sets of Wrists and 10 more sets of Fingers.

So to summarize all of that up: You want to inject state objects at each level of state as appropriate, which means that you also limit which controllers can talk with which other controllers.


问:
Large csv's to html report
I am working on a web front end + front end services.

I receive good sized csv files (10k lines). My service processes them and condenses them into one larger csv file (up to 300k lines).

This larger file will be turned into an html/pdf report after some extrapolation.

My questions are:

Taking 17,000 files and turning them into 1 takes FOREVER (18 hours last time I tried it). The current process is to take a line of the csv, parse it to see if it exists in my master array, and either create a new entry or add the data to an existing entry in the array. Is there a better way to do this? It seems the last item would take exponentially longer than the first.

Once this large file is created, parsing it seems to take quite a while as well. Should I move away from writing to a csv output and go with JSON for speed of data massaging? or even a lightweight db?

答: Using JSON instead isn't obvious, the format has greater complexity than CSV and is best used for exchanging petty data structures, preferably containing technical information. To speed stuff up, ensure that the master collection has a realistic intial capacity to contain that many rows, because resizing large collections is very expensive. Second, order the collection so that if the candidate row is greater than the last element, no further iteration is required. This won't work with Guid's.</p>

Title: Large csv's to html report


答:
Gotta disagree with the accepted answer.  The argument about allocating memory, etc. is only relevant if this method is called often with an illegal argument.

The purpose of checking arguments (programming by contract) and throwing exceptions is primarily to fix bugs during development.  During development, efficiency is not an issue.  Combined with unit tests, this should assure that ReadAll() is not called with a negative argument.  Or at least only called rarely in a case you didn't test.

So, with proper development and testing, efficiency will never be an issue.  Letting the check slip one or two levels is fine.  Though you may want to add a comment.

EDIT #1 added

Let's make the example slightly different.  The function returns the result as an array:

public string[] ReadAll(int maxCapacity) {...}

Would you check for maxCapacity>= 0 in your code?  Unlikely.  IMO, this case of using a List is close enough to an Array that checking the initialCapacity is overkill.

EDIT #2 Added

There are many times where it is completely unreasonable to check an incoming argument yourself.  For example, say that there is an XML String coming in.  Your method looks something like this: (pseudo-Java-like code, nor am I claiming that this is a good design)

```<code>public double getFooBarFraction(String xml) throws AllKindsOfExceptions {
   Document doc = DOMParser.getInstance().parse(xml);
   return Double.parseDouble(doc.getElement("Foo")
                                .getElement("Bar")
                                .getAttribute("fraction"));
}
</code>```

Are you going to validate the XML yourself, or let the utility
DOMParser do that?

Are you going to look for elements and attributes
yourself, or let Document do that?

Are you going to test that count
can be parsed to an double, or let Double do that?

The answer is almost certainly "no" to all of the questions.  Now, you probably should wrap the calls in try/catch blocks for better error handling, but you still let the utility create the original exception.

In rereading the other answers, they do say "where it's easy to test" etc.  I guess if you can do the test in one or two lines of code, consider doing it.

Title: Is it OK to let invalid arguments slip to another method?

Body:
For example lets take this method:

public List<string[]> ReadAll(int listCapacity)
{
    List<string[]> list = new List<string[]>(listCapacity);

    while (Read())
    {
        list.Add(GetCurrentRow());
    }

    return list;
}
```

If listCapacity is less than zero, an ArgumentException will be thrown by the constructor of List<T>. Does it make sense to double check this? Passing the argument to List<T> immediately seems careless, but checking it seems silly because List<T> will definitely check it.

Important note: the code snippet is not just a copy-paste method, its part of a full utility.

Body:
Gotta disagree with the accepted answer.  The argument about allocating memory, etc. is only relevant if this method is called often with an illegal argument.

The purpose of checking arguments (programming by contract) and throwing exceptions is primarily to fix bugs during development.  During development, efficiency is not an issue.  Combined with unit tests, this should assure that ReadAll() is not called with a negative argument.  Or at least only called rarely in a case you didn't test.

So, with proper development and testing, efficiency will never be an issue.  Letting the check slip one or two levels is fine.  Though you may want to add a comment.

EDIT #1 added

Let's make the example slightly different.  The function returns the result as an array:

public string[] ReadAll(int maxCapacity) {...}

Would you check for maxCapacity>= 0 in your code?  Unlikely.  IMO, this case of using a List is close enough to an Array that checking the initialCapacity is overkill.

EDIT #2 Added

There are many times where it is completely unreasonable to check an incoming argument yourself.  For example, say that there is an XML String coming in.  Your method looks something like this: (pseudo-Java-like code, nor am I claiming that this is a good design)

public double getFooBarFraction(String xml) throws AllKindsOfExceptions {
   Document doc = DOMParser.getInstance().parse(xml);
   return Double.parseDouble(doc.getElement("Foo")
                                .getElement("Bar")
                                .getAttribute("fraction"));
}

Are you going to validate the XML yourself, or let the utility
DOMParser do that?

Are you going to look for elements and attributes
yourself, or let Document do that?

Are you going to test that count
can be parsed to an double, or let Double do that?

The answer is almost certainly "no" to all of the questions.  Now, you probably should wrap the calls in try/catch blocks for better error handling, but you still let the utility create the original exception.

In rereading the other answers, they do say "where it's easy to test" etc.  I guess if you can do the test in one or two lines of code, consider doing it.


答:
The answer is: it depends.  In your example, you should let List throw its exception and let any exception bubble up the chain.

Your example method should not know or care whether the value is invalid, since it's sole purpose is to pass it along to something else.  If you were using the value in ReadAll as something other than an argument to List, you would be correct to test it before use, but you're not.

An invalid argument to your method is not one that will not be understood by a separate utility, it is one that does not make sense to your code.

As a side note, parameters that exist simply to be passed along, should be fairly rare.


答:
Aside memory allocation reason (which, by the way, looks like premature optimization to me), there are other elements in favor of catching invalid arguments as soon as possible:

Stack trace

When an exception occurs, you expect the few last lines to show you the location of a mistake. Having to search from bottom to top of the stack to find the culprit will waste your time later, during debug, when you specifically won't have time.

Being sloppy about input validation and letting called methods handle that again and again will mean that the stack trace will be larger than it should be. If you know that ReadAll cannot accept a negative capacity, why adding a line to stack trace, instead of throwing an exception right now in order to make the debugging easy?

Readability

Your code is expected to be self-documenting. I can only know your method doesn't accept negative values if I inspect the method closely. This is OK if I'm about to modify the method; this is not OK if I simply want to use the method, and don't really care how is it implemented.

And no, I can't rely on documentation, since it's always incomplete and obsolete.

Validating the inputs right at the top of the method would help readability: it would be clear that I can't use negative values, and I would avoid wasting additional time:

Inspecting the body of the method,

Inspecting every method in the code base this method calls,

Reading MSDN for every .NET Framework method this method calls.

Code contracts

Since you tagged your question .net and your code looks like C#, I can't avoid talking about code contracts. If you have used code contracts, you would be forced to add a Contract.Requires anyway, otherwise the static checker will complain that nothing guarantees that the list constructor will be called with valid arguments.

That's also the benefit of code contracts: they force you to handle invalid inputs at the top of the stack, so when the input is invalid, you stop right now, instead of calling dozens of other methods before encountering an exception.


问:
Implement Generic DataSet Builder with C#
I want to create a data access library that can build a DataSets with relations which can easily be written to XML with dataset.WriteXML(). This is a get to know C# endeavor that will hopefully gain me some productivity as well (lots of converting relational tables to XML from different data sources for document generation)

So far the only difference I see between the Data Access technologies (SQL, OLEDB, ODBC) with regards to how I will use them for this is that they require a type specified Connection and Adapter (SqlAdapter, OleDbAdapter, OdbcAdapter, etc).

So in my mind I envision classes with two methods and a public data set that will be filled.

```<code>public DataSet DataSet { get; set; }

public void InsertTables(string ConnectionString, string[] TableNames, string[] Commands)

public void AddRelations(string[] PrimaryTables, string[] PrimaryKeys, string[] ChildTables, string[] ForeignKeys, bool[] NestingRules)
</code>```

I already started with an OleDb Implementation that works well, and I want to set up something similar for other Data Access technologies. However, I want to be as efficient as possible with the code so am looking for advice on how to accomplish.

I was thinking that the Template Method Design pattern could be a solid approach, but then I also thought that a single class that utilizes generics might work as well (I am new to C# and not that familiar with them).

I am looking for a general example of how I could accomplish this with a good design pattern and/or generics.

Here is what I have for the OleDbDesign. Any advice is greatly appreciated.

```<code> public class OleDbDataSetBuilder
{
    private DataSet _DataSet;

    public DataSet DataSet { get { return _DataSet; } }

    public OleDbDataSetBuilder(string DataSetName)
    {
        this._DataSet = new DataSet(DataSetName);
    }

    public void InsertTables(string ConnectionString, string[] TableNames, string[] Commands)
    {

        if (TableNames.Length != Commands.Length)
        {
            throw new Exception("Error: Must provide a table name for each command.");
        }

        OleDbConnection cn = new OleDbConnection(ConnectionString);

        OleDbDataAdapter adapter = new OleDbDataAdapter("", cn);

        adapter.SelectCommand = new OleDbCommand("", cn);

        for (int i = 0; i < TableNames.Length; i++)
        {
            adapter.SelectCommand.CommandText = Commands[i];

            adapter.Fill(_DataSet, TableNames[i]);
        }

        cn.Close();

    }

    public void AddRelations(string[] PrimaryTables, string[] PrimaryKeys, string[] ChildTables, string[] ForeignKeys, bool[] NestingRules)
    {

        for (int i = 0; i < PrimaryTables.Length; i++)
        {
            DataColumn pk = _DataSet.Tables[PrimaryTables[i]].Columns[PrimaryKeys[i]];

            DataColumn fk = _DataSet.Tables[ChildTables[i]].Columns[ForeignKeys[i]];

            DataRelation relation = _DataSet.Relations.Add(pk, fk);

            relation.Nested = NestingRules[i];
        }
    }
}
</code>```

答:
Here is a link describing this approach.

Below is my resultant class based on Dan's suggestion

```<code>using System;
using System.Data;
using System.Data.Common;

namespace CustomDataAccess{

public class DataSetBuilder
{

    #region Properties

    private DataSet _DataSet;

    public DataSet DataSet { get { return _DataSet; } }

    #endregion

    #region Constructors

    public DataSetBuilder()
    {
        this._DataSet = new DataSet();
    }

    public DataSetBuilder(string DataSetName)
    {
        this._DataSet = new DataSet(DataSetName);
    }

    public DataSetBuilder(DataSet DataSet)
    {
        this._DataSet = DataSet;
    }

    #endregion

    #region Public Methods

    public DataSetBuilder InsertTables(DataTable Table)
    {
        this._DataSet.Tables.Add(Table);

        return this;
    }

    public DataSetBuilder InsertTables(string DbProviderName, string ConnectionString, string TableName, string CommandText)
    {
        System.Data.Common.DbDataAdapter adapter = Create_Adapter(DbProviderName, ConnectionString);

        Fill_Adapter(adapter, TableName, CommandText);

        adapter.SelectCommand.Connection.Close();

        return this;
    }

    public DataSetBuilder InsertTables(string DbProviderName, string ConnectionString, string[] TableName, string[] CommandText)
    {
        if (TableName.Length != CommandText.Length)
        {
            throw new Exception("Error: Must provide a table name for each command.");
        }

        System.Data.Common.DbDataAdapter adapter = Create_Adapter(DbProviderName, ConnectionString);

        for (int i = 0; i < TableName.Length; i++)
        {

            Fill_Adapter(adapter, TableName[i], CommandText[i]);
        }

        adapter.SelectCommand.Connection.Close();

        return this;
    }

    public void AddRelations(string ParentTable, string PrimaryKey, string ChildTable, string ForeignKey, bool NestingRule)
    {
        Add_Relations(ParentTable, PrimaryKey, ChildTable, ForeignKey, NestingRule);
    }

    public void AddRelations(string[] ParentTable, string[] PrimaryKey, string[] ChildTable, string[] ForeignKey, bool[] NestingRule)
    {

        for (int i = 0; i < ParentTable.Length; i++)
        {
            Add_Relations(ParentTable[i], PrimaryKey[i], ChildTable[i], ForeignKey[i], NestingRule[i]);
        }
    }

    #endregion

    #region Private Methods

    private System.Data.Common.DbDataAdapter Create_Adapter(string DbProviderName, string ConnectionString)
    {
        DbProviderFactory dbFactory = System.Data.Common.DbProviderFactories.GetFactory(DbProviderName);

        System.Data.Common.DbConnection connection = dbFactory.CreateConnection();

        connection.ConnectionString = ConnectionString;

        connection.Open();

        System.Data.Common.DbCommand command = dbFactory.CreateCommand();

        command.Connection = connection;

        System.Data.Common.DbDataAdapter adapter = dbFactory.CreateDataAdapter();

        adapter.SelectCommand = command;

        return adapter;
    }

    private void Fill_Adapter(System.Data.Common.DbDataAdapter Adapter, string TableName, string CommandText)
    {
        Adapter.SelectCommand.CommandText = CommandText;

        Adapter.Fill(_DataSet, TableName);
    }

    private void Add_Relations(string ParentTable, string PrimaryKey, string ChildTable, string ForeignKey, bool NestingRule)
    {
        DataColumn pk = _DataSet.Tables[ParentTable].Columns[PrimaryKey];

        DataColumn fk = _DataSet.Tables[ChildTable].Columns[ForeignKey];

        DataRelation relation = _DataSet.Relations.Add(pk, fk);

        relation.Nested = NestingRule;
    }

    #endregion

}}
</code>```

Body:
Here is a link describing this approach.

Below is my resultant class based on Dan's suggestion

using System;
using System.Data;
using System.Data.Common;

namespace CustomDataAccess{

public class DataSetBuilder
{

    #region Properties

    private DataSet _DataSet;

    public DataSet DataSet { get { return _DataSet; } }

    #endregion

    #region Constructors

    public DataSetBuilder()
    {
        this._DataSet = new DataSet();
    }

    public DataSetBuilder(string DataSetName)
    {
        this._DataSet = new DataSet(DataSetName);
    }

    public DataSetBuilder(DataSet DataSet)
    {
        this._DataSet = DataSet;
    }

    #endregion

    #region Public Methods

    public DataSetBuilder InsertTables(DataTable Table)
    {
        this._DataSet.Tables.Add(Table);

        return this;
    }

    public DataSetBuilder InsertTables(string DbProviderName, string ConnectionString, string TableName, string CommandText)
    {
        System.Data.Common.DbDataAdapter adapter = Create_Adapter(DbProviderName, ConnectionString);

        Fill_Adapter(adapter, TableName, CommandText);

        adapter.SelectCommand.Connection.Close();

        return this;
    }

    public DataSetBuilder InsertTables(string DbProviderName, string ConnectionString, string[] TableName, string[] CommandText)
    {
        if (TableName.Length != CommandText.Length)
        {
            throw new Exception("Error: Must provide a table name for each command.");
        }

        System.Data.Common.DbDataAdapter adapter = Create_Adapter(DbProviderName, ConnectionString);

        for (int i = 0; i < TableName.Length; i++)
        {

            Fill_Adapter(adapter, TableName[i], CommandText[i]);
        }

        adapter.SelectCommand.Connection.Close();

        return this;
    }

    public void AddRelations(string ParentTable, string PrimaryKey, string ChildTable, string ForeignKey, bool NestingRule)
    {
        Add_Relations(ParentTable, PrimaryKey, ChildTable, ForeignKey, NestingRule);
    }

    public void AddRelations(string[] ParentTable, string[] PrimaryKey, string[] ChildTable, string[] ForeignKey, bool[] NestingRule)
    {

        for (int i = 0; i < ParentTable.Length; i++)
        {
            Add_Relations(ParentTable[i], PrimaryKey[i], ChildTable[i], ForeignKey[i], NestingRule[i]);
        }
    }

    #endregion

    #region Private Methods

    private System.Data.Common.DbDataAdapter Create_Adapter(string DbProviderName, string ConnectionString)
    {
        DbProviderFactory dbFactory = System.Data.Common.DbProviderFactories.GetFactory(DbProviderName);

        System.Data.Common.DbConnection connection = dbFactory.CreateConnection();

        connection.ConnectionString = ConnectionString;

        connection.Open();

        System.Data.Common.DbCommand command = dbFactory.CreateCommand();

        command.Connection = connection;

        System.Data.Common.DbDataAdapter adapter = dbFactory.CreateDataAdapter();

        adapter.SelectCommand = command;

        return adapter;
    }

    private void Fill_Adapter(System.Data.Common.DbDataAdapter Adapter, string TableName, string CommandText)
    {
        Adapter.SelectCommand.CommandText = CommandText;

        Adapter.Fill(_DataSet, TableName);
    }

    private void Add_Relations(string ParentTable, string PrimaryKey, string ChildTable, string ForeignKey, bool NestingRule)
    {
        DataColumn pk = _DataSet.Tables[ParentTable].Columns[PrimaryKey];

        DataColumn fk = _DataSet.Tables[ChildTable].Columns[ForeignKey];

        DataRelation relation = _DataSet.Relations.Add(pk, fk);

        relation.Nested = NestingRule;
    }

    #endregion

}}


问:
Scripts to run Java programs - e.g. Ant
My team currently use an Ant script to execute various Java programs.

Note that I am not asking about managing the build/deployment cycle for which we are already using Maven (quite happily).

For example, we use something like the following:

```<code><path id="lib">
  <fileset dir="path/to/lib" />
</path>

<path id="run" >
  <path refid="lib" />
</path>

<target name="aJavaProgram" >
  <java classname="path.to.AJavaProgam"
        classpathref="run" fork="yes" failonerror="false" append="true" />
</target>

<target name="anotherJavaProgram" depends="aJavaProgram" >
  <java classname="path.to.AnotherJavaProgam"
        classpathref="run" fork="yes" failonerror="false" append="true" />
</target>
</code>```

We originally chose Ant for the following reasons (or rather I didn't choose Ant, it was that way when I joined, but I think these are good reasons for the choice):

it was an easy way of managing dependencies (although we now pick up these from Maven)

it allows us to easily build/maintain dependencies between particular jobs

we can deploy the Ant script, and the Java libraries, and easily run particular jobs - i.e.

we don't have to worry about classpaths (configured in the Ant script)

we don't have to worry about building jars with main classes specified in the manifest

we can use Ant to create / store / manage arguments passed to main() methods

we can plug these ant scripts into our IDEs and run the jobs from there.

Generally speaking, we have been very happy with this.

However, an increasing issue is the ant-java-shutdown hook issue - this means that if one of these Java programs fails but doesn't finish, terminating the Ant process from which it was started doesn't terminate the Java process - which then has to be done manually, and is a real bind.

Also, I'm conscious of two other (possible) factors:

this is using Ant in a slightly unusual way, which is perhaps not how Ant was intended to be used (or at least, so it seems to me...)?

I'm not really sure, but it seems that fewer and fewer developers/teams are using Ant these days, with preference for other technologies.

So, to clarify:

I want a flexible approach to execute various Java programs

the approach that we have been using was to do this via Ant scripts, but this had the following problems:

terminating the Ant task does not kill the Java program

this "feels" like Ant is not the right tool for the job

how might we meet the needs specified above?

if not Ant, the solution should not face the termination / shutdown hook issue

答:
In a perfect world shutting down your Ant program would also shut down your Java programs.  It sounds like you need an explicit shutdown procedure.

Ant is great for writing platform-independent scripts.  I've never heard of a long-lived Ant process before.  In my experience the Ant program runs, does its job, and exits.  I would suggest setting spawn=true when you fire up the Java programs so they will continue after Ant dies, then allowing Ant to exit as quickly as possible.

You should make an explicit Ant task whose job it is to shut down the system.  The quick-and-dirty way is to find those Java programs and kill them.  Assuming these are programs that you wrote, you'll be able to incorporate explicit shutdown hooks.  For example, have each program listen on a predefined port and when someone connects to that port and issues the right instructions the program will initiate a graceful shutdown.

This suggestion comes with security risks -- what if a malicious program initiates the shutdown sequence?  You'll have to make sure your firewall is configured appropriately so that only trusted processes or machines can access the shutdown port.  That part is left as an exercise for the reader. :)

Edit: Make sure your Ant task and/or the Java program do appropriate error checking on any parameters that are passed in.  Otherwise you could have a situation that is really challenging to debug. (Thanks to @randomA)

Title: Scripts to run Java programs - e.g. Ant


问:
How to do documentation for code and why is software (often) poorly documented?
There are some good examples of well-documented code out there, such as java api. But, a lot of code in public projects such as git and internal projects of companies is poorly documented and not very newcomer friendly.

In all my software development stints, I have had to deal with poorly documented code. I noticed the following things -

Little or no comments in code.

Method and variable names are not self describing.

There is little or no documentation for how the code fits into the system or business processes.

Hiring bad developers or not mentoring the good ones . They can't write simple and clean code. Hence its difficult or impossible for anyone, including the developer to document the code.

As a result, I have had to go through a lot of code and talk to many people to learn things. I feel this wastes everyone's time. It also creates the need for KT/Knowledge transfer sessions for newcomers to a project.

I learned that documentation is not given the attention it deserves because of the following reasons:

Laziness.

Developers don't like to do anything but code.

Job security. (If no one can understand your code easily, then you might not be easily replaceable.)

Difficult deadlines leave little time to document.

So, I am wondering if there is a way to encourage and enforce good documentation practices in a company or project. What are the strategies to be used for creating decent documentation for the systems and code of any project, regardless of its complexity ? Are there any good examples of when minimal or no documentation is needed ?

IMHO, I feel that we should have a documentation review after a project is delivered. If it is not simple, concise, illustrative and user friendly, the developer or technical documentation engineer own the responsibility for it and be made to fix it. I neither expect people to make reams of documentation, not hope that it will be user friendly like the head first books, but I expect it to eliminate the need for hours of analysis and wasteful KT sessions.

Is there a way to end or alleviate this madness ? "Document driven development" perhaps ?

答:
How to document code?

You already have a hint: look at how Java API is documented.

More generally, there is no unique set of rules which apply to every project. When I work on business-critical large-scale projects, the documentation has nothing to do with the one I would write for a small open source library, which, in turn, has nothing to do with the documentation of my medium-scale personal project.

Why many open source projects are not documented well?

Because most open source projects are made by people who contribute to those projects because it's fun. Most programmers and developers consider that writing documentation is not fun enough to be done for free.

Why many closed-source projects are not documented well?

Because it costs a huge amount of money to (1) write good documentation and to (2) maintain it.

The immediate cost (cost of writing the documentation) is clearly visible to the stakeholders: if your team asks to spend the next two months documenting the project, it's two additional months of salary to pay.

The long term cost (cost of maintaining the documentation) becomes noticeable pretty easy too to the managers, and is often the first target when they must lower the cost or shorten the delays. This causes an additional problem of outdated documentation which quickly becomes useless, and is extremely expensive to update.

The long term savings (savings from not having to waste a few days exploring the legacy code just to understand a basic thing which should have been documented years ago) are, on the other hand, difficult to measure, which confirms the feeling of some managers that writing and maintaining documentation is a waste of time.

What I often observe is that:

At the beginning, the team is willing to document a lot.

Over time, pressure of deadlines and lack of interest make it more and more difficult to maintain the documentation.

A few months later, a new person who joins the project practically can't use the documentation, because it doesn't correspond at all to the actual system.

Noticing that, management blames developers for not maintaining the documentation; developers ask to spend a few weeks updating it.

If management grants a few weeks for that, the cycle repeats.

If management refuses, based on previous experience, it only increases the bad experience, since the product lacks documentation, but a few months were spent writing and maintaining it.

Documentation should be a continuous process, just like testing. Spend a week simply coding a few thousands of LOC, and getting back to tests and documentation is very, very painful.

How to encourage the team to write documentation?

Similarly to the ways to encourage people to write clean code, to do regular refactoring, to use design patterns or to add enough unit tests.

Lead by example. If you write good documentation, your pairs might start doing it too.

Do systematic code reviews, including formal code reviews targeted at inspecting the documentation.

If some members of the team are particularly antipathetic to good documentation (or documentation at all), discuss the subject with them privately, to understand what are the impediments which prevent them from writing better documentation. If they blame the lack of time, you see the source of the problems.

Make the presence or the lack of documentation measurable for a few weeks or months, but don't focus on that. For example, you may measure the number of lines of comments per LOC, but don't make it a permanent measure, otherwise, developers will start writing long but meaningless comments just to get rid of low scores.

Use gamification. This comes together with the previous point.

Use positive/negative reinforcement.

(See the comment by SJuan76) Treat the lack of comments as errors. For example, in Visual Studio, you can check an option to generate XML documentation. If you also check that all warnings are treated as errors, the lack of a comment at the top of a class or a method will halt the compilation.

As for the three previous points, this one should be used with caution. I used it for a while with a particularly tough team of beginner programmers, and it ended up with StyleCop-compliant comments like that:

    ///
    /// Gets or sets the PrimaryHandling.
    ///
    public Workflow PrimaryHandling { get; set; }
```

which were, hm..., not particularly helpful.

Remember: nothing automated can help you pinpoint bad comments when programmers wants to screw with you. Only code reviews and other human tasks will help.

Are there any good examples of when minimal or no documentation is needed?

Documentation explaining the architecture and the design is not needed:

For a prototype,

For a personal project written in a few hours to accomplish a task, while being pretty sure this project won't be maintained any longer,

For any project where it is obvious, given the small size of it, coupled with the particularly clean code, that you will spend more time writing documentation than all the future maintainers exploring the code.

In-code documentation (code comments) is not needed according to some developers when the code is self-documenting. For them, the presence of comments is, except in the rare cases, not a good sign, but a sign that the code wasn't refactored enough to be clear without the need for comments.

I feel that we should have a documentation review after a project is delivered.

If your project is delivered at least once per week, it's the way to go. If your project is not agile and is delivered at the intervals of six months, then do more regular reviews.

Body:
How to document code?

You already have a hint: look at how Java API is documented.

More generally, there is no unique set of rules which apply to every project. When I work on business-critical large-scale projects, the documentation has nothing to do with the one I would write for a small open source library, which, in turn, has nothing to do with the documentation of my medium-scale personal project.

Why many open source projects are not documented well?

Because most open source projects are made by people who contribute to those projects because it's fun. Most programmers and developers consider that writing documentation is not fun enough to be done for free.

Why many closed-source projects are not documented well?

Because it costs a huge amount of money to (1) write good documentation and to (2) maintain it.

The immediate cost (cost of writing the documentation) is clearly visible to the stakeholders: if your team asks to spend the next two months documenting the project, it's two additional months of salary to pay.

The long term cost (cost of maintaining the documentation) becomes noticeable pretty easy too to the managers, and is often the first target when they must lower the cost or shorten the delays. This causes an additional problem of outdated documentation which quickly becomes useless, and is extremely expensive to update.

The long term savings (savings from not having to waste a few days exploring the legacy code just to understand a basic thing which should have been documented years ago) are, on the other hand, difficult to measure, which confirms the feeling of some managers that writing and maintaining documentation is a waste of time.

What I often observe is that:

At the beginning, the team is willing to document a lot.

Over time, pressure of deadlines and lack of interest make it more and more difficult to maintain the documentation.

A few months later, a new person who joins the project practically can't use the documentation, because it doesn't correspond at all to the actual system.

Noticing that, management blames developers for not maintaining the documentation; developers ask to spend a few weeks updating it.

If management grants a few weeks for that, the cycle repeats.

If management refuses, based on previous experience, it only increases the bad experience, since the product lacks documentation, but a few months were spent writing and maintaining it.

Documentation should be a continuous process, just like testing. Spend a week simply coding a few thousands of LOC, and getting back to tests and documentation is very, very painful.

How to encourage the team to write documentation?

Similarly to the ways to encourage people to write clean code, to do regular refactoring, to use design patterns or to add enough unit tests.

Lead by example. If you write good documentation, your pairs might start doing it too.

Do systematic code reviews, including formal code reviews targeted at inspecting the documentation.

If some members of the team are particularly antipathetic to good documentation (or documentation at all), discuss the subject with them privately, to understand what are the impediments which prevent them from writing better documentation. If they blame the lack of time, you see the source of the problems.

Make the presence or the lack of documentation measurable for a few weeks or months, but don't focus on that. For example, you may measure the number of lines of comments per LOC, but don't make it a permanent measure, otherwise, developers will start writing long but meaningless comments just to get rid of low scores.

Use gamification. This comes together with the previous point.

Use positive/negative reinforcement.

(See the comment by SJuan76) Treat the lack of comments as errors. For example, in Visual Studio, you can check an option to generate XML documentation. If you also check that all warnings are treated as errors, the lack of a comment at the top of a class or a method will halt the compilation.

As for the three previous points, this one should be used with caution. I used it for a while with a particularly tough team of beginner programmers, and it ended up with StyleCop-compliant comments like that:

    /// <summary>
    /// Gets or sets the PrimaryHandling.
    /// </summary>
    public Workflow PrimaryHandling { get; set; }

which were, hm..., not particularly helpful.

Remember: nothing automated can help you pinpoint bad comments when programmers wants to screw with you. Only code reviews and other human tasks will help.

Are there any good examples of when minimal or no documentation is needed?

Documentation explaining the architecture and the design is not needed:

For a prototype,

For a personal project written in a few hours to accomplish a task, while being pretty sure this project won't be maintained any longer,

For any project where it is obvious, given the small size of it, coupled with the particularly clean code, that you will spend more time writing documentation than all the future maintainers exploring the code.

In-code documentation (code comments) is not needed according to some developers when the code is self-documenting. For them, the presence of comments is, except in the rare cases, not a good sign, but a sign that the code wasn't refactored enough to be clear without the need for comments.

I feel that we should have a documentation review after a project is delivered.

If your project is delivered at least once per week, it's the way to go. If your project is not agile and is delivered at the intervals of six months, then do more regular reviews.


答:
I think you should make a distinction between comments and documentation. While comments are descriptive, they lack consistancy, they are scattered all over the code. Comments should never compensate for code which is not self-describing enough, instead it should hint other programmers at tricky parts.

Whether code should be documented depends on the scale of the project. Surely there are people who believe that everything should be documented, and it seems easy to justify that thought because who would dare to oppose documenting knowledge? Fortunately software development is not science, and the world doesn't collapse if the details behind your little program become obscure. Now concerning a professional software for use by many developers, yes obviously you should document your code. But if you are in the position to code on that level, then you would obviously know that.

tl;dr

If you're asking for every project to be well documented, then you're asking too much.

Title: How to do documentation for code and why is software (often) poorly documented?

Body:
There are some good examples of well-documented code out there, such as java api. But, a lot of code in public projects such as git and internal projects of companies is poorly documented and not very newcomer friendly.

In all my software development stints, I have had to deal with poorly documented code. I noticed the following things -

Little or no comments in code.

Method and variable names are not self describing.

There is little or no documentation for how the code fits into the system or business processes.

Hiring bad developers or not mentoring the good ones . They can't write simple and clean code. Hence its difficult or impossible for anyone, including the developer to document the code.

As a result, I have had to go through a lot of code and talk to many people to learn things. I feel this wastes everyone's time. It also creates the need for KT/Knowledge transfer sessions for newcomers to a project.

I learned that documentation is not given the attention it deserves because of the following reasons:

Laziness.

Developers don't like to do anything but code.

Job security. (If no one can understand your code easily, then you might not be easily replaceable.)

Difficult deadlines leave little time to document.

So, I am wondering if there is a way to encourage and enforce good documentation practices in a company or project. What are the strategies to be used for creating decent documentation for the systems and code of any project, regardless of its complexity ? Are there any good examples of when minimal or no documentation is needed ?

IMHO, I feel that we should have a documentation review after a project is delivered. If it is not simple, concise, illustrative and user friendly, the developer or technical documentation engineer own the responsibility for it and be made to fix it. I neither expect people to make reams of documentation, not hope that it will be user friendly like the head first books, but I expect it to eliminate the need for hours of analysis and wasteful KT sessions.

Is there a way to end or alleviate this madness ? "Document driven development" perhaps ?


问:
Early attempt to remove Python GIL resulted in bad performance: Why?
This post from Python creator, Guido Van Rossum, mentions an early attempt to remove the GIL from Python:

This has been tried before, with disappointing results, which is why
  I'm reluctant to put much effort into it myself. In 1999 Greg Stein
  (with Mark Hammond?) produced a fork of Python (1.5 I believe) that
  removed the GIL, replacing it with fine-grained locks on all mutable
  data structures. He also submitted patches that removed many of the
  reliances on global mutable data structures, which I accepted.
  However, after benchmarking, it was shown that even on the platform
  with the fastest locking primitive (Windows at the time) it slowed
  down single-threaded execution nearly two-fold, meaning that on two
  CPUs, you could get just a little more work done without the GIL than
  on a single CPU with the GIL. This wasn't enough, and Greg's patch
  disappeared into oblivion. (See Greg's writeup on the performance.)

I can hardly argue with the actual results, but I really wonder why this happened.  Presumably, the main reason that removing the GIL from CPython is so difficult is because of the reference counting memory management system.  A typical Python program will call Py_INCREF and Py_DECREF thousands or millions of times, making it a key contention point if we were to wrap locks around it.

But, I don't understand why adding atomic primitives would slow down a single threaded program.  Suppose we just modified CPython so that the refcount variable in each Python object was an atomic primitive.  And then we just do an atomic increment (fetch-and-add instruction) when we need to increment the reference count.  This would make Python reference counting thread-safe, and shouldn't have any performance penalty on a single-threaded application, because there would be no lock contention.

But alas, many people who are smarter than me have tried and failed, so obviously I'm missing something here.  What is wrong with the way I'm looking at this problem?

答:
Another wild hypothesis: In 1999 Linux and other Unices hadn't a performant synchronisation like it has now with futex(2) (http://en.wikipedia.org/wiki/Futex). Those came around 2002 (and were merged into 2.6 around 2004).

Since all builtin data structures has to be synchronized locking costs a lot.
Ӎσᶎ already pointed out, that atomic operations are not necessary cheap.


答:
There's always something to get better at. If you're in that situation, sometimes you can make the whole team better, too.

Grow as a mentor and a coach, and you may find that those folks you led are now challenging you to keep up.

Title: Charles Barkley syndrome

Body:
Charles Barkley was an excellent basketball player, a hall of fame, and a dream team member.  He played for the 76ers, Suns, and Rockets.  Yet he never won an NBA championship.  Some might argue this was because he was never surrounded by other players of his caliber, and in the NBA, you can't win on your own.

So what does this have to do with programming?

How many of you out there feel like Sir Charles?  Leading your team in every category, KLOCs, bugs fixed, systems configured...  Always the one pushing for improvements, upgrading systems, negotiating with customers...  Feeling like you are carrying the team.  Anger just under the surface.

Only to retire eventually, without "the ring"1.

1: Keep in mind, Charles never blamed his team.  He just performed at his best.


答:
I believe you are trying to recreate the concept of a database management system the hard way. File I/O combined with parsing and re-parsing your data is what kills your performance.

Option 1: Handle the merging yourself

a) Put your master "array" into a database as a set of rows in (one or more) table(s).

b) Read in your files, and merge the results in to the tables.

Option 2: Let the database handle the merging

a) Put your master "array" into one or more tables in a database (table A). Construct your indices.

b) Import a file into your database into tables similar in form to the master tables, but separate and temporary (table B).

c) Merge the master and imported data using LEFT JOIN to produce a temporary update table C. (INNER JOIN)

d) Antimerge the master and imported data by finding all records that are not in the master table and putting them into a temporary table D. (RIGHT EXCLUDING JOIN)

e) Perform an update from table C into table A. Then, add all records from table D to table A.

(For an excellent view of the JOIN terminology, I use this set of diagrams and code: Visual Representation)

Title: Large csv's to html report

Body:
I am working on a web front end + front end services.

I receive good sized csv files (10k lines). My service processes them and condenses them into one larger csv file (up to 300k lines).

This larger file will be turned into an html/pdf report after some extrapolation.

My questions are:

Taking 17,000 files and turning them into 1 takes FOREVER (18 hours last time I tried it). The current process is to take a line of the csv, parse it to see if it exists in my master array, and either create a new entry or add the data to an existing entry in the array. Is there a better way to do this? It seems the last item would take exponentially longer than the first.

Once this large file is created, parsing it seems to take quite a while as well. Should I move away from writing to a csv output and go with JSON for speed of data massaging? or even a lightweight db?


问:
Terminology: queue versus fifo
When referring to or documenting a typical lock-free circular data structure (or class or object) used to communicate between arbitrarily long asynchronous threads or processors: "queue", "fifo" or "FIFO" are commonly used. Is there a technical reason why one term might be the more accurate or better communicative usage in some situation over the other term. </p>

答:
The terms FIFO and queue are interchangeable.

In most programming languages, queue and stack terms are preferred to FIFO and LIFO, and to many programmers, they will feel more descriptive. As Nick Alexeev noted, FIFO is more common in hardware.

Finally, don't use lowercase fifo: FIFO is an acronym, which means that it should be written in capitals.

Title: Terminology: queue versus fifo


答:
Queue can also mean a priority queue or a timing queue where elements are pulled out based on how soon or in which order they should be handled they should be handled. This is common in event based architectures to handle timeouts. It may or may not be an actual data structure or just a virtual one that you pop an event off from.

However in the context of data structures queue and FIFO are interchangeable.

Title: Terminology: queue versus fifo

Body: When referring to or documenting a typical lock-free circular data structure (or class or object) used to communicate between arbitrarily long asynchronous threads or processors: "queue", "fifo" or "FIFO" are commonly used. Is there a technical reason why one term might be the more accurate or better communicative usage in some situation over the other term. </p>


问:
How bad can it be to lack teamwork when you are a programmer?
I'm still at school, and I know I have problems dealing with other people.

I'm not an angry or shy or different, I just like to work my way and with my opinions while respecting other's, I have a big curiosity and hunger for knowledge, but I lack practice and I guess people don't want to work with me because they might fear I would talk some kind of morale. (For example I started to learn programming using linux instead of windows, even if I use windows a lot. And I have a mac).

What happens to programmers who lack teamwork? Where does the problems begin? Does being a good programmer compensate at least a little? Is it normal for a programmer to have a vision about his work instead of just doing what he is told?

答:
Since you are just getting ready to go into the work force, I'm going to point out something else.

Entry level programmers are never superstars. You can't go into a job thinking you are better than everyone else because demonstrably, you are not. You have been competing with other people at your level, so you can think, I'm better than these people, I must be a great programmer.

But someone fresh out of school does not know what the person who has ten years of professional experience knows. You just don't know it yet. Now I admit not everyone with lots of experience is a superstar either and just being entry level doen't mean you can't be a decent programmer. It doesn't even mean you can't become a superstar with less seasoning than some other people (Well some will never be superstars, but thats OK too).

But you won't have the credibilty to get your ideas implemented until you are something other than the most junior person on the team. To get that credibility, you need to be a team player. You need to learn about the business domain and how businesses operate. You need to understand that your personal needs and wants are irrelevant in the workplace most places. You are going to be hired to do a specific job and produce results. Until you have produced some of them, people will be skeptical of whatever you suggest even if you are correct. You have to walk the walk before you can talk the talk.