答:
I agree with Friend 1

From a compiler viewpoint, it doesn't matter... and option 2 will only save you a few bytes of file-size on your gigaByte hard-drive

From a human perspective, it doesn't matter to you which way you use today, as you know what you have written.

But when you come back to it in a day, week, month or year - or someone else comes back to it, Option 2 will be much less readable and much less understandable.


问:
Is it still worth learning desktop gui development?
For the last couple of years, all of the serious projects I have worked on have been either web based, or had a non graphical user interface (services, command line scripts etc...).  I can throw together a WinForms app or do some simple WPF when needed, but I've never really delved into some of the lower level API's like MFC or QT.

I understand that this depends on the situation but in general is it still worth taking the time to learn desktop development well or are applications moving to the web and mobile devices at a pace which makes this knowledge less relevant?  Also, do you expect developers you work with to have desktop gui expertise?

答: Even if you never intend to do desktop dev, I would suggest you get enough experience that you would have an informed opinion on when it is better to use a desktop solution over a web client.</p>

ContentLicense: CC BY-SA 2.5


问:
Third party libraries in an open-source C# project
I'm going to start an open source project from scratch, using git (via github) to manage the source. The project will be written in C# and will depend on at least two external libraries (more are likely to come). I wonder how I should reference the libraries, and the following ideas came to my mind:

A folder within the project that contains all external libraries as dll

This would mean I have the dll files in my repo, which I think is bad, because it isn't source. Also, I don't know how Visual Studio (or other IDEs) store the path the libraries, if they use absolute paths, that would be impossible.

Get the external libraries via nuget

This would be a clean and nice way to have the libraries organized, but what what if a library I need doesn't have a nuget-package? I can't just create one, can I?

Storing the source of the external library as part of my repo

Sounds like a stupid idea, it would make updating the libraries a pain.

Reference the repositories of the other projects via git somehow.

Sounds good, I could make my own fork of it to keep a state or just point to a commit. But is that even possible? Is that a good way?

tl;dr: How should I handle external libraries in an open-source C# project?

答:
I suspect I may get downvoted for this, but I wanted to throw this out there anyway.

I think including the DLLs themselves is really not a bad idea.

Sure, they aren't text; but that is true of plenty of asset types that commonly are included in source repositories (e.g., images).

Sure, you can't really diff them; but that is true of other compiled resources that are also often included in repositories (e.g., minified & compressed JavaScript files).

Generally speaking, they shouldn't be very large (I seldom see DLLs that are more than a Mb or two); so bloating your repo and making it annoying to clone shouldn't be an issue, either.

I recognize that NuGet is the de facto standard for managing external dependencies in .NET. However, in the event that a NuGet package isn't available for the library you want to use, I really think including the DLL is the least painful approach, without any seriously awful drawbacks that I can see.

