问:
Clojure state and persistence
I'm learning Clojure to see if it's something I can leverage at my current job, and more importantly, how I can convince my bosses that Clojure has a 'killer feature' over java that makes it worth the investment1.

The feature that I'm guessing most clojure evangelists would tout is state management and concurrency.

The example that I see often in blogs and books is an account balance that’s being updated by multiple threads.  Clojure’s state management can always cleanly ensure that the balance will be accurate regardless of the number of threads reading and writing that value.

In practice, though, an application would never allow an account balance to live only in memory, it would have to be persisted outside of the JVM (probably in a database) for two hopefully obvious reasons:

If the app goes down the database will need to accurately reflect
the latest state for recovery.  For this reason the database cannot be asynchronously updated, and all reads would have to block until the database update is complete.

If other applications are reading or
manipulating the account balance (maybe because we’ve scaled our app
out to several servers), that balance would need to be kept in sync
between all instances.

Can Clojure’s state management handle situations like this elegantly?  For instance, given scenario 2 above, all reads of the account balance would first need to check the database to get the value, and if the database is locked, it would have to block until the correct value is available, no?

It’s great that Clojure handles my in-memory concurrency very elegantly but if that elegance can’t be extended to external state then do I really gain anything?

1(note that things like expressiveness, elegance, etc. are rarely considered killer features by mgmt.)

答:
Actually this looks like of a dupe of question on Stack Overflow.  Keeping the question here as well, though, since the question seems more appropriate for this site.

The long and short of this is that for my purposes, since STM does not support the 'D' in ACID, Clojure's state and concurrency management doesn't buy me anything.  Unfortunately.

Title: Clojure state and persistence


问:
Unit testing C++: What to test?
TL;DR

Writing good, useful tests is hard, and has a high cost in C++. Can you experienced developers share your rationale on what and when to test?

Long story

I used to do test-driven development, my whole team in fact, but it didn't work well for us. We have many tests, but they never seem to cover the cases where we have actual bugs and regressions - which usually occur when units are interacting, not from their isolated behaviour.

This is often so hard to test on the unit level that we stopped doing TDD (except for components where it really speeds up development), and instead invested more time increasing the integration test coverage. While the small unit tests never caught any real bugs and were basically just maintenance overhead, the integration tests have really been worth the effort.

Now I've inherited a new project, and am wondering how to go about testing it. It's a native C++/OpenGL application, so integration tests are not really an option. But unit testing in C++ is a bit harder than in Java (you have to explicitely make stuff virtual), and the program isn't heavily object oriented, so I can't mock/stub some stuff away.

I don't want to rip apart and OO-ize the whole thing just to write some tests for the sake of writing tests. So I'm asking you: What is it I should write tests for? e.g.:

Functions/Classes that I expect to change frequently?

Functions/Classes that are more difficult to test manually?

Functions/Classes that are easy to test already?

I began to investigate some respectful C++ code bases to see how they go about testing. Right now I'm looking into the Chromium source code, but I'm finding it hard to extract their testing rationale from the code. If anyone has a good example or post on how popular C++ users (guys from the committee, book authors, Google, Facebook, Microsoft, ...) approach this, that'd be extra helpful.

Update

I have searched my way around this site and the web since writing this. Found some good stuff:

When is it appropriate to not unit test?

https://stackoverflow.com/questions/109432/what-not-to-test-when-it-comes-to-unit-testing

http://junit.sourceforge.net/doc/faq/faq.htm#best

Sadly, all of these are rather Java/C# centric. Writing lots of tests in Java/C# is not a big problem, so the benefit usually outweights the costs.

But as I wrote above, it's more difficult in C++. Especially if your code base is not-so-OO, you have to severely mess things up to get a good unit test coverage. For instance: The application I inherited has a Graphics name space that is a thin layer above OpenGL. In order to test any of the entities - which all use its functions directly - I'd have to turn this into an interface and a class and inject it in all the entities. That's just one example.

So when answering this question, please keep in mind that I have to make a rather big investment for writing tests.

答:
It's a shame TDD "didn't work well for you." I think that's the key to understanding where to turn. Revisit and understand how TDD didn't work, what could you have done better, why was there difficulty.

So, of course your unit tests didn't catch the bugs you found. That's kind of the point. :-) You didn't find those bugs because you prevented them from happening in the first place by giving thought to how the interfaces should work and how to make sure they were tested properly.

To answer, you question, as you have concluded, unit testing code that is not design to be tested is difficult. For existing code it may be more effective to use a functional or integration test environment rather than a unit test environment. Test the system overall focusing on specific areas.

Of course new development will benefit from TDD. As new features are added, refactoring for TDD might help to test the new development, while also allowing development of new unit test for the legacy functions.

ContentLicense: CC BY-SA 3.0

Title: Unit testing C++: What to test?


问:
Is event chaining considered good practice?
From time to time I've encountered scenarios where several complex conditions need to be met prior to triggering an event. Furthermore, most listeners also run additional checks to determine the course of action. This got me thinking whether a better solution would be to think in terms of smaller events and let them trigger inside each other.

Chaining events would allow me to weave in any additional listeners later on with fairly low effort (possible violation of YAGNI?). My code would consist of simple easily understood elements, which shouldn't be difficult for others to understand.

However, the possible downsides to this solution would be the fact that should something happen to go wrong in the chain (e.g false event triggering due to human error), it would be quite difficult to catch the bug.

Is event chaining a good ideaTM? If not, what are the alternative methods to keep event related code getting cluttered?

答:
Event chaining is a good idea if

It's generally appropriate to your scenario.  A simple example is a user's UI action triggering other visual events.

Each event is self-contained and manageable.  You don't want the solution to become overly cumbersome.

The flow of control is easy to follow.  It needs to be implemented on a platform and in a language that's easy for a developer to walk through.  If you need to track down "magic" methods to trace what's happening, you're going down the wrong path.

It's very important to think the solution through and generalize some things before starting to build the system.  For example, in an OO language you should have a basic interface or abstract class as the basis for all events.  That class should incorporate things like logging / debugging.  You might also want a generalized event management class for handling failures gracefully.


问:
Python mutable default argument: Why?
I know that default arguments are created at the function initialisation time and not every time the function is called.  See the following code:

```<code>def ook (item, lst=[]):
    lst.append(item)
    print 'ook', lst

def eek (item, lst=None):
    if lst is None: lst = []
    lst.append(item)
    print 'eek', lst

max = 3
for x in xrange(max):
    ook(x)

for x in xrange(max):
    eek(x)
</code>```

What I do not get is why this was implemented this way.  What benefits does this behaviour offers over an initialisation at each call time?

答:
This happens because functions in Python are first-class objects:

Default parameter values are evaluated when the function definition is
  executed. This means that the expression is evaluated once, when the
  function is defined, and that the same “pre-computed” value is used
  for each call.

It goes on to explain that editing the parameter value modifies the default value for subsequent calls, and that a simple solution of using None as the default, with an explicit test in the function body, is all that is needed to ensure no surprises.

Which means that def foo(l=[]) becomes an instance of that function when called, and gets reused for further calls. Think of function parameters as becoming apart of an object's attributes.

Pro's could include leveraging this to have classes have C-like static variables. So it's best to declare default values None and initialize them as needed:

```<code>class Foo(object):
    def bar(self, l=None):
        if not l:
            l = []
        l.append(5)
        return l

f = Foo()
print(f.bar())
print(f.bar())

g = Foo()
print(g.bar())
print(g.bar())
</code>```

yields:

[5] [5] [5] [5]

instead of the unexpected:

[5] [5, 5] [5, 5, 5] [5, 5, 5, 5]

Title: Python mutable default argument: Why?

Body:
This happens because functions in Python are first-class objects:

Default parameter values are evaluated when the function definition is
  executed. This means that the expression is evaluated once, when the
  function is defined, and that the same “pre-computed” value is used
  for each call.

It goes on to explain that editing the parameter value modifies the default value for subsequent calls, and that a simple solution of using None as the default, with an explicit test in the function body, is all that is needed to ensure no surprises.

Which means that def foo(l=[]) becomes an instance of that function when called, and gets reused for further calls. Think of function parameters as becoming apart of an object's attributes.

Pro's could include leveraging this to have classes have C-like static variables. So it's best to declare default values None and initialize them as needed:

class Foo(object):
    def bar(self, l=None):
        if not l:
            l = []
        l.append(5)
        return l

f = Foo()
print(f.bar())
print(f.bar())

g = Foo()
print(g.bar())
print(g.bar())

yields:

[5] [5] [5] [5]

instead of the unexpected:

[5] [5, 5] [5, 5, 5] [5, 5, 5, 5]


答:
Speaking from the standpoint of someone who once spent a couple of days tracking down an event-chain-related error, this is a Very Bad Idea(sm).  You're hiding your control flow which (as you noted) can make debugging a nightmare.  The situation I was in arose when someone added some error-handling code which reset a control.  This led to a chain of onPropertyChange handlers that wound up refreshing the control which had the error handler, which led to it resetting the other control again, and so on.  Basically the UI would simply lock up with the CPU pegged at 100%.

If you have some way to prevent event handlers from being triggered more than once for the same root event, then you might be able to avoid this, but I can imagine situations where you might want multiple event handler invocations.

Title: Is event chaining considered good practice?

Body:
From time to time I've encountered scenarios where several complex conditions need to be met prior to triggering an event. Furthermore, most listeners also run additional checks to determine the course of action. This got me thinking whether a better solution would be to think in terms of smaller events and let them trigger inside each other.