This is assuming you are not going to frequently update these DLLs (i.e., they're libraries that have reached maturity, and release new versions on an infrequent basis at most). In this case the folder containing the DLLs is very much a snapshot of your dependencies at any point in history. When you update your dependency, you can just update the DLL.

If, on the other hand, these are libraries that are changing very frequently (e.g., they're your own libraries which you're working on in parallel with this project), then I take back everything I just said. You don't want to clutter your Git history with constant DLL updates. In this case I would actually suggest learning more about Git submodules, or using Doc Brown's script idea.

ContentLicense: CC BY-SA 3.0


问:
A programming language that allows you to define new limits for simple types
Many languages like C++, C#, and Java allow you to create objects that represent simple types like integer or float. Using a class interface you can override operators and perform logic like checking if a value exceeds a business rule of 100.

I'm wondering if it's possible in some languages to define these rules as annotations or attributes of a variable/property.

For example, in C# you might write:

```<code>[Range(0,100)]
public int Price { get; set; }
</code>```

Or maybe in C++ you could write:

```<code>int(0,100) x = 0;
</code>```

I've never seen something like this done, but given how dependent we have become on data validation before storage. It's strange that this feature hasn't been added to languages.

Can you give example of languages where this is possible?

答:
Ranges are a special case of invariants. From Wikipedia:

An invariant is a condition that can be relied upon to be true during execution of a program.

A range [a, b] can be declared as a variable x of type Integer with the invariants x >= a and x <= b.

Therefore Ada or Pascal subrange types aren't strictly neccessary. They could be implemented with an integer type with invariants.


问:
I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?
My day job is  java/web developer. I have been using eclipse for ~5years. I think its excellent and I also use Webstorm for javascript and html/jsp.

I do on occasion need to ssh into server and mess around with config files; for this I use vi and it pains me. I have to get up a webpage listing the syntax/commands : press escape, then asterix, turn around three times and the text will be entered two lines above your cursor. Its so unintuitive to me, and I imagine anyone who grew up in the late eighties nineties.

Here are the main reasons I think eclipse is brilliant(and I assume other IDE's), and do not switch to emacs and/or vim.

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

availablity of 3rd party plugins - eg
findbugs/checkstyle.

One of the arguments I hear is that with emacs/vim you can create your own plugins - well OK, but you can do that in eclipse too. But you don't need to as everything is already there!  Its like saying buy this half built car, you can build the rest yourself.

Why are people using emacs/vim ? Do people who use it actually work on complex object-oriented projects in large organisations ?

What are the reasons to switch to vim/emacs. How would my productivity increase if I did switch?

答:
The best tool (in the short term) is one you're highly proficient with.

People use 30+ year old technology because they're highly proficient with it. They built their workflow and habits around these tools. If you're more familiar with a modern IDE like Eclipse, there isn't much reason to switch. Learning how to use Eclipse more efficiently is a better investment of your time (e.g. use Mylyn).


问:
Testcase runner for parametrized testcases
Let me explain my situation. I'm planning a kind of test case runner for doing testcases on external devices, which are microcontroller based. Lets consider the devices:

Device 1

Device 2

There exist a lot of test cases which can be run with one of the devices above. For example:

Testcase 1

Testcase 2

The main reason that all the testcases can be run with any device is, that the testcases validates some standard and this software should be extensible for future devices.

The testcases itself must be runnable with changing parameters. For example Testcase 1 does some Timing Verification the testcase needs as input parameter the datarate: 4800, 9600, 19200.

Now hoping you understand the situation, let me explain my design questions.

For implementing the test cases I thought about an Attribute based approach, like nunit does it.
The more complicated problem is, how to define the parametrized testcases?
Like this:

```<code>Device 1:
   Testcase 1:
      datarate: 4800, 9600, 19200
   Testcase 2:
      supply: 1, 2, 3

Device 2:
   Testcase 1:
      datarate: 9600, 19200, 38400
   Testcase 2:
      supply: 3, 4, 5
</code>```

How would you design such a framework?

I've done a similar desin in python where I had for every device a XML containing the testcase definitions like:

```<code><Testcase="Testcase 1" datarate=4800/>
<Testcase="Testcase 1" datarate=9600/>
<Testcase="Testcase 1" datarate=19200/>
</code>```

答:
The method I prefer is based on a factory design pattern (which is different that most unit testing frameworks for .NET, but since you are designing your own framework starting from scratch may be ok).  In this scenario each common test case is a class unto itself (based on a common TestCaseBase class) then you have a factory that generates each test case, using the constructors to set parameters.

For instance:

```<code>public interface ITestCase
{
   void Init();
   void DoTest();
   void Cleanup();
}

public class DataRateTest : ITestCase
{
   public DataRateTest (string device, int datarate1,int datarate2,int datarate3)
   {
   }
   public void Init() { }
   public void DoTest() { }
   public void Cleanup() { }
}

public class TestCaseFactory
{
  public static List<ITestCase> GetTestCaseFor(string device, string testName)
  {
     List<ITestCase> tests = new List<ITestCase>();
     switch(device+"-"+testName)
     {
         case "Device1-Test1":
              tests.Add( new DataRateTest(device,4800, 9600, 19200));
              break;

         case "Device1-Test2":
              tests.Add( SupplyTest(device,3, 4, 5));
              break;

         case "Device1-ALL":
              tests.Add( new DataRateTest(device,4800, 9600, 19200));
              tests.Add( SupplyTest(device,3, 4, 5));
              break;
     }

     if (0 == tests.Count())
        throw new NotImplementedException("No test case found for:"+device+"-"+testName);
  }
}
</code>```

Body:
The method I prefer is based on a factory design pattern (which is different that most unit testing frameworks for .NET, but since you are designing your own framework starting from scratch may be ok).  In this scenario each common test case is a class unto itself (based on a common TestCaseBase class) then you have a factory that generates each test case, using the constructors to set parameters.

For instance:

public interface ITestCase
{
   void Init();
   void DoTest();
   void Cleanup();
}

public class DataRateTest : ITestCase
{
   public DataRateTest (string device, int datarate1,int datarate2,int datarate3)
   {
   }
   public void Init() { }
   public void DoTest() { }
   public void Cleanup() { }
}

public class TestCaseFactory
{
  public static List<ITestCase> GetTestCaseFor(string device, string testName)
  {
     List<ITestCase> tests = new List<ITestCase>();
     switch(device+"-"+testName)
     {
         case "Device1-Test1":
              tests.Add( new DataRateTest(device,4800, 9600, 19200));
              break;

         case "Device1-Test2":
              tests.Add( SupplyTest(device,3, 4, 5));
              break;

         case "Device1-ALL":
              tests.Add( new DataRateTest(device,4800, 9600, 19200));
              tests.Add( SupplyTest(device,3, 4, 5));
              break;
     }

     if (0 == tests.Count())
        throw new NotImplementedException("No test case found for:"+device+"-"+testName);
  }
}


问:
Why are nested loops considered bad practice?
My lecturer mentioned today that it was possible to "label" loops in Java so that you could refer to them when dealing with nested loops. So I looked up the feature as I didn't know about it and many places where this feature was explained it was followed by a warning, discouraging nested loops.

I don't really understand why? Is it because it affects the readability of the code? Or is it something more "technical"?

答:
Given the case of many nested loops you end up with polynomial time.  For example given this pseudo code:

```<code>set i equal to 1
while i is not equal to 100
  increment i
  set j equal to 1
  while j is not equal to i
    increment j
  end
 end
</code>```

This would be considered O(n^2) time which  would be a graph similar to:

Where the y-axis is the amount of time your program takes to terminate and the x-axis is the amount of data.

If you get too much data your program will be so slow nobody will wait for it. and It's not that much around 1,000 data entries I believe will take it too long.

Body:
Given the case of many nested loops you end up with polynomial time.  For example given this pseudo code:

set i equal to 1
while i is not equal to 100
  increment i
  set j equal to 1
  while j is not equal to i
    increment j
  end
 end

This would be considered O(n^2) time which  would be a graph similar to:

Where the y-axis is the amount of time your program takes to terminate and the x-axis is the amount of data.

If you get too much data your program will be so slow nobody will wait for it. and It's not that much around 1,000 data entries I believe will take it too long.


答:
Nested loops are frequently (but not always) bad practice, because they're frequently (but not always) overkill for what you're trying to do.  In many cases, there's a much faster and less wasteful way to accomplish the goal you're trying to achieve.

For example, if you have 100 items in list A, and 100 items in list B, and you know that for each item in list A there's one item in list B that matches it, (with the definition of "match" left deliberately obscure here), and you want to produce a list of pairs, the simple way to do it is like this:

```<code>for each item X in list A:
  for each item Y in list B:
    if X matches Y then
      add (X, Y) to results
      break
</code>```

With 100 items in each list, this will take an average of 100 * 100 / 2 (5,000) matches operations.  With more items, or if the 1:1 correlation is not assured, it becomes even more expensive.

On the other hand, there's a much faster way to perform an operation like this:

```<code>sort list A
sort list B (according to the same sort order)
I = 0
J = 0
repeat
  X = A[I]
  Y = B[J]
  if X matches Y then
    add (X, Y) to results
    increment I
    increment J
  else if X < Y then
    increment I
  else increment J
until either index reaches the end of its list
</code>```

If you do it this way, instead of the number of matches operations being based on length(A) * length(B), it's now based on length(A) + length(B), which means your code will run much faster.

Title: Why are nested loops considered bad practice?

Body:
My lecturer mentioned today that it was possible to "label" loops in Java so that you could refer to them when dealing with nested loops. So I looked up the feature as I didn't know about it and many places where this feature was explained it was followed by a warning, discouraging nested loops.

I don't really understand why? Is it because it affects the readability of the code? Or is it something more "technical"?

Body:
Nested loops are frequently (but not always) bad practice, because they're frequently (but not always) overkill for what you're trying to do.  In many cases, there's a much faster and less wasteful way to accomplish the goal you're trying to achieve.

For example, if you have 100 items in list A, and 100 items in list B, and you know that for each item in list A there's one item in list B that matches it, (with the definition of "match" left deliberately obscure here), and you want to produce a list of pairs, the simple way to do it is like this:

for each item X in list A:
  for each item Y in list B:
    if X matches Y then
      add (X, Y) to results
      break

With 100 items in each list, this will take an average of 100 * 100 / 2 (5,000) matches operations.  With more items, or if the 1:1 correlation is not assured, it becomes even more expensive.

On the other hand, there's a much faster way to perform an operation like this:

sort list A
sort list B (according to the same sort order)
I = 0
J = 0
repeat
  X = A[I]
  Y = B[J]
  if X matches Y then
    add (X, Y) to results
    increment I
    increment J
  else if X < Y then
    increment I
  else increment J
until either index reaches the end of its list

If you do it this way, instead of the number of matches operations being based on length(A) * length(B), it's now based on length(A) + length(B), which means your code will run much faster.


答:
Nested loops are fine as long as they describe the correct algorithm.

Nested loops have performance considerations (see @Travis-Pesetto's answer), but sometimes it's exactly the correct algorithm, e.g. when you need to access every value in a matrix.

Labeling loops in Java allows to prematurely break out of several nested loops when other ways to do this would be cumbersome. E.g. some game might have a piece of code like this:

```<code>Player chosen_one = null;
...
outer: // this is a label
for (Player player : party.getPlayers()) {
  for (Cell cell : player.getVisibleMapCells()) {
    for (Item artefact : cell.getItemsOnTheFloor())
      if (artefact == HOLY_GRAIL) {
        chosen_one = player;
        break outer; // everyone stop looking, we found it
      }
  }
}
</code>```

While code like the example above may sometimes be the optimal way to express a certain algorithm, it is usually better to break this code into smaller functions, and probably use return instead of break. So a break with a label is a faint code smell; pay extra attention when you see it.

Body:
Nested loops are fine as long as they describe the correct algorithm.

Nested loops have performance considerations (see @Travis-Pesetto's answer), but sometimes it's exactly the correct algorithm, e.g. when you need to access every value in a matrix.

Labeling loops in Java allows to prematurely break out of several nested loops when other ways to do this would be cumbersome. E.g. some game might have a piece of code like this:

Player chosen_one = null;
...
outer: // this is a label
for (Player player : party.getPlayers()) {
  for (Cell cell : player.getVisibleMapCells()) {
    for (Item artefact : cell.getItemsOnTheFloor())
      if (artefact == HOLY_GRAIL) {
        chosen_one = player;
        break outer; // everyone stop looking, we found it
      }
  }
}

While code like the example above may sometimes be the optimal way to express a certain algorithm, it is usually better to break this code into smaller functions, and probably use return instead of break. So a break with a label is a faint code smell; pay extra attention when you see it.


问:
Project implementation details in node.js
I am working as a software engineer turned team leader in a large software company. One of my areas of strength is node.js, and we are in the process of moving a lot of our services to separate node.js services, which is proving to be very successful so far.

However, I am supposed to stop day to day development of small node.js services, and simply lay down a proper specification, so that one of my team members can work on the actual code.

I am aware of tools like UML, but I don't think they apply to a system with apis built with node.js/express. I have made a few flowcharts, but my seniors want me to be very complete with the spec, down to each implementation detail.

How I can achieve this? Should I design objects in UML and make my developers make javascript objects which can be used in express routes?

答:
Apart from the obvious text description, I think that a sequence diagram would do the job. Any more specific and You might as well write the code.

Sequence diagrams


答:
Yes, but not in the way you are thinking.

GUI Programming is not any more difficult nor does it require specialized skills apart from familiarity with the gui programming interface. Hooking up buttons and windows and controls isn't terribly difficult and is pretty easy with modern programming environments compared to the early days with stuff like MFC. GUI programming is stuff that's fairly easy to learn when its demanded.

However, while hooking up buttons and text boxes is fairly easy, knowing when and where to place buttons, and designing a gui to be used by human beings is very difficult. That is a very valuable and important skill to have. However, the design principles that apply to native interfaces vs the web are very similar.

So learn how to design good user interfaces that are effective and don't confuse users, and you'll get familiarity with the programming for them for free.

Title: Is it still worth learning desktop gui development?

Body:
For the last couple of years, all of the serious projects I have worked on have been either web based, or had a non graphical user interface (services, command line scripts etc...).  I can throw together a WinForms app or do some simple WPF when needed, but I've never really delved into some of the lower level API's like MFC or QT.

I understand that this depends on the situation but in general is it still worth taking the time to learn desktop development well or are applications moving to the web and mobile devices at a pace which makes this knowledge less relevant?  Also, do you expect developers you work with to have desktop gui expertise?


问:
What's the difference between a stream and a queue?
What's the difference between a stream and a queue?  They both have the concept of an ordered set of elements, but tend to have different implementations and a different vocabulary of 'insert'/'extract' (streams) vs. 'enqueue'/'dequeue' (queue).  Are these interchangable?  Do they suggest different concepts or patterns?  If so, what are the differences?</p>

答:
The basic difference is in the way they're used.  In a stream, you usually only use one side of the operation: you open a stream to read, or write, but not both.  Whereas with a queue, you're putting items on and taking them off.

Also, queues are very strict about the order in which you put things on and take them off, while streams often (but not always) support a Seek operation, especially if you're reading from them.


问:
Is it a bad practice to modify code strictly for testing purposes
I have a debate with a programmer colleague about whether it is a good or bad practice to modify a working piece of code only to make it testable (via unit tests for example).

My opinion is that it is OK, within the limits of maintaining good object oriented and software engineering practices of course (not "making everything public", etc).

My colleague's opinion is that modifying code (which works) only for testing purposes is wrong.

Just a simple example, think of this piece of code that is used by some component (written in C#):

```<code>public void DoSomethingOnAllTypes()
{
    var types = Assembly.GetExecutingAssembly().GetTypes();

    foreach (var currentType in types)
    {
        // do something with this type (e.g: read it's attributes, process, etc).
    }
}
</code>```

I have suggested that this code can be modified to call out another method that will do the actual work:

```<code>public void DoSomething(Assembly asm)
{
    // not relying on Assembly.GetExecutingAssembly() anymore...
}
</code>```

This method takes in an Assembly object to work on, making it possible to pass your own Assembly to do the testing on. My colleague didn't think this is a good practice.

What is considered a good and common practice ?

答:
There are some serious differences between your examples.  In the case of DoSomethingOnAllTypes(), there is an implication that do something is applicable to types in the current assembly.  But DoSomething(Assembly asm) explictly indicates that you can pass any assembly to it.

The reason I point this out is that a lot of dependency-injection-for-testing-only steps outside the bounds of the original object.  I know you said "not 'making everything public'", but that's one of the biggest errors of that model, followed closely by this one: opening the object's methods up to uses they aren't intended for.


问:
Extension objects pattern
In this MSDN Magazine article Peter Vogel describes Extension Objects pattern.

What is not clear is whether extensions can be later implemented by client code residing in a separate assembly.

And if so how in this case can extension get access to private members of the object being extended?

I quite often need to set different access levels for different classes.

Sometimes I really need that descendants does not have access to the member but separate class does. (good old friend classes)

Now I solve this in C# by exposing callback properties in interface of the external class and setting them with private methods. This also allows to adjust access: read only or read|write depending on the desired interface.

```<code>class Parent
{
    private int foo;

    public void AcceptExternal(IFoo external)
    {
        external.GetFooCallback = () => this.foo;
    }
}

interface IFoo
{
    Func<int> GetFooCallback {get;set;}
}
</code>```

Other way is to explicitly implement particular interface.

But I suspect more aspproaches exist.

Update 1

New Peter's article makes it a bit clearer.

答:
I think that you missed a little bit of the point of the article. When he was talking about think in the Extension, he was talking about an concept, and not a particular Design Pattern. There are several Design Patterns that would allow for extension of your objects, this really depends on how you want to do it. Let me quote what 2 think could be the best to allow for extension:

Decorator Pattern:

```<code>private interface IPrice
{
    int Price { get; }
}

private class PriceDecorator : Pizza
{
    IPrice _price;

    protected virtual int OriginalPrice { get { return 0; } }

    public virtual int Price
    {
        get { return OriginalPrice + _price.Price; }
    }
    protected PriceDecorator() { }

    public PriceDecorator(IPrice price)
        : this()
    {
        _price = price;
    }
}

private class Pizza : PriceDecorator
{
    public Pizza(IPrice price) : base(price){}
    protected Pizza()  { }

    protected override int OriginalPrice
    {
        get { return 10; }
    }
}

class Cheese : PriceDecorator
{
    protected Cheese()  {    }
    public Cheese(IPrice price) : base(price) { }

    protected override int OriginalPrice
    {
        get { return 2; }
    }
}

class Pepperoni : PriceDecorator
{
    protected Pepperoni() {}
    public Pepperoni(IPrice price) : base(price){ }

    protected override int OriginalPrice
    {
        get { return 1; }
    }
}

class test
{
    void run()
    {
        var pizzaWithCheese = new Pizza(new Cheese());
        var pizzaWithCheeseAndPepperoni = new Pizza(new Cheese(new Pepperoni()));
    }
}
</code>```

Strategy Design Pattern:

You can read more here

```<code>abstract class StrategyBase
{
    public abstract void DoSomething();
}

class ConcreteStrategyA : StrategyBase
{
    public override void DoSomething()
    {
        Console.WriteLine("Called ConcreteStrategyA.DoSomething()");
    }
}

class ConcreteStrategyB : StrategyBase
{
    public override void DoSomething()
    {
        Console.WriteLine("I did something!");
    }
}

/// This is the class that you allow extension, using any of the strategies
class Context
{
    private StrategyBase _strategy;

    public Context(StrategyBase strategy)
    {
        this._strategy = strategy;
    }

    public void DoSomething()
    {
        _strategy.DoSomething();
    }
}

// Use it like this:
var c = new Context(new ConcreteStrategyA());
c.DoSomething();
</code>```

ContentLicense: CC BY-SA 4.0

Title: Extension objects pattern

Body:
I think that you missed a little bit of the point of the article. When he was talking about think in the Extension, he was talking about an concept, and not a particular Design Pattern. There are several Design Patterns that would allow for extension of your objects, this really depends on how you want to do it. Let me quote what 2 think could be the best to allow for extension:

Decorator Pattern:

private interface IPrice
{
    int Price { get; }
}

private class PriceDecorator : Pizza
{
    IPrice _price;

    protected virtual int OriginalPrice { get { return 0; } }

    public virtual int Price
    {
        get { return OriginalPrice + _price.Price; }
    }
    protected PriceDecorator() { }

    public PriceDecorator(IPrice price)
        : this()
    {
        _price = price;
    }
}

private class Pizza : PriceDecorator
{
    public Pizza(IPrice price) : base(price){}
    protected Pizza()  { }

    protected override int OriginalPrice
    {
        get { return 10; }
    }
}

class Cheese : PriceDecorator
{
    protected Cheese()  {    }
    public Cheese(IPrice price) : base(price) { }

    protected override int OriginalPrice
    {
        get { return 2; }
    }
}

class Pepperoni : PriceDecorator
{
    protected Pepperoni() {}
    public Pepperoni(IPrice price) : base(price){ }

    protected override int OriginalPrice
    {
        get { return 1; }
    }
}

class test
{
    void run()
    {
        var pizzaWithCheese = new Pizza(new Cheese());
        var pizzaWithCheeseAndPepperoni = new Pizza(new Cheese(new Pepperoni()));
    }
}

Strategy Design Pattern:

You can read more here

abstract class StrategyBase
{
    public abstract void DoSomething();
}

class ConcreteStrategyA : StrategyBase
{
    public override void DoSomething()
    {
        Console.WriteLine("Called ConcreteStrategyA.DoSomething()");
    }
}

class ConcreteStrategyB : StrategyBase
{
    public override void DoSomething()
    {
        Console.WriteLine("I did something!");
    }
}

/// This is the class that you allow extension, using any of the strategies
class Context
{
    private StrategyBase _strategy;

    public Context(StrategyBase strategy)
    {
        this._strategy = strategy;
    }

    public void DoSomething()
    {
        _strategy.DoSomething();
    }
}

// Use it like this:
var c = new Context(new ConcreteStrategyA());
c.DoSomething();


答:
A stream is not really a data structure as such (conceptually), but is a sequence of digitally encoded coherent signals (packets of data or data packets) used to transmit or receive information".  So basically a sequence of data.

A queue is a simple FIFO mechanism allowing you to add items to the back of the queue or take from the front.

Streams always have a source, e.g. a file, network location, etc.  A Queue does not inherently contain any data.

So essentially they are quite different in concept and as Mason pointed out, they are used differently.

Body: What's the difference between a stream and a queue?  They both have the concept of an ordered set of elements, but tend to have different implementations and a different vocabulary of 'insert'/'extract' (streams) vs. 'enqueue'/'dequeue' (queue).  Are these interchangable?  Do they suggest different concepts or patterns?  If so, what are the differences?</p>


问:
How is determined an impact of a requirement change on the existing code?
How companies working on large projects evaluate an impact of a single modification on an existing code?

Since my question is probably not very clear, here's an example:

Let's take a sample business application which deals with tasks. In the database, each task has a state, 0 being "Pending", ... 5 - "Finished".

A new requirement adds a new state, between 2nd and 3rd one.

It means that:

A constraint on the values 1 - 5 in the database must be changed,

Business layer and code contracts must be changed to add a new state,

Data access layer must be changed to take in account that, for example the state StateReady is now 6 instead of 5, etc.

The application must implement a new state visually, add new controls for it, new localized strings for tool-tips, etc.

When an application is written recently by one developer, it's more or less easy to predict every change to do. On the other hand, when an application was written for years by many people, no single person can anticipate every change immediately, without any investigation.

So since this situation (such changes in requirements) is very frequent, I imagine there are already some clever techniques and ways to predict the impact. Is there any? Do you know any books which deal about this subject?

Note: my question is not related to How do you deal with changing requirements? question. In fact, I'm not interested in evaluating the cost of a change, but rather the way to predict the parts of an application which will be concerned by the change. What will be those changes and how difficult they are really doesn't matter in my question.

答: How much of an impact it will have is not a problem that can be solved mechanically. You'll have to evaluate how your current system behaves, what kind of work is required to implement it, and what risks go along with it, and it will require human judgement.</p>


问:
What did Rich Hickey mean when he said, "All that specificity [of interfaces/classes/types] kills your reuse!"
In Rich Hickey's thought-provoking goto conference keynote "The Value of Values" at 29 minutes he's talking about the overhead of a language like Java and makes a statement like, "All those interfaces kill your reuse."  What does he mean?  Is that true?

In my search for answers, I have run across:

The Principle of Least Knowledge AKA The Law of Demeter which encourages airtight API interfaces.  Wikipedia also lists some disadvantages.

Kevlin Henney's Imperial Clothing Crisis which argues that use, not reuse is the appropriate goal.

Jack Diederich's "Stop Writing Classes" talk which argues against over-engineering in general.

Clearly, anything written badly enough will be useless.  But how would the interface of a well-written API prevent that code from being used?  There are examples throughout history of something made for one purpose being used more for something else.  But in the software world, if you use something for a purpose it wasn't intended for, it usually breaks.

I'm looking for one good example of a good interface preventing a legitimate but unintended use of some code.  Does that exist?  I can't picture it.

答:
I think slide 13 at his presentation (The Value of Values) helps to understand this:

Values

Don’t need methods

I can send you values without code

  and you are fine

My understanding is, Hickey suggests that if I need to, say, double the value you sent to me, I simply write code looking like

```<code>    MyValue = Double(YourValue)
</code>```

You see, above code is the same, no matter what kind value you sent - sort of a perfect reuse.

Now, how this would look like in the language having objects and interfaces?

```<code>    Doublable MyValue = YourValue.Double()
</code>```

oh wait! what if YourValue doesn't implement Doublable? not that it can't be doubled, it may perfectly be but... what if there's just no method Double? (what if there's a method called say TwiceAsMuch?)

Uh oh we've got a problem. YourValue.Double won't work, it can't be reused anymore. Per my reading of above slide, this is about what Hickey meant when he said, "All those interfaces kill your reuse!"

You see, interfaces assume that objects are passed around "along with their methods", along with code that operates on these. To use objects, one need to understand how to invoke that code, what method to call.

When expected method is missing, there is a problem, even though semantically, desired operation makes perfect sense for an object. As stated in the presentation, values don't need methods ("I can send you values without code and you are fine"), allowing to write code dealing with them in a generic manner.

Side note: notion of passing around code-less values somehow reminds me of a Flyweight pattern in OOP.

an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory...  Flyweight objects are by definition value objects. The identity of the object instance is of no consequence therefore two Flyweight instances of the same value are considered equal...

Flyweight usages I've seen typically followed the same approach of stripping off the code (methods, interfaces) from objects and passing stuff around around as, well, code-less values, expecting that receiving code has means necessary to operate on these.

This feels pretty much as at the slide, "values don’t need methods. I can send you values without code and you are fine".

Body:
I think slide 13 at his presentation (The Value of Values) helps to understand this:

Values

Don’t need methods

I can send you values without code

  and you are fine

My understanding is, Hickey suggests that if I need to, say, double the value you sent to me, I simply write code looking like

    MyValue = Double(YourValue)

You see, above code is the same, no matter what kind value you sent - sort of a perfect reuse.

Now, how this would look like in the language having objects and interfaces?

    Doublable MyValue = YourValue.Double()

oh wait! what if YourValue doesn't implement Doublable? not that it can't be doubled, it may perfectly be but... what if there's just no method Double? (what if there's a method called say TwiceAsMuch?)

Uh oh we've got a problem. YourValue.Double won't work, it can't be reused anymore. Per my reading of above slide, this is about what Hickey meant when he said, "All those interfaces kill your reuse!"

You see, interfaces assume that objects are passed around "along with their methods", along with code that operates on these. To use objects, one need to understand how to invoke that code, what method to call.

When expected method is missing, there is a problem, even though semantically, desired operation makes perfect sense for an object. As stated in the presentation, values don't need methods ("I can send you values without code and you are fine"), allowing to write code dealing with them in a generic manner.

Side note: notion of passing around code-less values somehow reminds me of a Flyweight pattern in OOP.

an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory...  Flyweight objects are by definition value objects. The identity of the object instance is of no consequence therefore two Flyweight instances of the same value are considered equal...

Flyweight usages I've seen typically followed the same approach of stripping off the code (methods, interfaces) from objects and passing stuff around around as, well, code-less values, expecting that receiving code has means necessary to operate on these.

This feels pretty much as at the slide, "values don’t need methods. I can send you values without code and you are fine".


问:
Is it good to have an interface plenty of methods which belong to different concepts, just to preserve the Liskov's Principle?
I'm currently studying a course based on Software Design and I had a discussion in class with my professor and some classmates about a problem represented by the next scenario:

Scenario

Imagine we have a graphic application which lets us plan the interior design of our future house using a perspective from top. We are able
  to add or remove some elements like furniture and change their
  position, but obviously, we can't move the walls of the house because
  it was already built.

Solution 1

To solve this problem, some of my classmates proposed a solution that could be expressed using the following UML diagram:

As you can see, they agreed on the use of a common interface called "Drawable" which represents the graphical objects displayed on the UI. The general class "App" manages a list of Drawables, and each of them has a set of methods. This interface is implemented by different classes such as Furniture, Wall or Window. The thing is that a Furniture object could be moved, but not the Walls nor the Windows. So, a Furniture would implement the 'move' method defined in Drawable. In contrast, Wall and Window simply will write it empty.

At this point, other classmates and I complained about this decission because the design does not require to fulfill with the constraints (like moving or not Drawable objects, depending on their nature). This way, the design will allow some new objects could be moved, although they probably shouldn't be. However, the professor said this design is good because it's flexible and transparent for the App class, because this class doesn't know what kind of instance is managing.

Extended case

In addition, we could think on an extreme case where we add several methods to the Drawable interface, such as 'sell', 'open' and 'lend'. Using the same approach described above, we will have an interface which could be able to do anything, like Superman. Therefore, I believe this is a bad design solution due to we are mixing behaviors which belong to different concepts (Movable, Sellable, Openable, and so on). Also, we are allowing a Wall object could implement the 'sell' method, which completely does not make sense... but my professor still insisted on his point of view and he didn't see the problem.

Solution 2 (based on the extended case)

Other people suggested we could add those interfaces (Movable, Sellable, Openable) and each of them would inherit from the Drawable interface. That way:

A Wall would implement Drawable directly

A Furniture would implement Movable and Sellable

A Window would implement just Openable

The next diagram summarizes this approach:

[Edit: The Drawable's move method should be removed, this is a mistake because it is now placed into the Movable interface]

Questions and Doubts

Finally, once you can figure out the problem, could you help me and answer these questions, please?

Aren't we breaking the Single Responsibility Principle with this super-mega-god-interface?

Are both approaches valid against the Liskov's Substitution Principle? I think it's broken in the first case because the post-conditions are broken due to some methods don't do anything. Anyway, in the second approach I'm not sure as well because of the interfaces inheritance tree

Maybe, another alternative could be the definition of basic Drawable objects (with 'click' and 'draw' methods). Thus, we may take advantage of some kind of mechanism like the Decorator pattern in order to add behaviors dynamically. But how?

If we use a language without interfaces such as JavaScript or Python, how can we deal with this problem?

答:
Solution 1 violates not only Liskov's Substitution Principle but it also violates the Interface Segregation Principle and the Single Responsability Principle. Solution 2 is the correct approach (see correction at the bottom).

Same as above

You can do that and solution 2 at the same time, they are not exclusive.

You should use non-OO solutions and patterns.

CORRECTION: Solution 2 is also wrong. Sellable and Movable must not inherit from Drawable. They should be separate and unrelated interface.


答:
Aren't we breaking the Single Responsibility Principle with this super-mega-god-interface?

Not exactly, because the interface isn't doing anything. It has no responsibilities.

You are breaking Liskov Substitution Principle and Interface Segregation Principle though.

LSP because you're writing methods that do nothing, just to make it fit the interface (ie. What is true of IDrawable -- that you can move it -- is not true of Wall).

ISP because you'll have situations like a trade method, which should have access to Buy and Sell methods, but will also have access to Draw.

Are both approaches valid against the Liskov's Substitution Principle? I think it's broken in the first case because the post-conditions are broken due to some methods don't do anything. Anyway, in the second approach I'm not sure as well because of the interfaces inheritance tree

It's just as broken in the second case as the first.

Edit: On second thoughts, it isn't. But it is still broken. It doesn't seem automatically true that everything that could have a Move method will also have a Draw method. It might be true in your case but, if you later find yourself wanting to pass an object with a Move method into a method that receives an IMovable, you're going to have to implement Draw on that object, even if you don't need it.

And it gains you nothing over a third solution ...

Maybe, another alternative could be the definition of basic Drawable objects (with 'click' and 'draw' methods). Thus, we may take advantage of some kind of mechanism like the Decorator pattern in order to add behaviors dynamically. But how?

The best alternative is to segregate your interfaces fully. You can still have objects with lots of methods (but Dependency-Inversion Principle and Single Responsibility Principle dictate you must push the logic down into services), but they only have to implement the interfaces they need. Wall shouldn't implement IMovable, if it can't be moved.

```<code>public class Wall : IDrawable
public class Furniture : IDrawable, IMovable, ISellable
public class Window : IDrawable, IOpenable
</code>```

Nothing here dictates that any of those interfaces must derive from another.

```<code>public interface IDrawable
{
    void Draw(Canvas canvas);
}

public interface IMovable
{
    void MoveTo(int x, int y);
}

etc
</code>```

You should then manage your list of IDrawables, which you can only be sure implement Draw(), and cast to see if other methods are available.

For example,

```<code>ITradable tradable = drawable as ITradable;
if (tradable != null)
{
    tradable.Trade(buyer, seller);
}
</code>```

You're going to have to do the above in your option 2 anyway, so why tie everything to IDrawable?

If we use a language without interfaces such as JavaScript or Python, how can we deal with this problem?

OO languages tend to support at least one of three things:

Interfaces (use ... interfaces)

Multiple inheritance (use abstract classes)

Dynamic types (use duck-typing; this is where Python comes in)

Prototypical languages, such as Javascript, support ... well, prototypes, which allow for a slightly modified version of duck-typing (in prototypes, you generally ask if a method exists before calling it).

Other paradigms generally handle these issues in their own way.

Title: Is it good to have an interface plenty of methods which belong to different concepts, just to preserve the Liskov's Principle?

Body:
I'm currently studying a course based on Software Design and I had a discussion in class with my professor and some classmates about a problem represented by the next scenario:

Scenario

Imagine we have a graphic application which lets us plan the interior design of our future house using a perspective from top. We are able
  to add or remove some elements like furniture and change their
  position, but obviously, we can't move the walls of the house because
  it was already built.

Solution 1

To solve this problem, some of my classmates proposed a solution that could be expressed using the following UML diagram:

As you can see, they agreed on the use of a common interface called "Drawable" which represents the graphical objects displayed on the UI. The general class "App" manages a list of Drawables, and each of them has a set of methods. This interface is implemented by different classes such as Furniture, Wall or Window. The thing is that a Furniture object could be moved, but not the Walls nor the Windows. So, a Furniture would implement the 'move' method defined in Drawable. In contrast, Wall and Window simply will write it empty.

At this point, other classmates and I complained about this decission because the design does not require to fulfill with the constraints (like moving or not Drawable objects, depending on their nature). This way, the design will allow some new objects could be moved, although they probably shouldn't be. However, the professor said this design is good because it's flexible and transparent for the App class, because this class doesn't know what kind of instance is managing.

Extended case

In addition, we could think on an extreme case where we add several methods to the Drawable interface, such as 'sell', 'open' and 'lend'. Using the same approach described above, we will have an interface which could be able to do anything, like Superman. Therefore, I believe this is a bad design solution due to we are mixing behaviors which belong to different concepts (Movable, Sellable, Openable, and so on). Also, we are allowing a Wall object could implement the 'sell' method, which completely does not make sense... but my professor still insisted on his point of view and he didn't see the problem.

Solution 2 (based on the extended case)

Other people suggested we could add those interfaces (Movable, Sellable, Openable) and each of them would inherit from the Drawable interface. That way:

A Wall would implement Drawable directly

A Furniture would implement Movable and Sellable

A Window would implement just Openable

The next diagram summarizes this approach:

[Edit: The Drawable's move method should be removed, this is a mistake because it is now placed into the Movable interface]

Questions and Doubts

Finally, once you can figure out the problem, could you help me and answer these questions, please?

Aren't we breaking the Single Responsibility Principle with this super-mega-god-interface?

Are both approaches valid against the Liskov's Substitution Principle? I think it's broken in the first case because the post-conditions are broken due to some methods don't do anything. Anyway, in the second approach I'm not sure as well because of the interfaces inheritance tree

Maybe, another alternative could be the definition of basic Drawable objects (with 'click' and 'draw' methods). Thus, we may take advantage of some kind of mechanism like the Decorator pattern in order to add behaviors dynamically. But how?

If we use a language without interfaces such as JavaScript or Python, how can we deal with this problem?

Body:
Aren't we breaking the Single Responsibility Principle with this super-mega-god-interface?

Not exactly, because the interface isn't doing anything. It has no responsibilities.

You are breaking Liskov Substitution Principle and Interface Segregation Principle though.

LSP because you're writing methods that do nothing, just to make it fit the interface (ie. What is true of IDrawable -- that you can move it -- is not true of Wall).

ISP because you'll have situations like a trade method, which should have access to Buy and Sell methods, but will also have access to Draw.

Are both approaches valid against the Liskov's Substitution Principle? I think it's broken in the first case because the post-conditions are broken due to some methods don't do anything. Anyway, in the second approach I'm not sure as well because of the interfaces inheritance tree

It's just as broken in the second case as the first.

Edit: On second thoughts, it isn't. But it is still broken. It doesn't seem automatically true that everything that could have a Move method will also have a Draw method. It might be true in your case but, if you later find yourself wanting to pass an object with a Move method into a method that receives an IMovable, you're going to have to implement Draw on that object, even if you don't need it.

And it gains you nothing over a third solution ...

Maybe, another alternative could be the definition of basic Drawable objects (with 'click' and 'draw' methods). Thus, we may take advantage of some kind of mechanism like the Decorator pattern in order to add behaviors dynamically. But how?

The best alternative is to segregate your interfaces fully. You can still have objects with lots of methods (but Dependency-Inversion Principle and Single Responsibility Principle dictate you must push the logic down into services), but they only have to implement the interfaces they need. Wall shouldn't implement IMovable, if it can't be moved.

public class Wall : IDrawable
public class Furniture : IDrawable, IMovable, ISellable
public class Window : IDrawable, IOpenable

Nothing here dictates that any of those interfaces must derive from another.

public interface IDrawable
{
    void Draw(Canvas canvas);
}

public interface IMovable
{
    void MoveTo(int x, int y);
}

etc

You should then manage your list of IDrawables, which you can only be sure implement Draw(), and cast to see if other methods are available.

For example,

ITradable tradable = drawable as ITradable;
if (tradable != null)
{
    tradable.Trade(buyer, seller);
}

You're going to have to do the above in your option 2 anyway, so why tie everything to IDrawable?

If we use a language without interfaces such as JavaScript or Python, how can we deal with this problem?

OO languages tend to support at least one of three things:

Interfaces (use ... interfaces)

Multiple inheritance (use abstract classes)

Dynamic types (use duck-typing; this is where Python comes in)

Prototypical languages, such as Javascript, support ... well, prototypes, which allow for a slightly modified version of duck-typing (in prototypes, you generally ask if a method exists before calling it).

Other paradigms generally handle these issues in their own way.


答:
He is likely referring to the basic fact that an interface can not be instantiated. You can not reuse an interface. You can only implement code that supports it, and when you write code for an interface there is no reuse.

Java has a history of providing frameworks of many API(s) that take an interface as arguments, but the team who developed the API never implement a wide range of classes for you to reuse with those interfaces.

It's kind of like a GUI framework that has an IWindow interface for a dialog box, and then you can add IButton interfaces for controls. Except, they never gave you a good Button class that implements IButton. So you're left creating your own.

Abstracted frameworks that have a wide range of base classes providing core functionalities are more reusable, and that works best when those abstracted classes are accessible to those using the framework.

Java developers started doing this thing where their API layers exposed only interfaces. You could implement those interfaces, but you could never reuse classes from the developer that implemented those interfaces. It's kind of like a cloak and dagger style of API development.

Title: What did Rich Hickey mean when he said, "All that specificity [of interfaces/classes/types] kills your reuse!"

Body:
In Rich Hickey's thought-provoking goto conference keynote "The Value of Values" at 29 minutes he's talking about the overhead of a language like Java and makes a statement like, "All those interfaces kill your reuse."  What does he mean?  Is that true?

In my search for answers, I have run across:

The Principle of Least Knowledge AKA The Law of Demeter which encourages airtight API interfaces.  Wikipedia also lists some disadvantages.

Kevlin Henney's Imperial Clothing Crisis which argues that use, not reuse is the appropriate goal.

Jack Diederich's "Stop Writing Classes" talk which argues against over-engineering in general.

Clearly, anything written badly enough will be useless.  But how would the interface of a well-written API prevent that code from being used?  There are examples throughout history of something made for one purpose being used more for something else.  But in the software world, if you use something for a purpose it wasn't intended for, it usually breaks.

I'm looking for one good example of a good interface preventing a legitimate but unintended use of some code.  Does that exist?  I can't picture it.


问:
Responsive Web Design vs. User-Agent Sniffing
The CSS3 media query feature has led to many interesting possibilities in terms of developing websites which adjust to many different screen sizes and devices.

However, in practice, I'm starting to get the sense that the CSS3 media query feature, and the whole "Responsive Web Design" movement, may not live up to its promise.

The problem I see is that, at the end of the day, web developers care mostly about whether their users are viewing content via a Desktop, Tablet, or Mobile device.  But CSS3 only provides a means to detect screen resolution.  In theory, detecting screen resolution seems like a great way to adjust for various different devices.  But in practice...

Suppose we have a simple Javascript function that just outputs the screen width:

```<code>function foo()
{
   alert(screen.width);
}
</code>```

On my Blackberry Touch, this outputs:

```<code>768
</code>```

On my Samsung Galaxy, this outputs:

```<code>800
</code>```

So...um, at this point, the resolution of mainstream smart phones is getting pretty close to Desktop-level resolutions.  The ability to detect whether a user is viewing your website via a smartphone, tablet, or desktop, seems to be increasingly difficult if all you're going by is screen resolution.

This makes me call into question the entire wisdom behind the whole CSS3 "Responsive Web Design" movement based on media queries.  It almost seems like the media query feature is better suited towards adapting to a resizing browser window on a Desktop screen, rather than various mobile devices.

Another possible technique for detecting mobile or tablet devices is to use feature detection, by checking if the ontouchstart event is supported.  But even this is becoming increasing unreliable as many Desktop screens start to support touch.

Question: So... as a web developer, if I can't rely on RWD or feature detection, is user-agent sniffing (as notoriously unreliable as always) really the best option to detect mobile devices?

答: User agents lie, too. If you Google around, you'll find lists of user agents vs reality. So this is a problem. Some resort to looking at the dpi setting to determine which or what kind of device it is.</p>


答:
Stop worrying so much about specific devices.

The ability to detect whether a user is viewing your website via a smartphone, tablet, or desktop, seems to be increasingly difficult if all you're going by is screen resolution

It is getting increasingly difficult to detect via screen resolution, and it will only get harder as more devices enter the market, but the purpose of media queries is not to detect device types.What media queries are good at is making tweaks to your design when it is no longer pleasant to use at the current dimensions. If the site starts to fall apart at 550px wide, then it doesn't matter if there's a device with those dimensions or not: you set the breakpoint there.

Its the same deal with feature detection. If the device supports touch, then what does it matter if it's a mobile device or some future wall-sized monitor? Either way the touch enhancements will probably be useful.

User-agent sniffing - as you've stated - is completely unreliable. I could change my User-agent string to Shakespeare quotes if I really wanted too. What would your site decide about my browser then?

User agents also require a lot of work to handle all the possibilities. Do you have one for Firefox on android? Chrome on IOS? Dolphin on Froyo? The WiiU Browser? The extremely limited browser on my old LG feature phone? Lynx? IE 13? Links? IceWeasel? The Blackberry playbook's browser? How are you telling the difference between Opera running on a tablet and opera running on a phone?

This list can only grow as time goes on.

Title: Responsive Web Design vs. User-Agent Sniffing

Body:
The CSS3 media query feature has led to many interesting possibilities in terms of developing websites which adjust to many different screen sizes and devices.

However, in practice, I'm starting to get the sense that the CSS3 media query feature, and the whole "Responsive Web Design" movement, may not live up to its promise.

The problem I see is that, at the end of the day, web developers care mostly about whether their users are viewing content via a Desktop, Tablet, or Mobile device.  But CSS3 only provides a means to detect screen resolution.  In theory, detecting screen resolution seems like a great way to adjust for various different devices.  But in practice...

Suppose we have a simple Javascript function that just outputs the screen width:

```<code>function foo()
{
   alert(screen.width);
}
</code>```

On my Blackberry Touch, this outputs:

```<code>768
</code>```

On my Samsung Galaxy, this outputs:

```<code>800
</code>```

So...um, at this point, the resolution of mainstream smart phones is getting pretty close to Desktop-level resolutions.  The ability to detect whether a user is viewing your website via a smartphone, tablet, or desktop, seems to be increasingly difficult if all you're going by is screen resolution.

This makes me call into question the entire wisdom behind the whole CSS3 "Responsive Web Design" movement based on media queries.  It almost seems like the media query feature is better suited towards adapting to a resizing browser window on a Desktop screen, rather than various mobile devices.

Another possible technique for detecting mobile or tablet devices is to use feature detection, by checking if the ontouchstart event is supported.  But even this is becoming increasing unreliable as many Desktop screens start to support touch.

Question: So... as a web developer, if I can't rely on RWD or feature detection, is user-agent sniffing (as notoriously unreliable as always) really the best option to detect mobile devices?


问:
Is it possible to use the Intel C/C++ compiler on Linux to create object files to be linked on Windows?
Why?

Depending on your source the Intel compiler is likely or most definitely the compiler generating the fastest executables for the x86 architecture (5 to 100 % execution time improvement).

Intel offers its compilers for Linux under a non-commercial license for free (I think I read it is free somewhere on their page: Intel - Non-Commercial Software Development).
There is also a free non-commercial license for students, but this license is not applicable although tools are offered for all three major operating systems (link dropped  due to reputation restriction).

Goal

I (as a non-student) would like to be able to use the Intel compilers for possible execution speed improvements under the non-commercial license to compile object files that can be linked to create executables and dynamic link libraries for Windows (and possibly OS X)

More Details:

What I inferred from this document is that the Intel compilers create object files that are compatible to the dominant compilers of the platform.

Sub-questions:

What are the object file formats of gcc, g++, cl, mingw32, icc, icpc, and icl on Windows and Linux (current versions)?

Could parts of the mingw32 cross-compiler toolchain be used to accomplish the goal?

Am I right that the metadata in the generated object files is the main issue?

ad 2:

mingw32-objcopy seems to be able to convert the Intel compiler output on Linux (presumably ELF) to Microsoft-compatible COFF (with the possible exception of relocateable object files). Could someone confirm that this actually works (for non-trivial applications), please?

答:
I propose the following answer:

A definite maybe (leaning towards yes) with a but regarding the context.

Explanation:
Regarding the "leaning" part: It seems to not be a total waste of time to try this, but (the "put" part) taking into account this answer you likely won't get the execution time improvements compared to an Intel-only toolchain. The relevant part being linker and runtime feedback to the compiler (whole program optimization, profile-guided optimization, link-time code generation).

Additional detail:

According to the MinGW FAQ there are possible problems with using libraries and DLLs:
 "Although dlls are supposed to be fairly portable across different Windows compilers, accessing dlls through a library file (.lib or .a) is not. The library file formats are specific to particular compilers and cannot be used portably with different compilers unless the compiler provides support for it."

To complete the answer:

sub-question 1:

What are the object file formats of gcc, g++, cl, mingw32, icc, icpc, and icl on Windows and Linux (current versions)?

The default object file format for any compiler on Windows is COFF (likely the PE variant).
The default object file format for any compiler on Linux is ELF

sub-question 2:

Could parts of the mingw32 cross-compiler toolchain be used to accomplish the goal?

Most likely yes (for the linking part), but most likely you will not get much execution time improvement.

sub-question 3:

Am I right that the metadata in the generated object files is the main issue?

Regarding linking: yes.


问:
How to salvage a business model from a mismatched database?
There is an application that involves billing enterprise customers for the services their customers utilize. The database schema does not properly reflect the business model. For instance, on a given account, services may become activated and deactivated. There is only a column to represent when the service was deactivated and the code in place just updates that same row if the service is reactivated rather than adding a new row. Ideally, a row would be added when a service activates and updated when deactivated, and there would be a column to represent the activation date.

As it stands, there is no solid billing history for these enterprise customers, but there needs to be from here on out. Do we set a "cutoff" for the legacy model that was corrupted and wipe the table clean? Do we add the appropriate column and start working with the table properly and just check for rows that have a 'activated date' of null to detect legacy? There must be several ways of handling this, but I have no experience with this kind of situation and would like to hear out some various approaches.

答:
"Of course the way things are now, there is no solid billing history due to the mistakes that were made."

As far as I understand your question, your database scheme is missing some features (like history information), and you have problems to change it because you don't know the full impact into your existing system.

One approach for dealing with that kind of situation is to solve the problem with upward-compatible extensions to your data model. For example, you need a history in your billing table? Add a new "billing_history" table, with exactly the same columns as your billing table, and an additional "record version number" as well as a "validity date" column. Then add an "after update" trigger to that table which makes a copy of the current billing record into the "billing_history" table whenever the "deactivated" flag is reset to "activated". Now, you can add new modules to search, display and access that history table, and you don't have to change anything in your existing modules.

The details may be different in your situation, but I hope you get the idea.


答:
In my experience, a stream is a sequence of bytes that are produced/consumed at rate often determined by data within the stream. For example, an MPEG data stream will have frame headers which describe what the next sequence of bytes does and how many need to be consumed. Binary serialisation of a document would be similar. It is not always self-describing : writing to STDOUT can be done in a stream-wise manner but it may be humanly-readable/non-parseable data. </p>

<p>Conversely, a queue is usually of a well-known type of object (or interface-supporting objects) that are consumed in their entirety. An example might be a queue of database jobs that are processed by a number of database workers. </p>

Title: What's the difference between a stream and a queue?

Body:
In my experience, a stream is a sequence of bytes that are produced/consumed at rate often determined by data within the stream. For example, an MPEG data stream will have frame headers which describe what the next sequence of bytes does and how many need to be consumed. Binary serialisation of a document would be similar. It is not always self-describing : writing to STDOUT can be done in a stream-wise manner but it may be humanly-readable/non-parseable data.

Conversely, a queue is usually of a well-known type of object (or interface-supporting objects) that are consumed in their entirety. An example might be a queue of database jobs that are processed by a number of database workers.


问:
Designing a SQL-like encapsulation object for programmatic use
In the last few weeks, I have been working on a Data Mapping Library, which has involved lots of research, experimentation, crying, blaming the whiteboard for not being big enough, and more research. But now I have a full idea of what I'm trying to do.

I have decided that before working on any data source adapters, I need to build a SQL expression library. The queries are not assembled with a string of text, but in the form of an instantiated object, containing multiple other objects associated with which part of the query it pertains to.

As such, a SELECT query object will have objects for the columns, table from, joins, where clause, group bys, having clause, order bys, and limit. These objects are then passed to the data source adapter, which will take the input and turn it into a query (or use it in other ways) so that it can fetch the data in a common fashion.

Although this is good enough for simple queries, when it comes to more complex queries, where the join reference, or a condition within the where clause is a nested select query (i.e. SELECT * FROM tblA INNER JOIN (SELECT * FROM tblB WHERE foo = 'bar'), or SELECT * FROM tblA WHERE alice IN (SELECT * FROM tblB WHERE foo = 'bar')), I am having trouble designing an interface where such a thing could be defined, which would later be passed to the adapter that could use it in whatever way it needs to.

So, can anyone propose a design that would allow for such queries to be defined in abstract which could be interpreted into a sql query, or into a nosql programmatic interface function call?

EDIT

The design of the system is such that all the tables and columns are defined as objects (separately, but with named associations for linking). Here is an example of the coding I am hoping to be able to execute:

```<code>tblA::select()
    ->where(new inCondition(
                           'tblAfooCol',
                            tblB::select()->where(new isNullCondition('tblBbarCol'))
                           )
           )
    ->fetch();
</code>```

Now, instead of this being directly translated into SQL (which is very easy), I am trying to plan a way that this can be returned to the data source adapter (internally through the fetch function). So far, the system I have built can handle the commands for a single SELECT query being parsed, but it is when sub queries are used in conjunction with the query that will be passed to the adapter. I am having problems determining how to encapsulate the sub query so the adapter can process it itself. As said before, converting it directly into SQL works great, but if I want to use it with a special adapter that does not use SQL (i.e. an XML or MongoDB adapter), without a function to convert the SQL into commands (or if it is SQL, converting some of the syntax to a valid specification for that rmdbs) that can be used may become very processor intensive (only for certain queries) and cost quite a lot of performance.

答:
If you're doing this because you need it, you should really consider using ActiveRecord, because it does everything that you're trying to do, and more:

http://www.phpactiverecord.org/

(don't reinvent the wheel).

If you're doing this for academic exercise, you could still benefit a ton from looking at the files in ActiveRecord and then using the concepts that you learn from code review.


答:
A difference between a stream and a queue is the way data rate is controlled:

in a queue, the sender adapts to the speed of the reader. The sender decides what to do if the queue is full: wait for availability of queue or throw data away.

in a stream, the reader adapts to the speed of the sender, The reader decides what to do if new data arrives before old one has been consumed.

With that perspective, character streams such as Unix pipes would not qualify as streams but as queues.


问:
In an online questionnaire, what is a best way to design a database for keeping track of users all attempts?
We have a web app where users can take online exams.

Exam admin will create a questionnaire. A questionnaire can have many Questions. Each question is a multiple choice question (MCQ).

Let's say an admin creates a questionnaire with 10 questions. Users attempt those questions. Now, unlike real exams users can attempt single questionnaire multiple times. And we have to keep track of his all attempts.

e.g.

```<code> +-------+-----------------+------------+-------+------------+----------+
 |User_id|Questionnaire_id |question_id |answer |attempt_date|attempt_no|
 +-------+-----------------+------------+-------+------------+----------+
 |1      |1                |1           |a      |1 June 2013 |1         |
 |1      |1                |2           |b      |1 June 2013 |1         |
 |1      |1                |1           |c      |2 June 2013 |2         |
 |1      |1                |2           |d      |2 June 2013 |2         |
 +-------+-----------------+------------+-------+------------+----------+
</code>```

Now it can also happen that  after user has attempted same questionnaire twice, admin can delete a question from same questionnaire, but users' attempt history should still have reference to that so that user can see his that question in his attempt history in spite of admin deleting that question.

If user now attempts this changed questionnaire he should see only 1 question.

```<code> +-------+-----------------+------------+-------+------------+----------+
 |User_id|Questionnaire_id |question_id |answer |attempt_date|attempt_no|
 +-------+-----------------+------------+-------+------------+----------+
 |1      |1                |1           |a      |3 June 2013 |3         |
 +-------+-----------------+------------+-------+------------+----------+
</code>```

Also, after this user modified some part of question, users attempt history should show question before modification while any new attempt should show the modified question.

How do we manage this at database level?

My first gut feeling was that,

For deletes, do not do physical delete, just make a question inactive so that history can still keep track of users attempt.

For modifications, create versions for questions and each new attempt refres to latest version of each question and history keeping reference to version of question at attempt time.

答:
Regarding deletes, your suggestion is right. A common best practice is to use flags to declare a property. In this example in your question table (wherever you store questions) add a new field called isDeleted. Set it to 0 per default upon inserting a new entry and update to 1 when you're deleting a question.

Now to the modifications. Your suggestion seems right to me again (as far as I've understood your explanation correctly). You could do this by adding a new field to your question table called something like parent, which should refer to the id of the updated question. I strongly recommend you use foreign keys at this point, as this is essential to maintain data integrity.


问:
Recompiling dll's and adding more during run time - what are my options?
I want to compile custom functions during run time based on user written scripts. I'll give a hypothetical example that should demonstrate exactly what I need to do. This is the best way for me to describe the problem. I'd like a little input/ideas in how I can solve this. At the bottom I give you my ideas.

I have 2 classes, one with public int x and y. Another with public int x,y,z. There can be more than one instance of each class running.

The thing with these classes though (and here comes my problem) is that they need to be updatable via a user written and then compiled function during run time, that then gets added to a list of update functions that gets run once per cycle/event. Which could be at the touch of some button or something.

Example: The user has written a script to update the public members of Class A. He has written A.X = B.Y + C.Z. The variables here are public, never private. This method needs to be compiled, and added to some list of functions to call each cycle. Obviously this method needs access to class B and C, as well as A. So pointers to those need to be passed in. The function returns nothing.

When I say class A, B, and C. I mean these as some instances of any classes. 'A' could be class Q, while both B and C could be from class T. Or any other variation. These classes do not need recompilation/user written or anything like that.

I just need help with coming up with options and how to compile a function that gets passed in some pointers and does something with them. But with all of that defined run time, what the function does, what gets passed into it, ect.

---- What I think I can do ---

I'm jumping extremely far in knowledge but it is what I always do. So I am just switching from C# to C++ and have little to go on for now while I know little. So all i can do is guess solutions and research them. I'm guessing I could compile a late loading dll for each function, and I'm guessing the dll has to know something about the data structures passed into it so I think it could work to have them in a separate normal dll usable by any program. (The A,B, and C class thingies, or rather Q, and T classes which A,B,and C were instances of in my little demo). So now both the normal program and the dll functions knows all about the classes, and all I have to do is compile the dlls during runtime, load them, and somehow get a pointer to them that my main application has and can call with the appropriate arguments. Then if the user changes the script, the dll unloads, recompiles, loads again, and a new pointer is gotten?

Any help is greatly appreciated. If you can help direct my learning/research I'll learn a lot faster and be able to implement this. Thank you so much!

答:
Technically, it is possible to let your program build a library and dynamically load that into your program. But it is very unlikely that such a program will be a success.
For starters, unless you are targeting C++ developers as your users, you should not assume that there is a C++ compiler present.

A far better approach is to incorporate a scripting engine in your program and to let the users write the extensions in the scripting language.
Possibilities here are for example Boost.Python or Lua.
That way you get the best of both worlds: the speed of C++ for your main program with the flexibility of scripting languages for the extensions.


问:
UML modelling semantics
In today's lecture about Modelling techniques with respect to MDD using UML the lecturer stated that it's absolutely necessary to give a (possibly) textual description about the semantics of each diagram you produce.

In my opinion it's not necessary to describe semantics of diagram elements which are already standardized by UML. I can see that it's completely appropriate if you extend the standard UML by stereotypes/tagged values for any reason.

In contrast, I think that standardization has in the ordinary case the intention to let people reason and talk about diagrams without the need to explain semantics every time. The only precondition is of course that they all rely on the same UML specification.

Another point regarding MDD is that using different semantics from time to time for the same diagram kind makes code generation and automatic model transformation difficult in the end.

Am I right with this notion?

Are there some inherent interpretation ambiguities in UML to make it more general usable?

答:
You're right that the stereotypes should need no explicit explanation (other than where they are defined, if you are using custom stereotypes for some reason); that's the point of using a stereotype. That usually does not mean you can avoid describing things though, as it is rare that software is just a coordination of stereotypes. Some description as well, on the parts that do something interesting (like issuing an ID or performing a calculation) can save a whole lot of complexity elsewhere. Note that text in a human-readable language is not the only way to do that describing; depending on what you are doing, mathematical equations, semantic annotations from an ontology, or even links to appropriate academic papers may be more suited. It all depends.

It's possible to write virtually an entire program using UML and appropriate code generation. You probably don't want to do that for anything real though, as the difficulty of managing the complexity of the size of diagrams required to describe a program of even medium size will make the use of graphical design models like UML rather impractical. UML is good for the architecture, the real purpose of which is to be shown to programmers so they understand the bigger picture, but isn't as well suited to detailed work. (I shudder to think of the complexity of my programs at the UML level if I expand everything out…)

Title: UML modelling semantics


问:
Sourcecode license: free for personal use and modification but no public distibution
For one of my apps, I want to make the source code “open source” so that others might adapt the code to their personal needs or even contribute improvements, but I don’t want anybody else to publish “my app”. Furthermore, I still want to be able to sell the app at some time in the future.

Is there a usual license for this, like the GPL or similar?

I found similar questions from 2010 which say something about dual licensing, but maybe there is a license fitting my needs?

A commercial software but open and free for personal/edu. How to license?

Free for personal use license?

Open Source but not Free Software (or vice versa)

Software licensing: open source, no commerical, no derivatives

答:
If you don't allow re-distribution of your software, then your code is not "open source".

To my knowledge, there is only one 'license' that forbids redistribution of the original software, and that is the default option of copyright law: no license.

Personal modification, without redistribution, is (to my knowledge) allowed under the copyright law in most jurisdictions, and if it isn't there is no effective way to enforce it anyway (apart from withholding the source code).


答:
One reason to avoid nesting loops is because it's a bad idea to nest block structures too deeply, irrespective of whether they're loops or not.

Each function or method should be easy to understand, both it's purpose (the name should express what it does) and for maintainers (it should be easy to understand the internals). If a function is too complicated to easily understand, that usually means that some of the internals should be factored out into separate functions so they can be referred to in the (now smaller) main function by name.

Nested loops can get difficult to understand relatively quickly, though some nesting of loops is fine - providing, as others point out, that doesn't mean you're creating a performance issue by using an extremely (and unnecessarily) slow algorithm.

Actually, you don't need nested loops to get absurdly slow performance bounds. Consider, for example, a single loop that in each iteration takes one item from a queue, then possibly puts several back - e.g. breadth-first search of a maze. The performance isn't decided by the depth of nesting of the loop (which is only 1) but by the number of items that get put in that queue before it's eventually exhausted (if it's ever exhausted) - how big the reachable part of the maze is.


问:
How to get different resources in a single endpoint in RESTful?
I have a REST webservice that have a couple of resources, like Company and User. But now I need to make a modification to the API to return a special list combining company, user and maybe other type of resource. Like a list of recommendations with various type of resources.

Which is the best approach to solve this?

I need to make a new endpoint (resource), something like: /recommendations? I already have the /company endpoint, and the /user endpoint returning the corresponding objects. This is fine. But now I need some way to return an array with a combination of users and companies.

Also I'm thinking that the json will look like an array of objects, but how the client can know which type of object is parsing if every object in the array is a different resource?

EDIT

I want that my client could show a recomendations screen in the app. The problem is that this list can combine multiple types of data (users, companies). It doesn't matter if this resources have a relationship or not.
The client shoud recive a json like that:

```<code>"recomendations": [
    {
        "id_user": 1
        "name": "Jean"
        ...
    },
    {
        "id_company": 2
        "name": "Starbucks"
        ...
    },
    ...
]
</code>```

答:
I would define a separate Recommendation type with all the relevant information for recommendations in it.
In your model, this type does not map directly to a database table, but rather gets its contents from both the User and Company tables (possibly using an SQL UNION).


问:
What could an algorithm look like that iterates through all combinations of two variables to aim at a certain number of entries?
For background information, see "Some background" further down.

I have a list that looks like this:

```<code>Start-Time-In-Seconds;End-Time-In-Seconds
1;2
4;6
12;15
...
</code>```

This works together with a wave file by acting as a cutlist. So the desired parts are 1->2, 4->6, 12->15, ...

If the distance between End-Time-In-Seconds of the previous element and Start-Time-In-Seconds of the current element is below a threshold of seconds(I call it Pausendauer) I merge those two, ie if the threshold is 3 seconds then the list will be

```<code>Start-Time-In-Seconds;End-Time-In-Seconds
1;6
12;15
...
</code>```

If the distance between Start-Time-In-Seconds and End-Time-In-Seconds is below a threshold of seconds(I call it Minimallänge) I discard this sample, ie if the threshold is 4 seconds then the list will be

```<code>Start-Time-In-Seconds;End-Time-In-Seconds
1;6
...
</code>```

What could an algorithm look like that iterates (intelligently) through all combinations of Minimallänge and Pausendauer to aim at a certain number of entries? Example:

The number of entries should be 3. Given the number 3 the algorithm should iterate (intelligently) through all combinations of Minimallänge and Pausendauer to output something like this:

```<code>Start-Time-In-Seconds;End-Time-In-Seconds
1;12
18;20
50;100
</code>```

And that should be all. You notice I did not add "..." to it as the final list is to only consist of three entries.

Some background: The wave file contains several interviews being recorded continuously with pauses in between. A VAD gave me areas where it presumes voice to be. As I know the number of total conversations(f.i. 3, usually more which is why this makes sense) my goal is to determine them automatically. The cutlist is the raw output of my VAD which I want to turn into a usable cutlist for ffmpeg.

PS: If you can, share an algorithm in c#.

答:
Let us consider a series of audio chunks separated by pauses, and let Li be the length of chunk i, and Pi the pause between chunk i and chunk i+1. So we have:

```<code>[ chunk 0, L0 = 15s ]..(P0 s of silence)..[ chunk 1, L1 = 7s ]...
</code>```

If we merge chunks wherever Pi < P, we will get from a minimum of 1 chunk (when P >= max(Pi) ) to a maximum of N (when P < min(Pi)).

If we reject chunks of length less than L, the pauses will merge: by discarding chunk Cj, the pause between Cj-1 and Cj+1 becomes Pj-1+Lj+Pj, and therefore the number of superchunks for any given P will increase.

The number of chunks for any given L will then monotonically decrease with increasing P, from a maximum of CL = number of chunks longer than L.

The result should be something like this:

So the area of interest will be sort of L-shaped (not necessarily one "cell" wide or tall), and seen from above, it could look like this:

```<code>#
##
###
###
#######
  ########
    #########
</code>```

So, given that one "exploration" of the array is going to cost O(N), you could start with a suitable value of (L,P), e.g. (0,0) and "walk" the array increasing L until you meet two points, one above, one below (or equal) to the desired threshold.

```<code>#         0
##        1
###       2
###       3
######A   4
  ####98765
    #######
</code>```

(Here, 0...9,A..F are the iterations. Note that at iteration 6 you also check the cell "above" the 6, as 4 is "above" the 5, so they cost double).

The cost decreases from O(L'P') (where L' is the maximum length you consider, P' is the maximum pause) to O(L'+P').

But a major clinch could be, what happens if the "intra-conversation" pause is longer than the "inter-conversation" pause?

I mean, if the interval between interviews is longer than any interval within the interviews, then all of the above is redundant: just hunt for the N longer pauses, and those will be the pauses between interviews.

What happens on the other hand if there is one "internal" pause that is longer than the space between interviews? Then, the above algorithm (actually, any length-based algorithm I can think of, unless the average length of an interview is known and reliable, and the extra pause is not too near to the beginning or end of the interview) will choose that pause as an interview splitter, and whatever is before (or after) will be assigned to the adjacent interview.

To address this issue, I think that you need to do a deeper inspection, maybe classifying chunks based on frequency distribution. You might still misattribute the first or last interviewer's chunk, if it is the same in two adjacent interviews and there's no reliable "script" (e.g. the interviews are always closed by the interviewer, etc.).:

```<code><male voice> And that's all.

[ 3 seconds ]

<female voice> Very well.. then, thank you, mr. Alpha.
[ 2 seconds ]
<female voice> Good morning, mr. Beta.
<male voice> Good morning.
</code>```

Body:
Let us consider a series of audio chunks separated by pauses, and let Li be the length of chunk i, and Pi the pause between chunk i and chunk i+1. So we have:

[ chunk 0, L0 = 15s ]..(P0 s of silence)..[ chunk 1, L1 = 7s ]...

If we merge chunks wherever Pi < P, we will get from a minimum of 1 chunk (when P >= max(Pi) ) to a maximum of N (when P < min(Pi)).

If we reject chunks of length less than L, the pauses will merge: by discarding chunk Cj, the pause between Cj-1 and Cj+1 becomes Pj-1+Lj+Pj, and therefore the number of superchunks for any given P will increase.

The number of chunks for any given L will then monotonically decrease with increasing P, from a maximum of CL = number of chunks longer than L.

The result should be something like this:

So the area of interest will be sort of L-shaped (not necessarily one "cell" wide or tall), and seen from above, it could look like this:

#
##
###
###
#######
  ########
    #########

So, given that one "exploration" of the array is going to cost O(N), you could start with a suitable value of (L,P), e.g. (0,0) and "walk" the array increasing L until you meet two points, one above, one below (or equal) to the desired threshold.

#         0
##        1
###       2
###       3
######A   4
  ####98765
    #######

(Here, 0...9,A..F are the iterations. Note that at iteration 6 you also check the cell "above" the 6, as 4 is "above" the 5, so they cost double).

The cost decreases from O(L'P') (where L' is the maximum length you consider, P' is the maximum pause) to O(L'+P').

But a major clinch could be, what happens if the "intra-conversation" pause is longer than the "inter-conversation" pause?

I mean, if the interval between interviews is longer than any interval within the interviews, then all of the above is redundant: just hunt for the N longer pauses, and those will be the pauses between interviews.

What happens on the other hand if there is one "internal" pause that is longer than the space between interviews? Then, the above algorithm (actually, any length-based algorithm I can think of, unless the average length of an interview is known and reliable, and the extra pause is not too near to the beginning or end of the interview) will choose that pause as an interview splitter, and whatever is before (or after) will be assigned to the adjacent interview.

To address this issue, I think that you need to do a deeper inspection, maybe classifying chunks based on frequency distribution. You might still misattribute the first or last interviewer's chunk, if it is the same in two adjacent interviews and there's no reliable "script" (e.g. the interviews are always closed by the interviewer, etc.).:

<male voice> And that's all.

[ 3 seconds ]

<female voice> Very well.. then, thank you, mr. Alpha.
[ 2 seconds ]
<female voice> Good morning, mr. Beta.
<male voice> Good morning.


问:
Agile MVP (Most Valuable Player/Programmer)
Recently I've been involved in an agile project (using scrum) where management came up with the idea that the team would nominate a developer 'MVP' as well as a QA 'MVP' at the end of each sprint, voted on by the team.  The MVP then gets a small monetary reward and free lunch as well as a trophy to display on his desk.  We've had two sprints so far with this reward system in place.

The good I see from this is the following:

More bugs have been fixed (which is what upper management wants to see, a number change in the direction they want)

The MVP from each 'team' gets recognized and gets a self esteem boost (or is it an ego boost?)

I've noticed a few what I would consider bad sides to doing such a thing (at least from a developer standpoint):

There are a few developers who are so concerned with the number that the quality of bug fixes has gone down. Fixes in one area are causing regressions in another.

There are a few developers who are cherry picking 'easier/quicker' bugs to boost their bug count.  Could be good of bad here I guess.

Higher priority (which a lot of the time correlates to 'harder/longer to fix') defects actually become lower priority.

Blocking defects are not addressed in a timely manner, as usually they take longer and require more coordination with QA.

The team aspect within the Dev team has been lost.  The team aspect of Dev and QA working together as one hasn't improved either, but hasn't really changed too much from before.

Work beyond bug fixes, or working towards THAT number, isn't easily recognizable/tracked.

I do believe that each of the 'bad' above can be addressed to some degree, depending on how the team handles each.

My question is, then, has anyone successfully pulled anything like this off, where you recognize an MVP per sprint?  If so, what do you think contributed to that success?

答:
Agile emphasizes team effort, not the effort of individuals. So no, this approach is clearly not agile.

Rather than encourage team collaboration, this encourages each team members to focus on his own result. It can even lead to members avoiding helping each other (or worse), which in the long run will stop the team from getting better.

I suggest rewarding the team as a whole if they did a good job.


答:
If you insist of doing it yourself

don't

look at Hibernate criteria API or JPA criteria API for inspiration.

I don't know PHP, but i would be surprised if there wasn't a lot of libraries for this for PHP

Title: Designing a SQL-like encapsulation object for programmatic use

Body:
In the last few weeks, I have been working on a Data Mapping Library, which has involved lots of research, experimentation, crying, blaming the whiteboard for not being big enough, and more research. But now I have a full idea of what I'm trying to do.

I have decided that before working on any data source adapters, I need to build a SQL expression library. The queries are not assembled with a string of text, but in the form of an instantiated object, containing multiple other objects associated with which part of the query it pertains to.

As such, a SELECT query object will have objects for the columns, table from, joins, where clause, group bys, having clause, order bys, and limit. These objects are then passed to the data source adapter, which will take the input and turn it into a query (or use it in other ways) so that it can fetch the data in a common fashion.

Although this is good enough for simple queries, when it comes to more complex queries, where the join reference, or a condition within the where clause is a nested select query (i.e. SELECT * FROM tblA INNER JOIN (SELECT * FROM tblB WHERE foo = 'bar'), or SELECT * FROM tblA WHERE alice IN (SELECT * FROM tblB WHERE foo = 'bar')), I am having trouble designing an interface where such a thing could be defined, which would later be passed to the adapter that could use it in whatever way it needs to.

So, can anyone propose a design that would allow for such queries to be defined in abstract which could be interpreted into a sql query, or into a nosql programmatic interface function call?

EDIT

The design of the system is such that all the tables and columns are defined as objects (separately, but with named associations for linking). Here is an example of the coding I am hoping to be able to execute:

```<code>tblA::select()
    ->where(new inCondition(
                           'tblAfooCol',
                            tblB::select()->where(new isNullCondition('tblBbarCol'))
                           )
           )
    ->fetch();
</code>```

Now, instead of this being directly translated into SQL (which is very easy), I am trying to plan a way that this can be returned to the data source adapter (internally through the fetch function). So far, the system I have built can handle the commands for a single SELECT query being parsed, but it is when sub queries are used in conjunction with the query that will be passed to the adapter. I am having problems determining how to encapsulate the sub query so the adapter can process it itself. As said before, converting it directly into SQL works great, but if I want to use it with a special adapter that does not use SQL (i.e. an XML or MongoDB adapter), without a function to convert the SQL into commands (or if it is SQL, converting some of the syntax to a valid specification for that rmdbs) that can be used may become very processor intensive (only for certain queries) and cost quite a lot of performance.