Chaining events would allow me to weave in any additional listeners later on with fairly low effort (possible violation of YAGNI?). My code would consist of simple easily understood elements, which shouldn't be difficult for others to understand.

However, the possible downsides to this solution would be the fact that should something happen to go wrong in the chain (e.g false event triggering due to human error), it would be quite difficult to catch the bug.

Is event chaining a good ideaTM? If not, what are the alternative methods to keep event related code getting cluttered?


问:
What's the most important, useful or enlightening thing you learnt in the last 12 months?
A lot of people in the coding community talk about continuous improvement, deliberate practice and so-on - but when they talk about their current practices it's almost like they 'sprang fully formed from the loins of Zeus' because you don't hear about how their opinions changed over time or what they learnt recently.

Every now and then though I go to a talk, or read a book, or talk to someone and they open up a bit more and I find that I learn a lot from these insights.

So, if you had to pick one thing from the last 12 months that you learnt what would it be?

答: I learned that it takes only one rotten manager to spoil the whole project, but it takes lots of good programmers to clean up the mess afterwards.</p>

ContentLicense: CC BY-SA 2.5


问:
Why doesn't Microsoft release UX frameworks to build UI's like their current UIs?
When I started learning programming with the .NET framework, I started by using WinForms as a UI technology. It uses “classic” menus just like this office 2000:

A few years later Office 2007 was released, the ribbon was born:

And even some years later Office 2010 was released, which also added new features like the stage:
A few days ago Office 15 preview was released and they added more fancy new stuff:

That's huge progress IMO, but why don’t they enable the developers to build UI’s like them? When I have a look at .NET, there’s still no way to build a ribbon. Even with WPF, which is highly extensible, there are no premade controls. So the community has started several projects to create all those "features". I know, today Microsoft has released a ribbon for WinForms and WPF, but that's still not part of any core framework (not even the 4.5 one). But this is not limited to .NET as far as I know? Today there are still no APIs for unmanaged applications to create those ribbon UI’s?!

In Germany they are offering free UX training to make sure everything fits their style! http://j.mp/NZGgH9

Why doesn’t Microsoft give the cool stuff to us developers? Do they want their applications to be unique?

答:
They have released a UI framework that supports ribbons -- it's just supported in MFC instead of .NET.

There's probably room for quite a bit of debate as to why they did things that way, but it is what they did anyway.

It looks like Metro-style apps will be supported much more universally -- not only C++, but also C#, VB, and Javascript are supported, if I'm not mistaken.


答:
One potential drawback is that it's quite easy to accidentally end up with looping updates. e.g. A -> B -> C -> A -> B...

Another approach is to create composite events which are responsible for fire off a sequence of events. This means you shouldn't end up stuck in a loop, and gives you a single place to catch errors/etc. I've had some success with this, though admittedly haven't used it for anything particularly complicated (yet!).


问:
Why isn't the arrow operator in C++ just an alias of *.?
In c++, the * operator can be overloaded, such as with an iterator, but the arrow (->) (.*) operator does not work with classes that overload the * operator. I imagine that the preprocessor could easily replace all instances of -> with (*left).right, and that would make iterators nicer to implement. is there a practical reason for -> to be different, or is that just a peculiarity of the language/designers?</p>

答:
As a general rule, C++ is designed to favor flexibility, so overloads of * and -> are separate. Though it's fairly unusual to do so, if you want to badly enough you can write those overloads to do entirely different things (e.g., might make sense for a domain specific language implemented inside of C++).

That said, iterators do support either usage. On ancient implementations, you might find a library that requires (*iter).whatever instead of iter->whatever, but if so, that's a bug in the implementation, not a characteristic of the language. Given the amount of work involved in implementing all the standard containers/algorithms/iterators, it's not surprising that some early releases were somewhat incomplete, but they were never really intended to be that way.


答:
The rule that foo->bar equals (*foo).bar only holds for the builtin operators.

Unary operator * doesn't always have the pointer dereference semantics. I could make a library in which it means matrix transposition, zero-or-more parser matches, or pretty much anything.

It would make the language more bothersome if anything that overloads unary operator * would suddenly gain an operator -> you did not ask for, with semantics that might not make sense.

operator -> is separately overloadable, so if you want one, you can overload one with minimal effort.

Also note that such an overload would have some rather interesting properties, like automatically chaining operator -> calls until one in the chain returns a raw pointer. This is quite useful for smart pointers and other proxy types.

```<code>#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <iostream>
#include <ostream>

struct Foo
{
    boost::shared_ptr<std::string> operator -> () const
    {
        return boost::make_shared<std::string>("trololo");
    }
};

int main()
{
    Foo foo;
    std::cerr << foo->size() << std::endl;
}
</code>```

Title: Why isn't the arrow operator in C++ just an alias of *.?

Body: In c++, the * operator can be overloaded, such as with an iterator, but the arrow (->) (.*) operator does not work with classes that overload the * operator. I imagine that the preprocessor could easily replace all instances of -> with (*left).right, and that would make iterators nicer to implement. is there a practical reason for -> to be different, or is that just a peculiarity of the language/designers?</p>

Body:
The rule that foo->bar equals (*foo).bar only holds for the builtin operators.

Unary operator * doesn't always have the pointer dereference semantics. I could make a library in which it means matrix transposition, zero-or-more parser matches, or pretty much anything.

It would make the language more bothersome if anything that overloads unary operator * would suddenly gain an operator -> you did not ask for, with semantics that might not make sense.

operator -> is separately overloadable, so if you want one, you can overload one with minimal effort.

Also note that such an overload would have some rather interesting properties, like automatically chaining operator -> calls until one in the chain returns a raw pointer. This is quite useful for smart pointers and other proxy types.

#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <iostream>
#include <ostream>

struct Foo
{
    boost::shared_ptr<std::string> operator -> () const
    {
        return boost::make_shared<std::string>("trololo");
    }
};

int main()
{
    Foo foo;
    std::cerr << foo->size() << std::endl;
}


答:
Is event chaining a good idea?

It's one of those things that seems like a really good idea, until you use it.

It is very difficult to set up cascading events without some sort of implied dependency on order. It's difficult to set them up without causing issues due to infinite loops and occasional memory leaks. They make class design more difficult due to coupling caused by events needing to know both where to attach and where to cascade to.

And they're super hard on debugging and reasoning about code.

Now sometimes they can be used in relatively limited scenarios where the structure of the code limits some of these problems. In UIs, cascading events can be used to trigger down the hierarchy because that hierarchy structure helps limit ownership and looping concerns.

Still, I find far more often these days that I accept a delegate in a constructor for that sort of extensible behavior than let arbitrary behavior latch on at runtime.


答:
"The C++ Programming Language" describes the fact that these operators are different so that they can be, but also says:

If you provide more than one of these operators, it might be wise to provide the equivalence, just as it is wise to ensure that ++x and x+=1 have the same effect as x=x+1 for a simple variable x of some class if ++,+=,=, and + are provided.

So it seems that the language designers provided separate overload points because you might want to overload them differently, rather than assuming that you always want them to be the same.


问:
What do you think of this new if-then syntax
I was just thinking of something that would be really cool to have in my if-elif-else controls.

```<code>
if condition:
    stuff()
elif condition:
    otherstuff()
then:
    stuff_that_applies_to_both()
else:
    stuff_that_doesnt_aply_to_either()
</code>```

So basically a then will be run when any of the conditions are run EXCEPT the else condition. Do you think this is useful? It's similar to the try-except-else of python.

I think some of you are nitpicking a very preliminary implementation. The then block would be just like the else block in a try-except block in python. The real reason I suggest this is for situations like this.

```<code>
m = {}
if condition == '1':
    m['condition'] = condition
elif condition2 == '3':
    m['condition2'] = condition2
elif condition3 == 'False':
    m['condition3'] = True
then:
    run_test_that_relies_on_one_of_the_conditions_being_true()

return m
</code>```

The then block is scoped to the first if just like the else is. So nesting works fine. And if you need to run a method before the if statements, that really has nothing to do with this use case.

答:
I find your syntax confusing, but I see some value in the concept.  Conceptually, when I've considered the issue, what I've found myself wanting is an "unelse", which basically would execute things in the cases where the last else didn't fire.  Looking at it from that angle, I would suggest that one could achieve a similar result via:

```
  do
  {
    if (condition1)
      ... stuff for condition1 only
    else if (condition2)
      ... stuff for condition2 only
    else
    {
      ... stuff for neither condition
      break;
    }
    ... stuff for both conditions
  } while(0); // Continuation point for break
```

Another option may in some cases be:

```
  if ( ( condition1 && (action1,1)) ||
       ( condition2 && (action2,1)) ||
       (action_for_neither,0))
    action_for_either;
```

A bit nasty looking, but in some cases there may not be any good way of expressing the desired sequence of events other than duplicating code or using goto (which might not be so bad, except for the cartoon someone might insert here).

Body:
I find your syntax confusing, but I see some value in the concept.  Conceptually, when I've considered the issue, what I've found myself wanting is an "unelse", which basically would execute things in the cases where the last else didn't fire.  Looking at it from that angle, I would suggest that one could achieve a similar result via:

  do
  {
    if (condition1)
      ... stuff for condition1 only
    else if (condition2)
      ... stuff for condition2 only
    else
    {
      ... stuff for neither condition
      break;
    }
    ... stuff for both conditions
  } while(0); // Continuation point for break

Another option may in some cases be:

  if ( ( condition1 && (action1,1)) ||
       ( condition2 && (action2,1)) ||
       (action_for_neither,0))
    action_for_either;

A bit nasty looking, but in some cases there may not be any good way of expressing the desired sequence of events other than duplicating code or using goto (which might not be so bad, except for the cartoon someone might insert here).


问:
What are good source control check-in strategies for large tasks?
The general rule is to keep check-ins small and check-in often. But sometimes the task requires large changes to the underlying framework. Then checking in before compeleting the task will break the project until you check in the finished work.

So what strategies do people use to reduce the risk of losing work, or deciding something you are doing is the wrong approach, then changing your mind after removing the code and trying another approach?

When I can, I'll check-in half done work commented out, or if it compiles and nothing is using new files I'll check them in. The larger the change the more likely I am to branch the project and then merge back when I have everything working again. Another option if the source control system allows is shelf sets, which are basically small branches. So when I finish for the day or come to a decision point, I'll shelve my changes, and then if something catastrophic happens, or I want to come back to that point, I can.

答:
I use git, so my answer is "branch". Branch, and commit piece-meal as you complete the various bits.

Push your commits upstream as you're happy, so your colleagues can review the changes without disrupting trunk.

When everyone's happy with the code, merge and you're done!

(What I tend to do for relatively long-running branches is periodically merge trunk (master, in git terminology) into my branch, so the two branches don't diverge too radically.)


问:
Understanding comparison using Big O notation
I was going through this heavily discussed and highly voted question on SO and stumbled across one comment that got 5 upvotes.

So I assume this was a great comment.But it got my head spinning at the same time. Can any one explain this comment? The comment says:

You can't compare big-O values directly without thinking about constant factors. For small lists (and most lists are small), ArrayList's O(N) is faster than LinkedList's O(1).

答:
Ever heard of a Fibonacci heap? That's an infamous example of huge constant factor. See here: SO on Fibonacci heap

Every big-O notation hides a constant factor behind it. A O(N) function could be f(N) = N or g(N) = 100000000N; similarly, O(1) could be t(N) = 1 or k(N) = 100000000000.

In the above example, for f(N) and k(N), when N < 100000000000, the linear time f(N) is actually faster than the constant time k(N).

OwnerDisplayName: Geek

OwnerDisplayName: Ziyao Wei


答: all O(1) means is that it takes constant time, but not necessarily 1 unit of time.  So for a concrete example, let's say the LinkedList takes 3 seconds to access any element.  This is in constant time, but it is fairly slow.  It is not hard to imagine a situation where we have an Arraylist with O(n) access, but where n is small enough that no element would take more than 2 seconds to access.  In such cases, the ArrayList would actually be faster than the LinkedList.</p>

Title: Understanding comparison using Big O notation

Body:
I was going through this heavily discussed and highly voted question on SO and stumbled across one comment that got 5 upvotes.

So I assume this was a great comment.But it got my head spinning at the same time. Can any one explain this comment? The comment says:

You can't compare big-O values directly without thinking about constant factors. For small lists (and most lists are small), ArrayList's O(N) is faster than LinkedList's O(1).

OwnerDisplayName: Julian Coltea


答:
The definition of BigO means that you've defined a function where you've bounded the running time as a function of the input size, for all values greater than some constant factor.

What is a constant factor? Basicaly it's the part of the running time that doesn't depend on the input size. Lets say your linked list was stored in China. Even though it's O(1), every operation involves a flight to china. That's a constant factor, it never changes. However, the scalability of the algorithm is still O(1) because the flight to China is the same amount of time independent of the number of items in the list.

So yes, this statement is true in practice: "You can't compare big-O values directly without thinking about constant factors."

this statement is likely not true, it's implementation dependent: " For small lists (and most lists are small), ArrayList's O(N) is faster than LinkedList's O(1)."

OwnerDisplayName: exabrial


问:
Need some advice on CLI design, I need to provide simple but powerful command line options
I am writing a utility that runs on RHEL5 command line. I need my command line options to be simple but powerful. I looked at the various UNIX utilities to get an idea of how simple  command line utilities have to be. Do you guys suggest any documents/links that talk about command line etiquette? I am modelling my utility on top of LVM (that's all the info I can give for now). I know it's a software engineering question, but I thought it would be appropriate to post here. Please advise....

PS: I am not asking for details about getopt or command line utility parsers.....

答:
You have started with:

```need my command line options to be simple but powerful```

```modelling my utility on top of LVM(thats all the info I can give for now)```

Good thing that's not a tall-order request.

Since we don't know what specific logical volume manager functions you are referring to, it's hard to give specific examples of what to create for a command line option.

In general, you want to think about:

- commonly performed tasks

- steps required to perform those tasks

- how to simplify the steps and the tasks into single element

"Simple" is actually much more difficult to code.  You will likely need to eliminate the hundreds of options that could be and focus on the ones that are needed.

To rephrase what you're asking for is this: non-trivial and easy to use.  Dig into your use cases; find the commonality; present a "single" option to reflect the commonality of that use case.

And / Or just write really solid documentation that thoroughly explains what the options will do.  One fault I find with most man pages is that they're usually great for reference, but difficult to learn from.

Body:
You have started with:

need my command line options to be simple but powerful

modelling my utility on top of LVM(thats all the info I can give for now)

Good thing that's not a tall-order request.

Since we don't know what specific logical volume manager functions you are referring to, it's hard to give specific examples of what to create for a command line option.

In general, you want to think about:

- commonly performed tasks

- steps required to perform those tasks

- how to simplify the steps and the tasks into single element

"Simple" is actually much more difficult to code.  You will likely need to eliminate the hundreds of options that could be and focus on the ones that are needed.

To rephrase what you're asking for is this: non-trivial and easy to use.  Dig into your use cases; find the commonality; present a "single" option to reflect the commonality of that use case.

And / Or just write really solid documentation that thoroughly explains what the options will do.  One fault I find with most man pages is that they're usually great for reference, but difficult to learn from.


问:
Why all classes in .NET globally inherits from Object class?
Its very interesting for me which advantages gives "global root class" approach for framework.
In simple words what reasons resulted the .NET framework was designed to have one root object class with general functionality suitable for all classes.

Nowadays we are designing new framework for internal use (the framework under SAP platform) and  we all divided into two camps - first who thinks that framework should have global root, and the second - who thinks opposite.

I am at "global root" camp. And my reasons what such approach would yields good flexibility and development costs reduction cause we will not develop general functionality any more.

So, I'm very interested to know what reasons really push .NET architects to design framework in such way.

答:
The pushed for a root object because they wanted all classes in the framework to support certain things (getting a hash code, converting to a string, equality checks, etc.). Both C# and Java found it useful to put all these common features of an Object in some root class.

Keep in mind that they aren't violating any OOP principles or anything. Anything in the Object class makes sense in any subclass (read: any class) in the system. If you choose to adopt this design, make sure you follow this pattern. That is, don't include things in the root that don't belong in every, single class in your system. If you follow this rule carefully, I don't see any reason why you shouldn't have a root class that contains useful, common code for the whole system.

OwnerDisplayName: Anton Semenov


答:
I remember Eric Lippert once saying that inheriting from the System.Object class provided 'the best value for the customer'. [edit: yep, he said it here]:

...They don't need a common base type. This choice was not made out of necessity. It was made out of a desire to provide the best value for the customer.

When designing a type system, or anything else for that matter, sometimes you reach decision points -- you have to decide either X or not-X... The benefits of having a common base type outweigh the costs, and the net benefit thereby accrued is larger than the net benefit of having no common base type.  So we choose to have a common base type.

That's a pretty vague answer. If you want a more specific answer, try asking a more specific question.

Having everything derive from the System.Object class provides a reliability and usefulness that I've come to respect alot. I know that all objects will have a type (GetType), that they'll be in line with the CLR's finalization methods (Finalize), and that I can use GetHashCode on them when dealing with collections.

Title: Why all classes in .NET globally inherits from Object class?

Body:
Its very interesting for me which advantages gives "global root class" approach for framework.
In simple words what reasons resulted the .NET framework was designed to have one root object class with general functionality suitable for all classes.

Nowadays we are designing new framework for internal use (the framework under SAP platform) and  we all divided into two camps - first who thinks that framework should have global root, and the second - who thinks opposite.

I am at "global root" camp. And my reasons what such approach would yields good flexibility and development costs reduction cause we will not develop general functionality any more.

So, I'm very interested to know what reasons really push .NET architects to design framework in such way.


答:
Just like the usual comment from SQL server people "it depends"

If you can, i would suggest you create a branch on the code so you can continue to apply small checkins of your work. Once completed, perform a merge backinto the main trunk.

Yes there is some chance of reowrk duplication of effort doing this. but at least you will maintian a trail of work you can rollback it it proves to be a dead end.

Title: What are good source control check-in strategies for large tasks?

Body:
The general rule is to keep check-ins small and check-in often. But sometimes the task requires large changes to the underlying framework. Then checking in before compeleting the task will break the project until you check in the finished work.

So what strategies do people use to reduce the risk of losing work, or deciding something you are doing is the wrong approach, then changing your mind after removing the code and trying another approach?

When I can, I'll check-in half done work commented out, or if it compiles and nothing is using new files I'll check them in. The larger the change the more likely I am to branch the project and then merge back when I have everything working again. Another option if the source control system allows is shelf sets, which are basically small branches. So when I finish for the day or come to a decision point, I'll shelve my changes, and then if something catastrophic happens, or I want to come back to that point, I can.


答:
Mathematically, it's a bit more elegant to have a type system which contains top, and allows you to define a language a bit more completely.

If you're creating a framework, then things necessarily will be consumed by an existing codebase. You can't have a universal supertype since all of the other types in whatever consumes the framework exist.

At that point, the decision to have a common base class depends on what you're doing. It is very rare that many things have a common behavior, and that it is useful to reference these things via the common behavior alone.

But it happens. If it does, then go right ahead in abstracting that common behavior.


答:
Because that's the way of the OOP. It's important to have a type (object) that can refer to anything. An argument of type object can accept anything. There's also inheritance, you can be sure that ToString(), GetHashCode() etc are available on anything and everything.

Even Oracle has realised the importance of having such a base type and is planning on removing primitives in Java near 2017


答:
I think that Java and C# designers added a root object because it was essentially free to them, as in free lunch.

The costs of adding a root object are very much equal to the costs of adding your first virtual function. Since both CLR and JVM are garbage collected environments with object finalizers, you need to have at least one virtual for your java.lang.Object.finalize or for your System.Object.Finalize method. Hence, the costs of adding your root object are already prepaid, you can get all the benefits without paying for it. This is the best of both worlds: users who need a common root class would get what they want, and users who could not care less would be able to program as if it's not there.


答:
Implementing event chaining well is difficult, for all the reasons mentioned by others.

However, it is also the basic premise of most rules engines.  JBoss Drools, IBM jRules, PegaSystems, Corticon, and FICO Blaze Advisor are all major Business Rules Management Systems (BRMS) that allow users to declare rules that fire off based on events that occur in the systems.  Both forward- and backward-chaining are possible and doable.

The Prolog language and its derivatives are based on the same notion.

The algorithms involved are not simple, debugging CAN be a pain, but there is a lot of value to be found in the model.


答:
A couple of reasons, common functionality all child classes can share.  And it also gave the framework writers the ability to write a lot of other functionality into the framework everything could use.  An example would be the ASP.NET caching and sessions.  Almost anything can be stored in them, because they wrote the add methods to accept objects.

A root class can be very alluring, but it is very, very easy to misuse.  Would it be possible to have a root interface instead?  And just have one or two small methods?  Or would that add a lot more code than is required to your framework?

I ask I am curious about what functionality you need to expose to all the possible classes in the framework you are writing.  Will that truly be used by all the objects?  Or by most of them?  And once you create the root class, how will you prevent people from adding random functionality to it? Or random variables they want to be "global"?

Several years ago there was very large application where I created a root class.  After a few months of development it was populated by code that had no business being in there.  We were converting a old ASP application and the root class was the replacement to the old global.inc file we had used in the past.  Had to learn that lesson the hard way.


问:
Strategy/algorithm to divide pot to chips
I want to split poker pot to chips.

Example:

Pot = $17.500.

I have the endless piles of chips. I have the following types of chips: ChipsTypes = [$1, $5, $10, $25, $100, $500, $1.000, $5.000, $10.000, and so on]. Index starts from 0.

I want to get an array that says which chips I have to take to divide the pot and in which order to have minimum number of denominations and chips after pot-to-chips conversion. For example Result = [7, 5] means that I have to take 3 * $5.000 + 5 * $500 which $17.500.

Is there is any strategy or algorithm that would suit my need?

答:
In general, since this seems like a homework question and I don't want to give away the answer, here's the strategy to solving the problem.

Find the largest denomination at or below the value of the pot and divide the pot by that denomination

That's how many of that denomination of chip you require

Take the remainder of the pot, and repeat these steps until the pot is $0.00

For example

```<code>   17.5 / 10 = 1 with 7.5 remaining (we need one $10 chip)
    7.5 / 5  = 1 with 2.5 remaining (we need one  $5 chip)
   ...etc
</code>```

...it appears I still pretty much gave away the answer.

Body:
In general, since this seems like a homework question and I don't want to give away the answer, here's the strategy to solving the problem.

Find the largest denomination at or below the value of the pot and divide the pot by that denomination

That's how many of that denomination of chip you require

Take the remainder of the pot, and repeat these steps until the pot is $0.00

For example

   17.5 / 10 = 1 with 7.5 remaining (we need one $10 chip)
    7.5 / 5  = 1 with 2.5 remaining (we need one  $5 chip)
   ...etc

...it appears I still pretty much gave away the answer.


答: The most pressing cause for Object is containers (prior to generics) which could contain anything instead of having to go C-style "Write it again for everything you need". Of course, arguably, the idea that everything should inherit from a specific class and then abusing this fact to utterly lose every speck of type safety is so terrible that it should have been a giant warning light on shipping the language without generics, and also means that Object is thoroughly redundant for new code.


问:
Does extending GPL code make the new code GPL too?
I am currently adding some functionality to a popular open source project. It written in C and in Every file GPL license text is embedded. The functionality I am adding is not supported by the project. So you can say its some sort of extending.

My code gets compiled when the main project is compiled. My code is inside the main project and its integrated heavily.

Let me explain more thoroughly. Basically I know of two types of linking.

My program uses mysql c api. so I link my c code with libmysqlclient. Here I am using libmysqlclient

My code  adds hash-table functionality on libmysqlclient so user can access fields by column name.

My project is of second type. Should it be GPL?  What about the first scenario (I am curious)?

答: Yes.  The GPL is a viral license; anything you extend the project with, or even link to it with shared libraries, must either be GPL or a compatible license, which includes many but not all other open-source licenses.</p>

ContentLicense: CC BY-SA 4.0


答:
Clojure's in-memory STM doesn't handle durable persistence directly (by definition, it is designed for in-memory use case....)

However the principles apply equally well to persisted storage. For example take a look at Datomic, which is effectively a scalable ACID database management system based on Clojure's data structures and state management philosophy.

The common principles are roughly:

Immutable persistent data structures

State transitions managed by pure functions

Unlimited read scalability (non-transactional reads never need locks)

"pluggable" transaction semantics to suit your application

Separation of identity and state

Emphasis on data separated from functions that process it (i.e. distinct from  the OOP concept of encapsulating data and code)

Title: Clojure state and persistence

Body:
I'm learning Clojure to see if it's something I can leverage at my current job, and more importantly, how I can convince my bosses that Clojure has a 'killer feature' over java that makes it worth the investment1.

The feature that I'm guessing most clojure evangelists would tout is state management and concurrency.

The example that I see often in blogs and books is an account balance that’s being updated by multiple threads.  Clojure’s state management can always cleanly ensure that the balance will be accurate regardless of the number of threads reading and writing that value.

In practice, though, an application would never allow an account balance to live only in memory, it would have to be persisted outside of the JVM (probably in a database) for two hopefully obvious reasons:

If the app goes down the database will need to accurately reflect
the latest state for recovery.  For this reason the database cannot be asynchronously updated, and all reads would have to block until the database update is complete.

If other applications are reading or
manipulating the account balance (maybe because we’ve scaled our app
out to several servers), that balance would need to be kept in sync
between all instances.

Can Clojure’s state management handle situations like this elegantly?  For instance, given scenario 2 above, all reads of the account balance would first need to check the database to get the value, and if the database is locked, it would have to block until the correct value is available, no?

It’s great that Clojure handles my in-memory concurrency very elegantly but if that elegance can’t be extended to external state then do I really gain anything?

1(note that things like expressiveness, elegance, etc. are rarely considered killer features by mgmt.)


问:
Continuous Professional development – the best approach
From my experience in the current working environment, one's professional development is definitely in the hands of the individual.

As I see it there are several routes to the same objective based on cost, time and availability

External Offsite training Online

Training providers (itunes U,Pluralsight etc)

Books

Specialist /user groups

Specialist web sites (Channel9, stackoverflow,dnrtv,codeplex etc)

What would you consider to be the best approach (blend) to continued learning and maintaining a professional standard of work?

答: If you are on a team, I'd say the best way for learning is to work together with your peers and learn from each other.</p>


答:
In case (2), where you have actually added code to an existing GPL'ed project, the GPL is very clear that you are creating a derived work, which is subject to the GPL.

In the case of (1), there is some disagreement about whether or not linking to a GPL library obligates you to license your product under the GPL.  Personally, I am of the mind that you can do whatever you want by linking to a GPL library.  It seems to me that in this case, you are simply making use of the library, not creating a derived work.

However, it is also good to know that there is another license called the "LGPL" which specifically states that you are not obligated to license a product under the GPL as a result of linking to an LGLP library.

Title: Does extending GPL code make the new code GPL too?

Body:
I am currently adding some functionality to a popular open source project. It written in C and in Every file GPL license text is embedded. The functionality I am adding is not supported by the project. So you can say its some sort of extending.

My code gets compiled when the main project is compiled. My code is inside the main project and its integrated heavily.

Let me explain more thoroughly. Basically I know of two types of linking.

My program uses mysql c api. so I link my c code with libmysqlclient. Here I am using libmysqlclient

My code  adds hash-table functionality on libmysqlclient so user can access fields by column name.

My project is of second type. Should it be GPL?  What about the first scenario (I am curious)?


问:
Understanding my dvcs workflow
We are going to be building a new project using Mercurial as our version control system.

I'm still trying to fully understand what my workflow should look like, so I've listed below a case that I need some help undertanding.

A single application with multiple modules (Each module being hosted in its own repository)
Multiple developers need to make changes to the same module.
How should this be managed?

Should a hg pull be done and all changes be made on the local developers machine. Once those changes have been made the changes are pushed to dev.

Should each feature/bug fix get a new repository or branch on the server and the developer pushes his changes from his local hg to the remote hg. Once the feature is completed that repo/branch is merged back into dev.

Or a combinatiom of both. Small changes go straight into dev, and a feature that could take some time gets its own branch/repo.

Or any other strategies that you think are better suited.

答:
First off, are the modules project independant?, if not, consider avoiding using subrepos. Subrepos are considered a feature of last resort.

Secondly, don't go wild with the clones. Some use it instead of creating a branch (see dvcs - is "clone to branch" a common workflow?). I'd advise you to use repository management software/service such as Rhodecode or Bitbucket, and have each developer have a public fork to follow this workflow:

Finally, read about feature branching and maybe a little about Gitflow (the basic ideas are DVCS agnostic).

Title: Understanding my dvcs workflow


答:
All standalone heap objects inherit from Object; that makes sense because all standalone heap objects must have certain common aspects, such as a means of identifying their type.  Otherwise, if the garbage-collector had a reference to a heap object of unknown type, it would have no way of knowing what bits within the blob of memory associated with that object should be regarded as references to other heap objects.

Further, within the type system, it is convenient to use the same mechanism for defining the members of structures and the members of classes.  The behavior of value-type storage locations (variables, parameters, fields, array slots, etc.) is very different from that of class-type storage locations, but such behavioral differences are achieved in the source-code compilers and execution engine (including the JIT compiler) rather than being expressed in the type system.

One consequence of this is that defining a value type effectively defines two types--a storage-location type and a heap-object type.  The former may be implicitly converted to the latter, and the latter may be converted to the former via typecast.  Both types of conversion work by copying all public and private fields from one instance of the type in question to another.  Additionally, it is possible using generic constraints to invoke interface members on a value-type storage location directly, without making a copy of it first.

All of this is important because references to value-type heap objects behave like class references and not like value types.  Consider, for example, the following code:

```
string testEnumerator<T>(T it) where T:IEnumerator<string>
{
  var it2 = it;
  it.MoveNext();
  it2.MoveNext();
  return it.Current;
}
public void test()
{
  var theList = new List<string>();
  theList.Add("Fred");
  theList.Add("George");
  theList.Add("Percy");
  theList.Add("Molly");
  theList.Add("Ron");

  var enum1 = theList.GetEnumerator();
  IEnumerator<string> enum2 = enum1;

  Debug.Print(testEnumerator(enum1));
  Debug.Print(testEnumerator(enum1));
  Debug.Print(testEnumerator(enum2));
  Debug.Print(testEnumerator(enum2));
}
```

If the testEnumerator() method is passed a storage location of value type, it will receive an instance whose public and private fields are copied from the passed-in value.  Local variable it2 will hold another instance whose fields are all copied from it.  Calling MoveNext on it2 will not affect it.

If the above code is passed a storage location of class type, then the passed-in value, it, and it2, will all refer to the same object, and thus calling MoveNext() on any of them will effectively call it on all of them.

Note that casting List<String>.Enumerator to IEnumerator<String> effectively turns it from a value type to a class type.  The type of the heap object is List<String>.Enumerator but its behavior will be very different from the value type of the same name.

Body:
All standalone heap objects inherit from Object; that makes sense because all standalone heap objects must have certain common aspects, such as a means of identifying their type.  Otherwise, if the garbage-collector had a reference to a heap object of unknown type, it would have no way of knowing what bits within the blob of memory associated with that object should be regarded as references to other heap objects.

Further, within the type system, it is convenient to use the same mechanism for defining the members of structures and the members of classes.  The behavior of value-type storage locations (variables, parameters, fields, array slots, etc.) is very different from that of class-type storage locations, but such behavioral differences are achieved in the source-code compilers and execution engine (including the JIT compiler) rather than being expressed in the type system.

One consequence of this is that defining a value type effectively defines two types--a storage-location type and a heap-object type.  The former may be implicitly converted to the latter, and the latter may be converted to the former via typecast.  Both types of conversion work by copying all public and private fields from one instance of the type in question to another.  Additionally, it is possible using generic constraints to invoke interface members on a value-type storage location directly, without making a copy of it first.

All of this is important because references to value-type heap objects behave like class references and not like value types.  Consider, for example, the following code:

string testEnumerator<T>(T it) where T:IEnumerator<string>
{
  var it2 = it;
  it.MoveNext();
  it2.MoveNext();
  return it.Current;
}
public void test()
{
  var theList = new List<string>();
  theList.Add("Fred");
  theList.Add("George");
  theList.Add("Percy");
  theList.Add("Molly");
  theList.Add("Ron");

  var enum1 = theList.GetEnumerator();
  IEnumerator<string> enum2 = enum1;

  Debug.Print(testEnumerator(enum1));
  Debug.Print(testEnumerator(enum1));
  Debug.Print(testEnumerator(enum2));
  Debug.Print(testEnumerator(enum2));
}

If the testEnumerator() method is passed a storage location of value type, it will receive an instance whose public and private fields are copied from the passed-in value.  Local variable it2 will hold another instance whose fields are all copied from it.  Calling MoveNext on it2 will not affect it.

If the above code is passed a storage location of class type, then the passed-in value, it, and it2, will all refer to the same object, and thus calling MoveNext() on any of them will effectively call it on all of them.

Note that casting List<String>.Enumerator to IEnumerator<String> effectively turns it from a value type to a class type.  The type of the heap object is List<String>.Enumerator but its behavior will be very different from the value type of the same name.


问:
DDD, Saga & Event-sourcing: Can a Compensate Action simply be a delete on the event store?
I realize the above question probably raises a few 'what??'s, but let me try to explain :

I'm trying to wrap my head on a couple of related concepts, basically the Saga-pattern ( http://www.rgoarchitects.com/Files/SOAPatterns/Saga.pdf) in combination with Event-sourcing (A DDD-concept: http://en.wikipedia.org/wiki/Domain-driven_design)

A good post that wraps it together:
https://blog.jonathanoliver.com/cqrs-sagas-with-event-sourcing-part-ii-of-ii/

I'm getting to the question in a minute, but I think I have to try to summarize what I understand of it first (which might well be wrong, so please correct if that's the case) since this might well impact why I'm asking the question to begin with:

The Saga pattern is a sort of broker that given an action (end-user, automated, etc. essentially anything that is going to change data) divides that action up in business activities and sends each of these activities as messages to a Message Bus which in turn sends it to the respective aggregate roots to be taken care of.

These aggregate roots can operate completely autonomously (nice separation of concerns, great scalability, etc. )

A Saga-instance itself doesn't contain any business logic, that is contained in the aggregate roots it sends activities to. The only 'logic' contained in the Saga is 'process'-logic, (often implemented as a Statemachine), which determines based on actions received (as well as follow-up events) what to do (i.e: what activities to send)

The Saga-patterns implements a kind of distributed transaction pattern. I.e: when one of the aggregate roots (which again work autonomously, without knowing of eachothers existense) fails, the entire action might have to be rolled back.

This is implemented by having all aggregate roots, upon completion of their activity report back to the Saga. (In case of success as well as error)

In case all aggregate roots return a success, the internal statemachine if the Saga determines what to do next (or decides it's  done)

In case of failure, the Saga issues to all aggregate roots that took part in the last action a so called Compensation Action, i.e: an action to undo the last action each of the aggregate roots did.

This might be simply doing a 'Minus 1 vote' if the action was "plus 1 vote' but it could be more complicated like restoring a blogpost to it's previous version.

Event-sourcing (see the blogpost combining the two) aims to externalize saving the results of each of the activities that each of the aggregate roots undertake to a centralized Event Store (the changes are called 'events' in this context)

This Event store is the 'single version of the truth' and can be use to replay the state of all entities simply by iterating the events stored (essentially like an event log)

Combining the two (i.e: letting aggregate roots use Event-sourcing to outsource saving their changes before reporting back to the Saga) enables lots of nice possibilities, one of which concerns my question...

I felt I needed to get this off of my shoulder, since it's a lot to grasp in one go. Given this context/mindset (again, please correct if wrong)

the question: When an aggregate root receives a Compensate Action and if that aggregate root has outsourced it's state-changes using Event-sourcing, wouldn't the Compensate Action in all situations just be a delete of the last event in the Event Store for that given Aggregate Root? (Assuming the persist-implementation allows deletes)

That would make sense to me a lot (and would be another great benefit of this combination) but as I said I might be making these assumptions based on a incorrect/incomplete understanding of these concepts.

I hope this didn't get too long-winded.

Thanks.

答:
For completeness I thought to include an relevant snippet from Martin Fowler about ways to revert state:

As well as events playing themselves forwards, it's also often useful
  for them to be able to reverse themselves.

Reversal is the most straightforward when the event is cast in the
  form of a difference. An example of this would be "add $10 to Martin's
  account" as opposed to "set Martin's account to $110". In the former
  case I can reverse by just subtracting $10, but in the latter case I
  don't have enough information to recreate the past value of the
  account.

If the input events don't follow the difference approach, then the
  event should ensure it stores everything needed for reversal during
  processing. You can do this by storing the previous values on any
  value that is changed, or by calculating and storing differences on
  the event.

From: http://martinfowler.com/eaaDev/EventSourcing.html

OwnerDisplayName: Geert-Jan


答:
This design really traces back to Smalltalk, which I would view largely as an attempt at pursuing object orientation at the expense of nearly any and all other concerns. As such, it tends (in my opinion) to use object orientation, even when other techniques are probably (or even certainly) superior.

Having a single hierarchy with Object (or something similar) at the root makes it fairly easy (for one example) to create your collection classes as collections of Object, so it's trivial for a collection to contain any kind of object.

In return for this rather minor advantage, you get a whole host of disadvantages though. First, from a design viewpoint, you end up with some truly insane ideas. At least according to the Java view of the universe, what do Atheism and a Forest have in common? That they both have hashcodes! Is a Map a collection? According to Java, no, it's not!

In the '70s when Smalltalk was being designed, this sort of nonsense was accepted, primarily because nobody had designed a reasonable alternative. Smalltalk was finalized in 1980 though, and by 1983 Ada (which includes generics) was designed. Although Ada never achieved the kind of popularity some predicted, its generics were sufficient to support collections of objects of arbitrary types -- without the insanity inherent in the monolithic hierarchies.

When Java (and to a lesser extent, .NET) were designed, the monolithic class hierarchy was probably seen as a "safe" choice -- one with problems, but mostly known problems. Generic programming, by contrast, was one that almost everybody (even then) realized was at least theoretically a much better approach to the problem, but one that many commercially oriented developers considered rather poorly explored and/or risky (i.e., in the commercial world, Ada was largely dismissed as a failure).

Let me be crystal clear though: the monolithic hierarchy was a mistake. The reasons for that mistake were at least understandable, but it was a mistake anyway. It's a bad design, and its design problems pervade almost all code using it.

For a new design today, however, there's no reasonable question: using a monolithic hierarchy is a clear mistake and a bad idea.


答:
They do release some of these things.

Here's the Ribbon, usable in a .NET application.

And here's Metro, which you can program against using WPF/XAML or HTML/JavaScript.

Unfortunately,

Metro style app development in Visual Studio is supported only on Windows 8 Release Preview. Windows 7 is not supported.

Title: Why doesn't Microsoft release UX frameworks to build UI's like their current UIs?

Body:
When I started learning programming with the .NET framework, I started by using WinForms as a UI technology. It uses “classic” menus just like this office 2000:

A few years later Office 2007 was released, the ribbon was born:

And even some years later Office 2010 was released, which also added new features like the stage:
A few days ago Office 15 preview was released and they added more fancy new stuff:

That's huge progress IMO, but why don’t they enable the developers to build UI’s like them? When I have a look at .NET, there’s still no way to build a ribbon. Even with WPF, which is highly extensible, there are no premade controls. So the community has started several projects to create all those "features". I know, today Microsoft has released a ribbon for WinForms and WPF, but that's still not part of any core framework (not even the 4.5 one). But this is not limited to .NET as far as I know? Today there are still no APIs for unmanaged applications to create those ribbon UI’s?!

In Germany they are offering free UX training to make sure everything fits their style! http://j.mp/NZGgH9

Why doesn’t Microsoft give the cool stuff to us developers? Do they want their applications to be unique?


答: I haven't done TDD in C++ so i can't comment on that, but you're supposed to test the expected behaviour of your code. While the implementation can change, the behaviour should (usually?) stay the same. In Java\C# centric world, that would mean you only test the public methods, writing tests for the expected behaviour and doing that before implementation (which is usually better said than done :)). </p>

Title: Unit testing C++: What to test?

Body:
TL;DR

Writing good, useful tests is hard, and has a high cost in C++. Can you experienced developers share your rationale on what and when to test?

Long story

I used to do test-driven development, my whole team in fact, but it didn't work well for us. We have many tests, but they never seem to cover the cases where we have actual bugs and regressions - which usually occur when units are interacting, not from their isolated behaviour.

This is often so hard to test on the unit level that we stopped doing TDD (except for components where it really speeds up development), and instead invested more time increasing the integration test coverage. While the small unit tests never caught any real bugs and were basically just maintenance overhead, the integration tests have really been worth the effort.

Now I've inherited a new project, and am wondering how to go about testing it. It's a native C++/OpenGL application, so integration tests are not really an option. But unit testing in C++ is a bit harder than in Java (you have to explicitely make stuff virtual), and the program isn't heavily object oriented, so I can't mock/stub some stuff away.

I don't want to rip apart and OO-ize the whole thing just to write some tests for the sake of writing tests. So I'm asking you: What is it I should write tests for? e.g.:

Functions/Classes that I expect to change frequently?

Functions/Classes that are more difficult to test manually?

Functions/Classes that are easy to test already?

I began to investigate some respectful C++ code bases to see how they go about testing. Right now I'm looking into the Chromium source code, but I'm finding it hard to extract their testing rationale from the code. If anyone has a good example or post on how popular C++ users (guys from the committee, book authors, Google, Facebook, Microsoft, ...) approach this, that'd be extra helpful.

Update

I have searched my way around this site and the web since writing this. Found some good stuff:

When is it appropriate to not unit test?

https://stackoverflow.com/questions/109432/what-not-to-test-when-it-comes-to-unit-testing

http://junit.sourceforge.net/doc/faq/faq.htm#best

Sadly, all of these are rather Java/C# centric. Writing lots of tests in Java/C# is not a big problem, so the benefit usually outweights the costs.

But as I wrote above, it's more difficult in C++. Especially if your code base is not-so-OO, you have to severely mess things up to get a good unit test coverage. For instance: The application I inherited has a Graphics name space that is a thin layer above OpenGL. In order to test any of the entities - which all use its functions directly - I'd have to turn this into an interface and a class and inject it in all the entities. That's just one example.

So when answering this question, please keep in mind that I have to make a rather big investment for writing tests.


问:
Best practice on if/return
I want to know what is considered better way of returning when I have if statement.

Example 1:

```<code>public bool MyFunction()
{
   // Get some string for this example
   string myString = GetString();

   if (myString == null)
   {
      return false;
   }
   else
   {
      myString = "Name " + myString;
      // Do something more here...
      return true;
   }
}
</code>```

Example 2:

```<code>public bool MyFunction()
{
   // Get some string for this example
   string myString = GetString();

   if (myString == null)
   {
      return false;
   }

   myString = "Name " + myString;
   // Do something more here...
   return true;
}
</code>```

As you can see in both examples function will return true/false but is it a good idea to put else statement like in first example or it is better to not put it?

答: When your if statement always returns then there is no reason to use an else for the remaining code in the function.  Doing so adds extra lines and extra indentation.  Adding unnecessary code makes it harder to read and as everyone knows Reading code is Hard.

Title: Best practice on if/return


问:
Open source software with good code documentation to improve design skill
As I'm trying to get better at designing good software I'm wondering if there are out there good (as in well written) open source software with lot of code documentation that aims to explain details about why this or that design choice was made in the context of that specific problem set. I'm interested in OOP and I don't really care much about the language (php / java / c# are preferred tho :))

Example:

Problem: X

Possible way to handle this problem: A, B, C.

We choose B because... (technical details about the implementation, pros and cons, code comments etc)

答: There's a massive amount of code available for Java system classes.  It probably lacks the level of documentation you want, but it's real code solving real problems.  If you work in Java anyway it can be easy to get at and real interesting.</p>


问:
Is it common to use partial classes to achieve 'modularity'?
I recently encountered a situation in our codebase where a different team created a 'god class' containing around 800 methods, split across 135 files as a partial class.

I asked the other team about this.  While my gut reaction was to nuke it from orbit, they insist that it's a good design, a common practice, and that it promotes 'modularity' and 'ease of implementation' because new developers can bolt on functionality with almost no knowledge of the rest of the system.

Is this actually a common practice or in any way a good idea?  I'm inclined to take immediate steps to bring this beast down (or at least prevent it from growing further) but I'm willing to believe I'm wrong.

答:
This is not in any way a good idea.

Partial classes exist to help the form designer.  Using them for any other reason (and arguably for their intended purpose, but that's a different matter) is a bad idea, because it leads to bloated classes that are hard to read and understand.

Look at it this way:  If a god class with 800 methods in one file, where you know where everything is, is a bad thing--and I think everyone would agree that it is--then how can a god class with 800 methods spread across 135 files, where you don't know where everything is possibly be a good thing?


答:
The definition of O(f(n)) means that the specified algorithm's running time is less than or equal to c*f(n), for some c > 0, and for some n > n' (i.e. large values of n going towards infinity).

So O(1) implies that the running time is less than some constant, say j.

And O(n) implies that the running time is less than some constant, say k, times n. So k*n.

Since we're assuming the lists are small, that means that n is a very small number. Now, depending on implementation, the values of j and k can vary as well. It is entirely possible for the O(1) constant time to be very long, say on the order of seconds. And it is also possible that the O(n) constant factor could be very short, say on the order of microseconds. In this case, with a small value of n, it is clear that the O(n) algorithm can outperform the O(1) algorithm (n microseconds vs. a few seconds).

The original statement is definitely correct - you really can't compare Big-O easily without considering constants, but mainly at small values of n. Once you get to larger values, the differences become more clear.


答: I learned how a mathematical concept like Semirings applies to algorithms. With this you can show how some algorithms are the same except for using a different semiring. This shouldn't be that strange for me as a programmer, but my head was blown.</p>

Title: What's the most important, useful or enlightening thing you learnt in the last 12 months?

Body:
A lot of people in the coding community talk about continuous improvement, deliberate practice and so-on - but when they talk about their current practices it's almost like they 'sprang fully formed from the loins of Zeus' because you don't hear about how their opinions changed over time or what they learnt recently.

Every now and then though I go to a talk, or read a book, or talk to someone and they open up a bit more and I find that I learn a lot from these insights.

So, if you had to pick one thing from the last 12 months that you learnt what would it be?


答:
So in the end, they are doing normal procedural development without any piece of OOP. They have one global namespace with all methods, variables and whatnot.

Either persuade them they are doing it wrong or get the hell out of there.

Title: Is it common to use partial classes to achieve 'modularity'?

Body:
I recently encountered a situation in our codebase where a different team created a 'god class' containing around 800 methods, split across 135 files as a partial class.

I asked the other team about this.  While my gut reaction was to nuke it from orbit, they insist that it's a good design, a common practice, and that it promotes 'modularity' and 'ease of implementation' because new developers can bolt on functionality with almost no knowledge of the rest of the system.

Is this actually a common practice or in any way a good idea?  I'm inclined to take immediate steps to bring this beast down (or at least prevent it from growing further) but I'm willing to believe I'm wrong.


问:
How to port this architecture to .net?
My team is currently locked into using a tool we dislike that takes the form of a Eclipse plugin and a .jar; the plugin gives us a button to quickly run a single file's code (via invoking the main .jar and passing to it the current file). We want to move to C#.net.  Is there any way to get Visual Studio to replicate this behavior? Obviously we could put each runnable class into its own project in our solution, but that requires checking a lot of project files into source control. Ideally we'd have a main() method in each file and could tell visual studio to run just that file for development purposes, while the finished software would be run from a single entry point using command-line parameters.</p>

<p>(I don't want to give too much information here regarding the purpose of the software, so please just accept that the current setup makes a lot of sense for what we're doing and changing it too much would be rejected by management.) </p>

答:
What you are describing should be covered by a unit testing framework (to test your different classes in isolation).

nUnit supports categories, allowing you to selectively run sets of unit tests as needed.

Title: How to port this architecture to .net?


答:
I believe it could be done like this, but I'm not sure if it can really be implemented.

It would implemented Visual Studio addon, this addon then adds a popup action to source files. When action is executed, the code is compiled into assembly. Then using reflection, the class in file is found and checked against contract. This contract can be either interface of specific method. This contract is then executed.

Title: How to port this architecture to .net?

Body:
My team is currently locked into using a tool we dislike that takes the form of a Eclipse plugin and a .jar; the plugin gives us a button to quickly run a single file's code (via invoking the main .jar and passing to it the current file). We want to move to C#.net.  Is there any way to get Visual Studio to replicate this behavior? Obviously we could put each runnable class into its own project in our solution, but that requires checking a lot of project files into source control. Ideally we'd have a main() method in each file and could tell visual studio to run just that file for development purposes, while the finished software would be run from a single entry point using command-line parameters.</p>

<p>(I don't want to give too much information here regarding the purpose of the software, so please just accept that the current setup makes a lot of sense for what we're doing and changing it too much would be rejected by management.) </p>


答:
I don't like this at all. However, maybe the partial classes made sense to the developers during development because it allowed concurrent development of this large number of methods, specially if there is not much dependency between them.

Another possibility is that those partial classes were built to amend an automatically generated core class. If this is the case, one should not touch them, otherwise the custom code would be whipped-out when re-generating.

I am not sure that anyone can maintain this with ease without some study. Now if you kill it, the number of methods will not go down. The number of methods and complexity, to me, is the real problem. If the methods really belong to the class, then having 1 huge file is not going to make your life easier, specially in maintenance, in fact, it may be more error-prone to expose all this code for silly mistakes such as wild card search and replace.

So be careful and justify the kill decision. Also, consider what testing will be required.


答: Its perfectly fine from a practical design perspective assuming the 135 files actually group methods together similar to what traditional classes would do. It's only an average of 6 methods-per-file. Its definitely not the most popular or traditional way to design a project. Trying to change it will just create a bunch of problems and ill will for no real benefit. Making the project conform to OO standards will create as many problems as it solves. It is a completely different matter if the multiple files don't actually provide any meaningful separations.</p>


答:
What you want to do is actually interesting, it's hard to prove if it's wrong or right until you are done.

Here are some things to think about:

When would you ever deliberately pass this top-level object over a more specific object?

What code do you intend to put into every single one of your classes?

Those are the only two things that can benifit from a shared root.  In a language it is used to define a few very common methods and allow you to pass objects that haven't been defined yet, but those shouldn't apply to you.

Also, from personal experience:

I used a toolkit once written by a developer who's background was Smalltalk.  He made it so all his "Data" classes extended a single class and all the methods took that class--so far so good. The problem is the different data classes weren't always interchangable, so now my editor and compiler couldn't give me ANY help as to what to pass into a given situation and I had to refer to his docs which didn't always help..

That was the most difficult to use library I've ever had to deal with.


问:
What's the career path for a developer who doesn't like management?
If you're developer (Senior or Lead Developer) and you'd rather stay with code/design than pursue a management career, what are the available career paths at your company, or any you've heard of? How far can you go?

Is it possible to continue being a geek until you bite the dust or is that too naive?

Are people like Uncle Bob for example still considered developers, as they claim?

答: Although Architect seems to have negative connotations, I think that's the technical equivalent of moving to management.


答:
The best approach would be to get books and update you knowledge on tools you wish to learn.

Specialist websites should help you to answer some of your main questions.

Of course we have to consider that you should have, something like:

Willingness to experiment: try different commands until he got the software to do what you want. Try a few fixes on your own software before asking for help!

Ability to learn independently: never wait for an explanation, go for it! Hard-earned knowledge never fades and provides motivation when the next challenge appears!

Great sense of curiosity: ask your self how does this work? what does this code do? what about if you try a particular sequence of commands? Master your programs.

Title: Continuous Professional development – the best approach

Body:
From my experience in the current working environment, one's professional development is definitely in the hands of the individual.

As I see it there are several routes to the same objective based on cost, time and availability

External Offsite training Online

Training providers (itunes U,Pluralsight etc)

Books

Specialist /user groups

Specialist web sites (Channel9, stackoverflow,dnrtv,codeplex etc)

What would you consider to be the best approach (blend) to continued learning and maintaining a professional standard of work?


答:
The MSDN Partial Classes and Methods page suggests two situations for using partial classes:

1.  To split a giant class into multiple separate files.

2.  To have a place to put automatically generated source code.

2 is heavily used by Visual studio (e.g., for aspx files and for winforms).  This is a reasonable use of partial classes.

1 is what your team is doing.  I would say that using partial classes is a perfectly reasonable way to achieve modularity when you have giant classes, but having giant classes is itself unreasonable.  In other words, having a giant class is a bad idea, but if you're going to have a giant class, partial classes are a good idea.

Though if you can intelligently split a class into separate files for different users to work on, can't you just split it up into separate classes instead?


答:
One good example is the Linux kernel. The mailing list explains many design decisions, and there are also books that describe why the internals are written the way they are (one example being Understanding the Linux Kernel, although it looks like there are many others. Linux Magazine also has (or at least used to have) a summary of the mailing list talking about the main discussions/design decisions in the kernel community.

EDIT:
Since the kernel can be intimidating to just start "learning," here are a few areas to start with:

Task scheduling

Kernel memory allocation

file system

If you limit the scope to a single component, it should be easier to understand.

Also, to look at the code easily while reading documentation, it might help to look at LXR.

Title: Open source software with good code documentation to improve design skill

Body:
As I'm trying to get better at designing good software I'm wondering if there are out there good (as in well written) open source software with lot of code documentation that aims to explain details about why this or that design choice was made in the context of that specific problem set. I'm interested in OOP and I don't really care much about the language (php / java / c# are preferred tho :))

Example:

Problem: X

Possible way to handle this problem: A, B, C.

We choose B because... (technical details about the implementation, pros and cons, code comments etc)


问:
How to document unlimited argument parameters?
In PHP you can have a function take an infinite number of arguments like

```<code>  /**
   * Do abc...
   *
   * @since   1.0
   * @param   mixed $arg1       Arg description
   * @return  string            Results
   */
function abc($arg1 = null){
  $args = func_get_args();
  // do smth with $args
}
</code>```

How should I illustrate this in my DocBlock ?

答:
phpdoc.org manual example:

```<code>/**
 * @param mixed $varname,... unlimited OPTIONAL number of additional variables [...]
 */
</code>```

You may document parameters listed or any optional paramters that will
  be parsed by standard PHP functions func_num_args()/get_func_arg().
  Recommended name format for parameters listed with func_get_arg() is:

$paramname if there is only one parameter

$paramname,... if the number of parameters is unlimited

phpDocumentor will display the optional description unmodified.

Note that the $paramname,... will be shown in the output docs in both
  the parameter listing AND the function signature. If you are not
  indicating in the actual code that the parameter is optional (via
  "$paramname = 'a default value'"), then you should mention in the
  parameter's description that the parameter is optional.

Body:
phpdoc.org manual example:

/**
 * @param mixed $varname,... unlimited OPTIONAL number of additional variables [...]
 */

You may document parameters listed or any optional paramters that will
  be parsed by standard PHP functions func_num_args()/get_func_arg().
  Recommended name format for parameters listed with func_get_arg() is:

$paramname if there is only one parameter

$paramname,... if the number of parameters is unlimited

phpDocumentor will display the optional description unmodified.

Note that the $paramname,... will be shown in the output docs in both
  the parameter listing AND the function signature. If you are not
  indicating in the actual code that the parameter is optional (via
  "$paramname = 'a default value'"), then you should mention in the
  parameter's description that the parameter is optional.


问:
C++ Class Initalization
I'm a python programmer who sees a lot of C++ code but doesn't know the language and there seems to be two ways to initalize a class. I was hoping that someone can tell me the difference.

```<code>class Point {
        int x, y;
     public:
        int get_x();
        int get_y();
        Point(int, int);
}

// ok we are going to leave the methods and constructors unimplemented for brevity
// now here's the part that puzzles me
Point p(5, 5); // ..or
Point p = new Point(5, 5);
</code>```

What's the diffrence between the two?

答:
One of those variables lives on the stack, the other on the heap. The correct syntax is this:

```<code>Point p(5, 5);
Point* p = new Point(5, 5);
</code>```

The first one creates an object on the stack. When p goes out of scope, it'll be removed automatically. The second, creates a point object on the heap. Until you remove it manually, it'll remain in memory.

In the second case, p is a pointer to the Point object, while in the first case p is the point object.

Python essentially does only the second version and doesn't do the first. Python is garbage collected, so it'll also remove the point object from memory if it is no longer referenced.

However, I should mention (see comments) that the prefered method to create objects on the heap is to use smart pointers. See DeadMG's answer for more details.

Title: C++ Class Initalization

Body:
One of those variables lives on the stack, the other on the heap. The correct syntax is this:

Point p(5, 5);
Point* p = new Point(5, 5);

The first one creates an object on the stack. When p goes out of scope, it'll be removed automatically. The second, creates a point object on the heap. Until you remove it manually, it'll remain in memory.

In the second case, p is a pointer to the Point object, while in the first case p is the point object.

Python essentially does only the second version and doesn't do the first. Python is garbage collected, so it'll also remove the point object from memory if it is no longer referenced.

However, I should mention (see comments) that the prefered method to create objects on the heap is to use smart pointers. See DeadMG's answer for more details.


答:
```<code>Point p(5, 5); // ..or
</code>```

Creates an automatic variable "on the stack". This means that it's lifetime and memory is fixed to it's scope.

```<code>Point* p = new Point(5, 5);
</code>```

Creates a memory leak, double delete, or heap corruption in your program. This means that it almost certainly will crash your program, cause it to corrupt user data, or other fun side effects. Which is why actual C++ programmers use alternatives, such as...

```<code>auto p = make_unique<Point>(5, 5);
</code>```

Creates a Point "on the heap". In this case, it's lifetime and memory is fixed to the lifetime of the owning unique_ptr<Point>. This ownership can be transferred by move semantics. Unfortunately, make_unique is not provided as Standard (a known defect) but it's relatively easy to roll your own. It is a simple factory function.

```<code>auto p = std::make_shared<Point>(5, 5);
</code>```

Also creates a Point "on the heap". In this case, it's lifetime and memory is fixed to the lifetime of each shared_ptr<Point> that points to it. When they are all destroyed, the Point will be cleaned up. shared_ptr<Point> can be copied, unlike unique_ptr<Point>. This is very similar to Python's behaviour. However, do not forget that unlike in Python, there will be no machinery to break reference cycles.

Title: C++ Class Initalization

Body:
I'm a python programmer who sees a lot of C++ code but doesn't know the language and there seems to be two ways to initalize a class. I was hoping that someone can tell me the difference.

```<code>class Point {
        int x, y;
     public:
        int get_x();
        int get_y();
        Point(int, int);
}

// ok we are going to leave the methods and constructors unimplemented for brevity
// now here's the part that puzzles me
Point p(5, 5); // ..or
Point p = new Point(5, 5);
</code>```

What's the diffrence between the two?

Body:
Point p(5, 5); // ..or

Creates an automatic variable "on the stack". This means that it's lifetime and memory is fixed to it's scope.

Point* p = new Point(5, 5);

Creates a memory leak, double delete, or heap corruption in your program. This means that it almost certainly will crash your program, cause it to corrupt user data, or other fun side effects. Which is why actual C++ programmers use alternatives, such as...

auto p = make_unique<Point>(5, 5);

Creates a Point "on the heap". In this case, it's lifetime and memory is fixed to the lifetime of the owning unique_ptr<Point>. This ownership can be transferred by move semantics. Unfortunately, make_unique is not provided as Standard (a known defect) but it's relatively easy to roll your own. It is a simple factory function.

auto p = std::make_shared<Point>(5, 5);

Also creates a Point "on the heap". In this case, it's lifetime and memory is fixed to the lifetime of each shared_ptr<Point> that points to it. When they are all destroyed, the Point will be cleaned up. shared_ptr<Point> can be copied, unlike unique_ptr<Point>. This is very similar to Python's behaviour. However, do not forget that unlike in Python, there will be no machinery to break reference cycles.


答: The book Beautiful Code documents design problems and their solutions. I don't remember if all the chapters address open source projects, but at least one of them (the chapter on a particular design problem in SVN) does.</p>


问:
Is it reasonable to use POCO's that inherit from DTO's?
I'm designing a tiered .NET application, and I want to use the Code First approach.  I'm new to this, so I'm struggling to envision how it ought to be designed.  Would the following be a reasonable approach?  What problems or limitations might I run into?

Write DTO classes for my domain.  These will be used for data transfer between the server and client over WCF.

Write a set of POCO classes that inherits from the DTO classes.  Use these to generate the database on the server.

Write another set of POCO classes that inherits from the DTO classes.  Use these to generate an SDF database on the client.

答:
I would do those in a different order-

Firstly, I'd map my business domain, and figure out the best design to solve my business problem. This will give you your domain.

Then, Ideally in a completely different mindset, think about the requirements of your client-side and UI; what data will be displayed, and how? This will give you your DTOs.

Sometimes, the DTOs will resembel your domain classes quite closely. Other times- they will not.

Mapping between them can be made easier with automatic tools such as automapper.

In general, I always advocate to completely separate your domain classes and DTOs.
The gist of it is this- domain classes and DTOs are created to solve different problems. Therefore, they are not related by a 'is-a' relationship which is inheritance.


答:
In addition to what Martin wrote, I will add the following:

The most effective way to learn is practice. Unless you are Raymond Babbitt of course.

So try to ask for tasks that you don't master completely. It will forces you to learn the appropriate technologies to complete it.

Example: You don't know anything about WCF? Take that task that state "build a WCF service for the customer object".

EDIT: Just noticed that I already answer the same question here.

I hear, I know. I see, I remember. I do, I understand. [Confucius]


问:
Give open-source developers a free license for my commercial software?
I am creating a software package that will be useful to programmers, engineers and scientists.  List price will be in the region of $1,000 -- way beyond the budget of most open-source developers, hobbyists and enthusiasts.  So I am considering two things, the first generous, the second maybe a little greedy:

Offering a free license to individual open source developers upon proof of their credentials and details of their project.  Possibly also academics too.

Making the free license conditional on the developer granting me a commercial license to use the open source code they write in my own projects.  In the academic case, it's trickier, perhaps just a credit, a copy of papers, etc.

How would (1) and (2) be received?  Are there any examples of best practice here, or good precedents I can follow?

答:
Perhaps a better solution would be:

Give your program to qualified individuals without condition.

Ask them to consider returning the favor by allowing you to distribute open-source stuff that they develop for use with your product.

You'll be dealing with people who already have a proven track record of giving away their code, so there's a good chance that they'll let you distribute your stuff if they like you and your product. They'll like you and your product much more if you don't try to impose conditions on how they choose to distribute the code they write.


答:
I would keep each of these sets of classes separate (the ones for the WFC interaction, the ones for the database, and the ones for the view..the viewmodel).  It certainly will seem at first like you're just duplicating work, which is fine.  The benefit is if any of the classes need to be reused somewhere else, then they're separate and are more portable.

Sometimes you'll have viewmodels or DTOs where the field names and datatypes match exactly.  In this case, use something like Automapper to map from one object to another.  This lets you keep things separate while keeping your code clean and making the integration much more painless.

Title: Is it reasonable to use POCO's that inherit from DTO's?

Body:
I'm designing a tiered .NET application, and I want to use the Code First approach.  I'm new to this, so I'm struggling to envision how it ought to be designed.  Would the following be a reasonable approach?  What problems or limitations might I run into?

Write DTO classes for my domain.  These will be used for data transfer between the server and client over WCF.

Write a set of POCO classes that inherits from the DTO classes.  Use these to generate the database on the server.

Write another set of POCO classes that inherits from the DTO classes.  Use these to generate an SDF database on the client.


问:
Product owners with more than one product?
Is it normal and still proper (in agile/SCRUM-based software development) for a product owner to be in charge of more than one product?</p>

答:
The important part is to have a product owner in each team who has the right mix of skills, responsibilities, time. If a single person can fill the role for two teams, there's nothing wrong with that.

On the practical side, once you have 5 or 10 people on a development team there tends to be more than enough work to keep a product owner busy. The specific number will vary based on the kind of products you build and how you divide the work.


答:
The problem with two is you end up with interesting overall licenses. For instance, if they use a GPL program as the basis for theirs, they won't restrict your commercial access to it, but you would still be bound by the terms of the GPL for your access to his program.

Not to mention that would introduce odd terms that whoever contributed code would have to deal with. Saying "I am releasing this under Apache 2 terms" makes it easier to get contributors than "I am releasing it under these terms modified to allow X, Y, and Z commercial access, blah blah blah".

Title: Give open-source developers a free license for my commercial software?

Body:
I am creating a software package that will be useful to programmers, engineers and scientists.  List price will be in the region of $1,000 -- way beyond the budget of most open-source developers, hobbyists and enthusiasts.  So I am considering two things, the first generous, the second maybe a little greedy:

Offering a free license to individual open source developers upon proof of their credentials and details of their project.  Possibly also academics too.

Making the free license conditional on the developer granting me a commercial license to use the open source code they write in my own projects.  In the academic case, it's trickier, perhaps just a credit, a copy of papers, etc.

How would (1) and (2) be received?  Are there any examples of best practice here, or good precedents I can follow?


答:
Practicality may dictate that one person serve as the product owner in some circumstances, especially in related projects where one person with a high-level view of both can help the two teams to coordinate and learn from one another's mistakes, etc.

However, you need to beware of the costs of multi-tasking. If someone is constantly having to switch contexts between unrelated projects, they are probably not going to get nearly as much accomplished as if they were able to focus on one product at a time.

Title: Product owners with more than one product?

Body: Is it normal and still proper (in agile/SCRUM-based software development) for a product owner to be in charge of more than one product?</p>