答:
I'd recommend you to read the Big Ball of Mud essay.

Basically the point that the design tends to deteriorate as you progress with development and you have to dedicate work towards containing the complexity. The complexity itself can't be eliminated, only contained, because it's inherent in the problem you are trying to solve.

This leads to the main principles of agile development. The two most relevant are "you ain't gonna need it" telling you not to prepare the design for features you are not about to implement yet, because you are unlikely to get the design right anyway and "refactor mercilessly" telling you to work on maintaining sanity of the code throughout the project.

It seems that the answer is that no design is able to facilitate any change beyond contrived examples designed specifically to show that the design is stronger than it really is.

On a side-note you should be sceptical about object oriented programming. It's a great tool in many contexts, but you need to be aware of it's limits. Especially misuse of inheritance can lead to some unbelievably convoluted code. Of course you should be equally sceptical about any other design technique. Each has it's uses and each has it's weak points. There is no silver bullet.

Title: What changes are too big to be made easy by proper design?

Body:
This is a rather vague question, but it's something I've never felt has been answered in a satisfactory way when reading about proper design.

Generally, when learning about Object Oriented programming, abstraction, factoring out, etc, the holy grail of design - and the reason they always claim you're using the development techniques in question - is that it will make your program "easy to change", "maintainable", "flexible", or any of the synonyms used to express such a productive-sounding concept.  By marking ivars private, splitting code up into many small, self-contained methods, keeping interfaces general, you supposedly gain the ability to modify your program with total ease and grace.

For relatively small changes, this has worked well for me.  Changes to internal data structures used by a class to increase performance has never been a major difficulty, and neither have changes to the user-interface end, independent of the API, such as redesigning a text entry system or overhauling the graphics for a gameplay element.

All of these changes seem inherently self-contained.  None of them involve any changes to the behavior or design of the component of your program being modified, as far as outside code it concerned.  Whether or not you're writing procedurally or in an OO style, with large functions or small, these are easy changes to make even if you have only a moderately good design.

However, whenever the changes become big and hairy - that is, changes to the API - none of my precious "patterns" ever come to the rescue.  The big change remains big, the affected code remains affected, and many hours of bug-spawning work lie ahead of me.

So, my question is this.  How big a change does proper design claim to be able to facilitate?  Is there some further design technique, either unknown to me or that I have failed to implement, that truly does make sticky-sounding modification simple, or is that promise (which I have heard made by so many different paradigms) merely a nice idea, completely disconnected from the immutable truths of software development?  Is there a "change tool" I can add to my toolbelt?

Specifically, the problem I am facing that's led me to the forums is this:  I've been working on implementing an interpreted programming language (implemented in D, but that's not relevant), and I've decided that my closures' arguments should be keyword-based, rather than positional as they currently are.  This requires modifying all existing code that calls anonymous functions, which, luckily, is rather small because I am early on in the development of my language (< 2000 lines), but would be enormous if I had made this decision at a later stage.  In such a situation, is there any way that by proper foresight in design I could have made this modification easier, or are certain (most) changes intrinsically far-reaching?  I'm curious if this is in any way a failure of my own design skills - if it is, I'd be very eager to improve them with the necessary reading material if there is a way to ameliorate the severity of the problem.

To be clear, I am in no way skeptical of OOP or any of the other patterns commonly in use. For me, however, their virtues are in the original writing, rather than the maintaining, of code bases.  Inheritance allows you to abstract repetitive patterns out well, polymorphism allows you to separate code by human-understood function (which class) rather than by machine-understood effect (which branch of the switch statement), and small, self-contained functions allow you to write in a very pleasant "bottom-up" style.  However, I'm skeptical of their claims of flexibility.


问:
How signing out a CLA prevents legal issues in open-source projects?
For example: yeoman. It's licensed under a BSD license. The CLA form (Contributor License Agreement) isn't project specific, and it can be signed electronically.

How and what issues can signing out this agreement prevent?

Does it matter how big or minor contribution I made?

Why some projects require signed CLA to accept patches, while others don't? (eg. node.js vs rails)

答:
CLA's might also (in addition to other things mentioned on this page) protect the contributors from legal issues. Have a look at this excerpt from a CLA by Google:

You are not expected to provide support for Your Contributions, except
  to the extent You desire to provide support. You may provide support
  for free, for a fee, or not at all. Unless required by applicable law
  or agreed to in writing, You provide Your Contributions on an "AS IS"
  BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  implied, including, without limitation, any warranties or conditions
  of TITLE, NON- INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
  PARTICULAR PURPOSE.

ContentLicense: CC BY-SA 3.0


问:
What changes are too big to be made easy by proper design?
This is a rather vague question, but it's something I've never felt has been answered in a satisfactory way when reading about proper design.

Generally, when learning about Object Oriented programming, abstraction, factoring out, etc, the holy grail of design - and the reason they always claim you're using the development techniques in question - is that it will make your program "easy to change", "maintainable", "flexible", or any of the synonyms used to express such a productive-sounding concept.  By marking ivars private, splitting code up into many small, self-contained methods, keeping interfaces general, you supposedly gain the ability to modify your program with total ease and grace.

For relatively small changes, this has worked well for me.  Changes to internal data structures used by a class to increase performance has never been a major difficulty, and neither have changes to the user-interface end, independent of the API, such as redesigning a text entry system or overhauling the graphics for a gameplay element.

All of these changes seem inherently self-contained.  None of them involve any changes to the behavior or design of the component of your program being modified, as far as outside code it concerned.  Whether or not you're writing procedurally or in an OO style, with large functions or small, these are easy changes to make even if you have only a moderately good design.

However, whenever the changes become big and hairy - that is, changes to the API - none of my precious "patterns" ever come to the rescue.  The big change remains big, the affected code remains affected, and many hours of bug-spawning work lie ahead of me.

So, my question is this.  How big a change does proper design claim to be able to facilitate?  Is there some further design technique, either unknown to me or that I have failed to implement, that truly does make sticky-sounding modification simple, or is that promise (which I have heard made by so many different paradigms) merely a nice idea, completely disconnected from the immutable truths of software development?  Is there a "change tool" I can add to my toolbelt?

Specifically, the problem I am facing that's led me to the forums is this:  I've been working on implementing an interpreted programming language (implemented in D, but that's not relevant), and I've decided that my closures' arguments should be keyword-based, rather than positional as they currently are.  This requires modifying all existing code that calls anonymous functions, which, luckily, is rather small because I am early on in the development of my language (< 2000 lines), but would be enormous if I had made this decision at a later stage.  In such a situation, is there any way that by proper foresight in design I could have made this modification easier, or are certain (most) changes intrinsically far-reaching?  I'm curious if this is in any way a failure of my own design skills - if it is, I'd be very eager to improve them with the necessary reading material if there is a way to ameliorate the severity of the problem.

To be clear, I am in no way skeptical of OOP or any of the other patterns commonly in use. For me, however, their virtues are in the original writing, rather than the maintaining, of code bases.  Inheritance allows you to abstract repetitive patterns out well, polymorphism allows you to separate code by human-understood function (which class) rather than by machine-understood effect (which branch of the switch statement), and small, self-contained functions allow you to write in a very pleasant "bottom-up" style.  However, I'm skeptical of their claims of flexibility.

答:
In general terms, there's "pieces of code" (functions, methods, objects, whatever) and "interfaces between pieces of code" (APIs, function declarations, whatever; including the behaviour).

If a piece of code can be changed without changing the interface that other pieces of code depend on, then the change will be easier (and it doesn't matter if you use OOP or not).

If a piece of code can't be changed without changing the interface that other pieces of code depend on, then the change will be harder (and it doesn't matter if you use OOP or not).

The main benefits of OOP are that the public "interfaces" are clearly marked (e.g. an object's public methods) and other code can't use internal interfaces (e.g. the object's private methods). Because the public interfaces are clearly marked people tend to be more careful designing those public interfaces (which helps to avoid the harder changes). Because the internal interfaces can't be used by other code you can change them without worrying about other code depending on them.


问:
Application Settings, Status and more as Singleton?
I am relatively new to programming (1yr field experience now) and I think that I am overusing the singleton pattern and I need some input on how to do it in a better way. Right now I am using singletons as an excuse for static global data. I use singleton for Application Status, Application Settings and also a lot for "Managers". Basically they are all objects which are needed by different parts of my application. I think this pattern makes it easier then creating one object and inject it into all parts that need this.

Any downsides to this approach?
Any suggestion regarding this matter?

答:
In implementing the logic for a singleton, you're going to make it harder to test your application with different values.

I suggest you look at creating a single instance of your settings class but rather than make it globally accessible, you use dependency injection to provide a reference to each of your classes.

In terms of global status, this again could be used with DI as per my suggestion above however I would suggest that application status does not need to be global. I would reexamine your design and try and decouple the need for classes to know about global state. What I feel would be a better alternative is for you to have Factories where necessary that are injected with your settings and construct your objects for you.


答:
The cost of sweeping changes are often proportional to the size of the code base. Therefore, reduction of the size of the code base should always be one of the goals of any proper design.

In your example, proper design has already made your job easier: having to make changes throughout a 2000 lines of code base, instead of a 20000 or 200000 lines of code base.

Proper design reduces sweeping changes, but do not eliminate them.

Sweeping changes are quite easily automatable if there are proper support from language analysis tools. A blanket refactoring change can be applied to the whole code base in a search-and-replace style (while properly respecting the language rules). The programmer only need to make a yes/no judgement for every search hit.


问:
How to deal with complex codes in (huge) projects
I am preparing a memoir about "Why do (some) IT projects become too complex and how to avoid it ?".

If you have ever encountered projects having complex codes or were hard to maintain, how did you manage to go through it?

If you have to choose between several applications to use in your project, what would be your top priority in their functionality and why?

答: Also, resist the temptation to add quick hacks because the code is complex/bad/hacky already. In my experience you'll end up with exponential more complexity.</p>

ContentLicense: CC BY-SA 2.5


问:
Programming interview: on sorted arrays, algorithm proof
The following is a programming interview question: Given 3 sorted arrays. Find(x,y,z), (where x is from 1st array, y is from 2nd array, and z is from 3rd array), such that Max(x,y,z) - Min(x,y,z) is minimum. This question is discussed here: http://www.careercup.com/question?id=14805690

One possible solution discussed in the career cup page is the following: "Take three pointers. Each to the first element of the list. then find the min of them. compute max(xyx)-Min(xyz). If result less than till now result change it. increment the pointer of the array which contains the minimum of them"

My question is, how can we prove the correctness of this algorithm? If not, can we come up with cases where the algorithm fails. And if so, what is a correct algorithm to solve this problem with the proof.

答:
The algorithm has as loop-invariant where we know the smallest value of max(x, y, z) - min(x, y, z) for all possible values of x, y, or z smaller than the current values.

To start with x, y, and z are the smallest possible, so the invariant is true at the beginning. At the end, x, y, and z are the largest possible, so they cover all possible values, and we have the answer.

Given some values of x, y, z, if we know the optimal value of max(x, y, z) - min(x, y, z) for smaller values, then any better value would require incrementing x, y, or z.

If we don't increment the minimum of them then every larger value of x, y, or z can only increase the value of max(x, y, z) - min(x, y, z) because the maximum can only increase, and the minimum will stay the same. So the minimum is incremented to the smallest value that could possibly be better than the one we have, which maintains the loop-invariant.

OwnerDisplayName: Romonov

OwnerDisplayName: fgb


答:
Lets call sorted arrays A1, A2, A3. We have three indices i1, i2, i3. We want to find one triple (i1,i2,i3) such that max(A1[i1], A2[i2], A3[i3]) - min(A1[i1], A2[i2], A3[i3]) is minimal. At beginning i1 = i2 = i3 = 0.

One possible way is to try all triples (i1, i2, i3) for 0 <= i1 < A1.lenght, 0 <= i2 < A2.lenght, 0 <= i3 < A3.lenght. But many of those triples will be unnecessary to check.

Without loss of generality (this is just for easier talking about arrays) let A1[i1] <= A2[i2] <= A3[i3]. We will do one increment in this block.

There is no sence to try triples (j, i2, i3) for j < i1, because arrays are sorted and A1[j] <= A1[i1] which is minimum. Lets pretend we already tried all these (j, i2, i3).

There is no sence to try (i1, i2, j) for j > i3 because A3[i3] <= A3[j].

By trying triples (i1, j, i3) for arbitrary j we can go worse (min will be less or equal and max will be higher or equal).

We tried indices less than i1, i2, i3. We reasoned triples (j < i1, i2, i3) and (i1, j, i3) are unnecessary, (i1, i2, j>i3) too. Same arguments for (j <= i1, k, l = i3). Decrementing i3 is no use as we tried (actually or reasoned about it) this triple before increasing the third index.

We are left to increasing i1 which is index of min in the triple. After this the difference might get worse or A1[i1+1] is not minimal, but we proceed the same way.

Title: Programming interview: on sorted arrays, algorithm proof

Body:
The following is a programming interview question: Given 3 sorted arrays. Find(x,y,z), (where x is from 1st array, y is from 2nd array, and z is from 3rd array), such that Max(x,y,z) - Min(x,y,z) is minimum. This question is discussed here: http://www.careercup.com/question?id=14805690

One possible solution discussed in the career cup page is the following: "Take three pointers. Each to the first element of the list. then find the min of them. compute max(xyx)-Min(xyz). If result less than till now result change it. increment the pointer of the array which contains the minimum of them"

My question is, how can we prove the correctness of this algorithm? If not, can we come up with cases where the algorithm fails. And if so, what is a correct algorithm to solve this problem with the proof.

OwnerDisplayName: kyticka


答:
There is no design methodology that can save you from the hassles of a big requirements/scope change. It is just impossible to imagine and account for all possible changes that could be thought of at a later date.

Where a good design does help you is in helping you understand how all the parts fit together and what will be affected by the proposed change.

Additionally, a good design can limit the parts that are affected by most of the proposed changes.

In short, all changes are made easier by a good design, but good design can't turn a big change into a small one. (a bad/no design on the other hand can turn any small change into a big one.)


问:
If I accept contributions under a CLA, can I write "Copyright (c) My-Name"?
I'm thinking about open sourcing a project of mine. I'd accept contributions under a CLA that grants me a copyright license (I'll explain what I mean at the  end of this question). — Now, if someone submits a contribution, is it then okay that I write Copyright (c) 2013 My-Name at the top of each file? And mention any contributors in a separate document only, and refer people to the Git commit log and to GitHub statistics if they want details on individual contributors?

I think this should be fine with Copyright (c) My-Name, since I've been granted a copyright license?

If it's not okay, then I suppose the copyright-info-preamble of each source code file would have to include the name of all contributors to that file? Which doesn't seem practical (if there are very many contributors).

Here I'll try to explain what I mean with a "a CLA that grants me a copyright license". This is an edited excerpt from a CLA by Google:

.2. [...] You [that is, the contributor] hereby grant to [My-Name, that is, me] and to recipients of software
  distributed by [My-Name] a perpetual, worldwide, non-exclusive,
  no-charge, royalty-free, irrevocable copyright license to reproduce,
  prepare derivative works of, publicly display, publicly perform,
  sublicense, and distribute Your Contributions and such derivative
  works.

答:
No, you may not.

"Copyright (C) (year) (name): All Rights Reserved" is a copyright notice.  A copyright notice states unequivocally that YOU own the work in question, and people desiring to use the work must deal with you.  Note that the phrasing is High Magic: it must be phrased precisely this way.

Google's Contributor License Agreement (CLA) means that the person who owns the work in question has granted Google a license to use it, in accordance with the terms of the license.  It does not transfer ownership of the work.  The owner retains his rights as owner, unless he specifically gives them up (translation: SELLS them, in most cases).  This specifically includes the right to license the work to other people, regardless of how Google might feel about those other people.

Affixing a copyright notice to a work for which you have been assigned a license, but have not actually acquired ownership, is misrepresentation.


问:
Is modern C++ replacing C#? Is Microsoft pushing developers to adopt C++?
I hear about modern C++ popularity and some talks about migrating back to C++ from C# or other C-like languages.

I know about C++11 features but I would like to hear your experiences, especially from developers who migrated from C# to C++.

More importantly, does Microsoft push developers to use C++? If yes, why?

答: c++ is not replacing c#. Let us look into where c++ language is used. It is used when there is need for high performance, for writing middleware libraries, low level access, and for writing code for resource constrained devices. Though you can use c# for some of these c++ is more suited for these. Microsoft's push for c++ is highly related its big push into the mobile space. Nobody will ask you to write your next web app in c++. But with Qt, the productivity argument cannot made against c++. But I think a lot of people are not familiar with Qt.</p>


问:
Is it a good idea to schedule regular time to clean up code?
I'm managing a small team of developers. Every so often we decide we're going to spend a day or two to clean up our code.

Would it be a good idea to schedule regular time, say 1 week every 2 months, to just cleaning up our codebase?

答:
I would say definitely yes, with a proviso: it should be done often, preferably on a weekly basis. I believe that a scheduled regular code review coupled with actually acting on the items coming out of the code review pays off very quickly. See the answer of p.s.w.g.

1 week every 2 months is definitely not often enough. This speaks to most of the other answers who responded with 'No' to your question. The gist of most of these answers is that if you wait too long you will no longer be in touch with the code and it usually takes much longer to fix/clean up/refactor.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: The complexity of the app is directly proportional to the complexity of the UI. By this reasoning, you should be able to build Google or Twitter over a weekend.</p>


问:
How is developing apps for Windows Phone 8 is different from Windows Phone 7.x?
What has changed with regards to the design patterns? Do both use the same development techniques? If I'm faced with the option of learning Windows Phone 7 vs Windows Phone 8 will learning windows phone 7 will qualify me for directly start development for windows phone 8?

答:
Yes, the development skills are definitely transferrable. The biggest difference is that the emulator now runs on top of Hyper-V and is as a result a lot faster. The tooling is still .NET & XAML based, however WP8 prefers the use of C# + XAML i.e. WinRT than Silverlight, with Silverlight 5 being the last planned version.

For a list of all new development changes, look at the Microsoft release notes at http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206940(v=vs.105).aspx

If you persevere with learning WP7 you will find it a lot easier to pick up WP8.


答:
I think that the currently two popular "No" "Yes" answers are two aspects of the same truth. Remember the OP is talking about a group he is managing, not just himself as an individual. We cannot assume that all developers in the group are well-disciplined enough to write clean, easily readable code; and there's the issue of external pressure and agile-style methodologies. Also, even with people's best efforts, their differences in style will mean they might write code which would be considered clean when apart, but unclean when considered together with other people's (not to mention the creaky interfaces).

On the other hand, the "fix it while working on it" is in my opinion an ideal to aspire for. You can make your code come out even more "fixed-up" by

careful peer CRing

writing unit tests together with the code itself

adopting coding guidelines

using automatic formatters and linters (but YMMV)

etc.

Now, if the OP's team adopts the above, and if he encourages his subordinates - e.g. during code reviews and during periodic code clean-up sessions - to try to anticipate pitfalls and avoid ugliness in advance, over time he/they will hopefully need less clean-up time. (And then they could devote that time to documentation, deeper refactoring, and knowledge sharing of what they've written and consolidated.)

Title: Is it a good idea to schedule regular time to clean up code?

Body:
I'm managing a small team of developers. Every so often we decide we're going to spend a day or two to clean up our code.

Would it be a good idea to schedule regular time, say 1 week every 2 months, to just cleaning up our codebase?


问:
How to prevent my executable being treated from AV like bad or virus?
I'm creating a piece of software, that will run on windows and will act like launcher for the game, to serve as an auto-updater and file verifier in client side PC.

One thing I don't understand, why my antivirus software (Avast) is considering my exe file as dangerous and won't start it without asking to put it into sandbox, for safe use.

Is there any rules that my software should obey, to be treated as good, or should I pay hundreds of dollars for some sort of digital signing and other stuff?

I'm using C# with MS Visual Studio 2010.

VirusTotal report. No DLL injections, working as remote file downloader, using WebClient() class.

It is not like it warns about virus, but it "suggests" to sandbox it. Look at screenshot:

答:
"File prevalence/reputation is low" means Avast uses a reputation system based on the usage of the program. Only if your program has been installed and 'marked as benevolent' by enough users will it develop a good reputation and will this suggestion go away. Avast calls this the FileRep cloud feature and says "All new unknown files are potentially dangerous. Whenever they have become widespread, there will not be a reason to AutoSandbox them anymore". This is a PITA for small software companies (and Avast is not the only one doing this, note e.g. Symantec's Suspicious Insight"). One thing Avast suggests is "you can accelerate the process if you digitally sign the files."

Locally (on your computer) you can go to autosandbox expert settings and disable autosandboxing files with a low reputation, or maybe use a self-signed certificate, but that won't help you with your end users.
For those I suggest you do use a real certificate (costs money, but Windows likes it too), and update your documentation with this info.

Maybe there's more suggestions at the Avast forums as well.


问:
Algorithm for matching similar content text items
I am working on a website (C#, ASP.Net MVC 3) which reads some RSS feeds from multiple sources and put feed title and summary in a database table(Sql Server).

What I want to do is:
Put an algorithm in place which can relate multiple feeds. For example if each feed is a news item, I would like to relate all news which says in different grammar of English "Some has won some election".

Is there any standard algorithm for such kind of content matching logic?
If not, what kind of custom algorithm should be used?

If this logic can be written on Database side(e.g. Stored Procedure) it will be better.

答:
On the Database side, the Postgresql database engine, since version 8.3, has the feature: Fuzzy String Match

It "provides several functions to determine similarities and distance between strings."


问:
How to label software requirements?
What is a good strategy to label software requirements in an SRS?

Typically outline numbering is employed on headers - but these will renumber if a new heading is inserted in the document. To me it seems like a good idea to aim for a more stable designation for each software requirement. This should make it easier to reference a particular requirement even in the face of an updated SRS.

What are your experiences on this?

答:
One strategy:

Consider the SRS ID as just a number, and don't imply any strong notion of consecutive order (The social security number is a reasonable example.)

Don't recycle numbers.  When an ID in a sequence is deleted, mark it "Deleted", "Deprecated", etc.  I prefer to keep the requirement text in the deleted item so that I have a running record of the requirement evolution.  If you choose to do this, mark the deleted text obviously, for example a strike-out font.

#2 implies that new requirement additions will never occur "in place"; rather, they are always appended to the document.

This strategy can become difficult to organize or cluster hierarchically as changes accumulate, so tag each SRS ID with a meaningful label for searching, i.e. [GUI], [DB], etc.

There are other strategies, such as using dotted decimals to cluster requirements, for example:

1.0 GUI

2.0 DB

3.0 Processing

As you might guess, the respective requirements should be ordered under the top-level number accordingly: 1.1, 1.2...for GUI, 2.1, 2.3, 2.4 for DB, etc. Note that this strategy will need some form of controlled method for managing deletions and additions.

The key thing to enforce in a requirements document: once an ID has been used for a requirement, it cannot be used again different requirement.  In other words, if SRS 1234 was used and then deleted, it cannot resurface later.  (Allowing it to do so wreaks absolute havoc on requirements traceability over the course of an evolving project.)

Note that virtually any SRS organization/structure will have deficiencies.  Pick the one that suits your development environment and your application needs. (For example, the strategies above work reasonably well in highly-controlled development environments, such as those monitored by the FDA or other governmental bodies.)

Finally, consider using a requirements management tool.  There are good ones out there (open source to $$$$$) that will take care of all of this for you.

Title: How to label software requirements?


问:
Unit Testing in a "no setter" world
I do not consider myself a DDD expert but, as a solution architect, do try to apply best practices whenever possible.  I know there is a lot of discussion around the pro's and con's of the no (public) setter "style" in DDD and I can see both sides of the argument.  My problem is that I work on a team with a wide diversity in skills, knowledge and experience meaning that I cannot trust that every developer will do things the "right" way.  For instance, if our domain objects are designed so that changes to the object's internal state is performed by a method but provide public property setters, someone will inevitable set the property instead of calling the method.  Use this example:

```<code>public class MyClass
{
    public Boolean IsPublished
    {
        get { return PublishDate != null; }
    }

    public DateTime? PublishDate { get; set; }

    public void Publish()
    {
        if (IsPublished)
            throw new InvalidOperationException("Already published.");

        PublishDate = DateTime.Today;

        Raise(new PublishedEvent());
    }
}
</code>```

My solution has been to make property setters private which is possible because the ORM we are using to hydrate the objects uses reflection so it is able to access private setters.  However, this presents a problem when trying to write unit tests.  For example, when I want to write a unit test that verifies the requirement that we can't re-publish, I need to indicate that the object has already been published.  I can certainly do this by calling Publish twice, but then my test is assuming that Publish is implemented correctly for the first call. That seems a little smelly.

Let's make the scenario a little more real-world with the following code:

```<code>public class Document
{
    public Document(String title)
    {
        if (String.IsNullOrWhiteSpace(title))
            throw new ArgumentException("title");

        Title = title;
    }

    public String ApprovedBy { get; private set; }
    public DateTime? ApprovedOn { get; private set; }
    public Boolean IsApproved { get; private set; }
    public Boolean IsPublished { get; private set; }
    public String PublishedBy { get; private set; }
    public DateTime? PublishedOn { get; private set; }
    public String Title { get; private set; }

    public void Approve(String by)
    {
        if (IsApproved)
            throw new InvalidOperationException("Already approved.");

        ApprovedBy = by;
        ApprovedOn = DateTime.Today;
        IsApproved = true;

        Raise(new ApprovedEvent(Title));
    }

    public void Publish(String by)
    {
        if (IsPublished)
            throw new InvalidOperationException("Already published.");

        if (!IsApproved)
            throw new InvalidOperationException("Cannot publish until approved.");

        PublishedBy = by;
        PublishedOn = DateTime.Today;
        IsPublished = true;

        Raise(new PublishedEvent(Title));
    }
}
</code>```

I want to write unit tests that verify:

I cannot publish unless the Document has been approved

I cannot re-publish a Document

When published, the PublishedBy and PublishedOn values are properly
set

When publised, the PublishedEvent is raised

Without access to the setters, I cannot put the object into the state needed to perform the tests.  Opening access to the setters defeats the purpose of preventing access.

How do(have) you solve(d) this problem?

答:
One strategy is that you inherit the class(in this case Document) and write tests against the inherited class. The inherited class allows some way to set the object state in tests.

In C# one strategy could be to make setters internal, then exposing internals to test project.

You could also use the class API like you described("I can certainly do this by calling Publish twice"). This would be setting object state using the public services of the object, it doesn't seem too smelly to me. In the case of your example, this would probably be the way I'd do it.

Title: Unit Testing in a "no setter" world


答:
You say

do try to apply best practices whenever possible

and

the ORM we are using to hydrate the objects uses reflection so it is
  able to access private setters

and I have to think that using reflection to bypass access controls on your classes is not what I'd describe as "best practice". Its going to be horribly slow too.

Personally, I would scrap your unit test framework and go with something in the class - it seems that you're writing tests from the viewpoint of testing the entire class anyway, which is good. In the past, for some tricky components that needed testing, I ave embedded the asserts and setup code into the class itself (it used to be a common design pattern to have a test() method in every class), so you create a client that simply instantiates an object and calls the test method which can set itself up as you like without nastiness like reflection hacks.

If you're concerned about code bloat, just wrap the testing methods in #ifdefs to make them only available in debug code (probably a best practice itself)

Title: Unit Testing in a "no setter" world

Body:
I do not consider myself a DDD expert but, as a solution architect, do try to apply best practices whenever possible.  I know there is a lot of discussion around the pro's and con's of the no (public) setter "style" in DDD and I can see both sides of the argument.  My problem is that I work on a team with a wide diversity in skills, knowledge and experience meaning that I cannot trust that every developer will do things the "right" way.  For instance, if our domain objects are designed so that changes to the object's internal state is performed by a method but provide public property setters, someone will inevitable set the property instead of calling the method.  Use this example:

```<code>public class MyClass
{
    public Boolean IsPublished
    {
        get { return PublishDate != null; }
    }

    public DateTime? PublishDate { get; set; }

    public void Publish()
    {
        if (IsPublished)
            throw new InvalidOperationException("Already published.");

        PublishDate = DateTime.Today;

        Raise(new PublishedEvent());
    }
}
</code>```

My solution has been to make property setters private which is possible because the ORM we are using to hydrate the objects uses reflection so it is able to access private setters.  However, this presents a problem when trying to write unit tests.  For example, when I want to write a unit test that verifies the requirement that we can't re-publish, I need to indicate that the object has already been published.  I can certainly do this by calling Publish twice, but then my test is assuming that Publish is implemented correctly for the first call. That seems a little smelly.

Let's make the scenario a little more real-world with the following code:

```<code>public class Document
{
    public Document(String title)
    {
        if (String.IsNullOrWhiteSpace(title))
            throw new ArgumentException("title");

        Title = title;
    }

    public String ApprovedBy { get; private set; }
    public DateTime? ApprovedOn { get; private set; }
    public Boolean IsApproved { get; private set; }
    public Boolean IsPublished { get; private set; }
    public String PublishedBy { get; private set; }
    public DateTime? PublishedOn { get; private set; }
    public String Title { get; private set; }

    public void Approve(String by)
    {
        if (IsApproved)
            throw new InvalidOperationException("Already approved.");

        ApprovedBy = by;
        ApprovedOn = DateTime.Today;
        IsApproved = true;

        Raise(new ApprovedEvent(Title));
    }

    public void Publish(String by)
    {
        if (IsPublished)
            throw new InvalidOperationException("Already published.");

        if (!IsApproved)
            throw new InvalidOperationException("Cannot publish until approved.");

        PublishedBy = by;
        PublishedOn = DateTime.Today;
        IsPublished = true;

        Raise(new PublishedEvent(Title));
    }
}
</code>```

I want to write unit tests that verify:

I cannot publish unless the Document has been approved

I cannot re-publish a Document

When published, the PublishedBy and PublishedOn values are properly
set

When publised, the PublishedEvent is raised

Without access to the setters, I cannot put the object into the state needed to perform the tests.  Opening access to the setters defeats the purpose of preventing access.

How do(have) you solve(d) this problem?


答:
Yet another approach is to create a constructor of the class that allows the internal properties to be set on instantiation:</p>

```<code> public Document(
  String approvedBy,
  DateTime? approvedOn,
  Boolean isApproved,
  Boolean isPublished,
  String publishedBy,
  DateTime? publishedOn,
  String title)
{
  ApprovedBy = approvedBy;
  ApprovedOn = approvedOn;
  IsApproved = isApproved;
  IsApproved = isApproved;
  PublishedBy = publishedBy;
  PublishedOn = publishedOn;
}
</code>```

Title: Unit Testing in a "no setter" world

Body:
Yet another approach is to create a constructor of the class that allows the internal properties to be set on instantiation:

 public Document(
  String approvedBy,
  DateTime? approvedOn,
  Boolean isApproved,
  Boolean isPublished,
  String publishedBy,
  DateTime? publishedOn,
  String title)
{
  ApprovedBy = approvedBy;
  ApprovedOn = approvedOn;
  IsApproved = isApproved;
  IsApproved = isApproved;
  PublishedBy = publishedBy;
  PublishedOn = publishedOn;
}


问:
Have they missunderstood currying or have I?
This question is similar to the question posted on Does groovy call partial application 'currying'?, but not completely the same, and the answers given there do not really satisfy me.

I would like to state right at this point, before I go any further, that currying is one of the concepts that have been hard to fully understand. I think the reason for that is the fact that there seem to be two general definitions of currying, and they don't really mean the same thing both in theory and in application.

That being said, I think currying is a very simple concept once you decide to take only one of the two definitions and stick to it. In fact, currying should not be difficult to understand at all, but in my experience, understanding currying has been the equivalent of showing a little boy an apple and telling him that fruit is called apple, and then you go on calling that fruit an orange. The boy will never understand the simple concept of an apple because you have caused an enormous amount of confusion by calling the apple an orange.

The definition of currying that I've accepted as the right one is that currying is taking a function of an arbitrary arity and turning it into multiple chainable functions each of which accepts only one parameter (unary functions). In code, it would look like this:

```<code>f(1,2,3);
//becomes
f(1)(2)(3);
</code>```

However, some people, including well known programmers like John Resig, explain currying as something completely different. For them, currying is no more than simple partial application. There is even a generally accepted javascript function for currying:

```<code>Function.prototype.curry = function() {
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function() {
      return fn.apply(this, args.concat(
        Array.prototype.slice.call(arguments)));
    };
  };
</code>```

This functions does not really curry anything, but rather partially applies the supplied arguments. The reason why I don't think this function curries anything is because you can end up with a function that accepts more than one argument:

```<code>var f2 = f.curry(1); //f accepts 3 arguments f(1,2,3);
f2(2,3); // calling the resulting "curried" function.
</code>```

So, my question is, have I misunderstood currying or have they?

I will leave you with this post that explains currying in javascript, but in a way in which I don't really see any currying: https://javascriptweblog.wordpress.com/2010/04/05/curry-cooking-up-tastier-functions/

答:
I feel that Jon Resig's curry function is misnamed, and is actually a form of partial application.

Wikipedia actually has a well written section contrasting currying with partial application:

Currying and partial function application are often conflated.[10] The difference between the two is clearest for functions taking more than two arguments.

Given a function of type f:(X × Y × Z)→N, currying produces curry(f): X→(Y→(Z→N))). That is, while an evaluation of the first function might be represented as f(1, 2, 3), evaluation of the curried function would be represented as fcurried(1)(2)(3), applying each argument in turn to a single-argument function returned by the previous invocation. Note that after calling fcurried(1), we are left with a function that takes a single argument and returns another function, not a function that takes two arguments.

I'm going to break here because that last line is really important. Jon Resig's version of curry produces a function that takes two arguments, which means that it is not actually a currying function.

In contrast, partial function application refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given the definition of above, we might fix (or 'bind') the first argument, producing a function of type partial(f): (Y×Z)→N. Evaluation of this function might be represented as fpartial(2,3). Note that the result of partial function application in this case is a function that takes two arguments.

Intuitively, partial function application says "if you fix the first arguments of the function, you get a function of the remaining arguments". For example, if function div stands for the division operation x/y, then div with the parameter x fixed at 1 (i.e., div 1) is another function: the same as the function inv that returns the multiplicative inverse of its argument, defined by inv(y) = 1/y.

The practical motivation for partial application is that very often the functions obtained by supplying some but not all of the arguments to a function are useful; for example, many languages have a function or operator similar to plus_one. Partial application makes it easy to define these functions, for example by creating a function that represents the addition operator with 1 bound as its first argument.


问:
Task Scheduler shared hosting
I am using a shared host that which doesn't support CRON/TaskScheduler (it is a windows Godaddy server).

I need to search on email server for new emails on each 1 hour, I have the script on PHP.

Can I use PERL to emulate a task on certain times, or is there any other alternatives?

答: Perhaps a little "outside the box", but you could expose your code as a channel If This Then That (https://ifttt.com/) understands (for instance, an RSS feed), and then create a recipe that starts on a timer, and reads your "feed", kicking off your code?</p>

Title: Task Scheduler shared hosting


答:
I think scheduling regular time is very good whether that is a task in a regular waterfall style project, or stories in an agile one.  Having a set time may not be as valuable as just working it into your schedule.  This allows you to get it done as part of the schedule vs. canceling cleanup day because you are behind on the project.

Having managed a project that had a tremendous amount of code debt, working these in on a regular basis was key to getting things working smooth.  Some of our things were big, some were small.

After a few months of this kind of work our operations team lead told me how smooth everything was running.

Each item may not seem like a lot, but just like all debt, it ads up.


问:
Does Silverlight5 provide anything new for WCF
From WCF standpoint, just wondering whether I can leverage anything after upgrade from Silverlight 4 to Silverlight 5? I did some research regarding new features of SL5 and cannot find anything about changes to System.ServiceModel and System.ServiceModel.Web namespaces, is it rigth that nothing were added or am I missing something?

My Questions:

Have there been any changes to WCF in Silverlight 5?

If yes, has there been any changes to duplex polling on HTTP?

答:
Tomasz Janczuk wrote a great series of articles on the HTTP Polling Duplex protocol. Specifically, you might want to look at this one which discusses scalability directly.

The gist of it is that in order to provide scalability, you have to support the Duplex Service with a backend bus architecture. The services would be responsible just for shuttling messages from the client to the backend. The backend would be responsible for identifying where outgoing messages should be routed and how to process inbound messages.


问:
Microsoft's coding standards for ASP.NET controls
I cannot find any naming standards/conventions in MSDN for naming ASP.NET controls.

One of the following standards tends to be used by programmers:

lblAddress

AddressLabel

Address

According to MSDN's Name of Type Members, should we be treating ASP.NET controls as fields, hence using Pascal Case (e.g. AddressLabel)?

答: I'm for your second entry, AddressLabel. For a couple reasons. One, I believe that the Hungarian Notation first one is out of favor in a big way. Next, I believe that a lot of times labels precede input fields or another chunk of text, so there could be several "Address" controls and they'll need to be disambiguated in some form. Hence, AddressLabel.


答:
It's the second version, AddressLabel.  However,

If it's just a label, and you never refer to it in code, you can go with the default label1, label2, or whatever the IDE automatically assigns.

I prefer uxAddressLabel and uxAddressTextBox.  This causes intellisense to group all the controls together, and makes them much easier to refer to.  This is my only remaining use for Hungarian notation.

Title: Microsoft's coding standards for ASP.NET controls

Body:
I cannot find any naming standards/conventions in MSDN for naming ASP.NET controls.

One of the following standards tends to be used by programmers:

lblAddress

AddressLabel

Address

According to MSDN's Name of Type Members, should we be treating ASP.NET controls as fields, hence using Pascal Case (e.g. AddressLabel)?


答:
I cannot put the object into the state needed to perform the tests.

If you cannot put the object into the state needed to perform a test, then you cannot put the object into the state in production code, so there's no need to test that state. Obviously, this isn't true in your case, you can put your object into the needed state, just call Approve.

I cannot publish unless the Document has been approved: write a test that calling publish before calling approve causes the right error without changing the object state.

```<code>void testPublishBeforeApprove() {
    doc = new Document("Doc");
    AssertRaises(doc.publish, ..., NotApprovedException);
}
</code>```

I cannot re-publish a Document: write a test that approves an object, then calling publish once succeed, but second time causes the right error without changing the object state.

```<code>void testRePublish() {
    doc = new Document("Doc");
    doc.approve();
    doc.publish();
    AssertRaises(doc.publish, ..., RepublishException);
}
</code>```

When published, the PublishedBy and PublishedOn values are properly set: write a test that calls approve then call publish, assert that the object state changes correctly

```<code>void testPublish() {
    doc = new Document("Doc");
    doc.approve();
    doc.publish();
    Assert(doc.PublishedBy, ...);
    ...
}
</code>```

When publised, the PublishedEvent is raised: hook to the event system and set a flag to make sure it's called

You also need to write test for approve.

In other word, don't test the relation between internal fields and IsPublished and IsApproved, your test would be quite fragile if you do that since changing your field would mean changing your tests code, so the test would be quite pointless. Instead you should test the relationship between calls of public methods, this way, even if you modify the fields you wouldn't need to modify the test.

Title: Unit Testing in a "no setter" world

Body:
I cannot put the object into the state needed to perform the tests.

If you cannot put the object into the state needed to perform a test, then you cannot put the object into the state in production code, so there's no need to test that state. Obviously, this isn't true in your case, you can put your object into the needed state, just call Approve.

I cannot publish unless the Document has been approved: write a test that calling publish before calling approve causes the right error without changing the object state.

void testPublishBeforeApprove() {
    doc = new Document("Doc");
    AssertRaises(doc.publish, ..., NotApprovedException);
}

I cannot re-publish a Document: write a test that approves an object, then calling publish once succeed, but second time causes the right error without changing the object state.

void testRePublish() {
    doc = new Document("Doc");
    doc.approve();
    doc.publish();
    AssertRaises(doc.publish, ..., RepublishException);
}

When published, the PublishedBy and PublishedOn values are properly set: write a test that calls approve then call publish, assert that the object state changes correctly

void testPublish() {
    doc = new Document("Doc");
    doc.approve();
    doc.publish();
    Assert(doc.PublishedBy, ...);
    ...
}

When publised, the PublishedEvent is raised: hook to the event system and set a flag to make sure it's called

You also need to write test for approve.

In other word, don't test the relation between internal fields and IsPublished and IsApproved, your test would be quite fragile if you do that since changing your field would mean changing your tests code, so the test would be quite pointless. Instead you should test the relationship between calls of public methods, this way, even if you modify the fields you wouldn't need to modify the test.


问:
Are there any reasons not to accept a software deliverable as a virtual machine?
This is a question about logistics, not a technical question.

My company has outsourced some embedded software work.  Specifically, we have payed a contractor to develop an embedded system for us since we do not have adequate in-house knowledge to do it ourselves (we only have desktop application developers).

So, the contractors have finished the software and they have asked if they may deliver it to us in a virtual machine.  The VM is a Windows 8 machine containing the pre-configured CodeWarrior IDE with the source code as a CodeWarrior project.  The idea is that this will allow us to make code changes within the VM that is already configured for further development of this project.

Are there any drawbacks to doing this as opposed to having them walk us through how to configure our own development machines to make code changes to the project?  The only problem I can foresee is the VM running slowly and it taking a long time to rebuild the project when we make code changes.  But on the other hand, I like the idea of getting a pre-configured embedded system development environment so I don't have to add yet another IDE on my desktop application dev machine.

I can't really think of a good reason why not to accept a VM deliverable, but I just wanted to run it by this community in case there's something I'm missing.

答: The problem I see is that the knowledge of setting up and configuring the virtual machine is not in-house, and if configuration is non-trivial then you'll be relying on the other company when the software needs to be configured for different versions of the OS/libraries/hardware/whatever. Accepting the VM is fine to get up and running faster, but I'd insist on getting walk-through on how to configure your own system for future maintenance.</p>


答:
The ideal answer is No, because you take the steps necessary to avoid making this a necessity (clean up as you go along for several reasons already stated).

This may be the goal in the end, but you may have a team that is far from putting this into practice.

Managers have to take some responsibility It's not always the developer's fault. Managers can say one thing, but they start pushing for projects to get finished and make suggestions that promote bad practices. They may literally say,  "we'll clean it up later" or if it works, that's good enough.

You may have to start with dedicating a particular time to show this is important. Once you know your team is capable of cleaning up their code (not a given), then you can try to incorporate it more frequently.

Eventually, you shouldn't have to set a time.

Personnally, I struggle with solving a new problem and getting it to work while trying to keep things tidy. I am getting better at it, but often take a deliberate break and clean things up. It's a different mind-set for me. Eventually, the solid practices become habit.


答:
In a few of my projects, I've had to fight hard to get software delivered this way.  It's an excellent format.

Make sure you:

Get the source code of each release you get from the contractor, and merge it into your own source control system

Get documentation on the VM's environment setup, and can reproduce it in-house.  Add the documentation to your source control as well

Additional benefits:

If you archive the releases in VM format (save the .vhd or something) it is much easier to get them up and running several years down the line, even if the original team is fragmented or gone.

It is much easier to run different versions side by side.

With some VMWare integration (it might be possible with HyperV too), you can integrate these into a CI build automatically.

It saves developer time (at the beginning), because there's little to no environment setup.

I'd say go for it.

Title: Are there any reasons not to accept a software deliverable as a virtual machine?

Body:
This is a question about logistics, not a technical question.

My company has outsourced some embedded software work.  Specifically, we have payed a contractor to develop an embedded system for us since we do not have adequate in-house knowledge to do it ourselves (we only have desktop application developers).

So, the contractors have finished the software and they have asked if they may deliver it to us in a virtual machine.  The VM is a Windows 8 machine containing the pre-configured CodeWarrior IDE with the source code as a CodeWarrior project.  The idea is that this will allow us to make code changes within the VM that is already configured for further development of this project.

Are there any drawbacks to doing this as opposed to having them walk us through how to configure our own development machines to make code changes to the project?  The only problem I can foresee is the VM running slowly and it taking a long time to rebuild the project when we make code changes.  But on the other hand, I like the idea of getting a pre-configured embedded system development environment so I don't have to add yet another IDE on my desktop application dev machine.

I can't really think of a good reason why not to accept a VM deliverable, but I just wanted to run it by this community in case there's something I'm missing.


答:
No, you should do this while you are coding. This is called refactoring if you are using TDD. The problem when you wait a month or two to fix and clean your code is that you may alter the code behavior because you don't remember every piece of your code.

I suggest refactoring which is based on coding first the necessary code to make something work, and as soon as it works redesign it, optimize it, and make it pretty.


问:
Machine Learning with sample data set
I have a question regarding Machine Learning in general. Consider the following scenario:

Given a piece of text, we want a program to know whether the text is 'abusive' or not.

To do this we can give the program 1000 text samples and manually mark which ones are positive and which ones are negative. The program studies these and records which words/patterns are common in abusive texts. We then give it another 1000 un-marked texts, and it manages to identify 95% of these correctly using the patterns it learnt from the original 1000.

That's all good, but what about after that once the software 'goes live'? That is, we leave it to pull another 1000 texts every day and it's left to determine whether they are abusive or not on it's own. One might think it would be a good idea to continue to  recognise words/patterns in an attempt to 'learn' more and more each day? But the problem here is we don't know for sure whether the program is identifying each text correctly. So if it marks a clean text as abusive, it will falsely record words/patterns as abusive. This will then cause the program's intelligence to become more and more incorrect and off-track.

What is the general approach to the above problem?

答:
Usually, such filters are programmed to output not only a yes/no value for each sample, but rather a probability: a sample may, for example, be reported as 95% likely to be abusive. Then you set two thresholds, to divide your results in three groups: very unlikely to be abusive, very likely to be abusive, and uncertain.

For example, you might consider probabilities between 20% and 80% uncertain, and those might contain, say, 10% of your samples. You take those samples, have someone classify them manually, and feed the results back to the system as training data (this is exactly what the typical Bayesian e-mail spam filters do when you manually mark something as spam or ham).

Over time, this will increase the accuracy of the predictions, so the number of samples in the "uncertain" category will decrease. If you like, you can now make the thresholds stricter, say, 5% and 95%.

Title: Machine Learning with sample data set


答: Environment running slowly should not be an issue, just throw memory and CPU at it. Overhead of modern VM for desktop type work like most SW development is very small, it is saved many times over by not needing to do any setup when changing hardware.</p>


答:
I don't see a massive draw-back with it, but I would say that accepting a VM with the source code on it should entail the same paranoia as accepting a shipment of a machine with the software and dev environment installed, so please make sure there's nothing bad installed on the VM before you spin it up in an environment that has access to your internal network.

If/when you have the VM up and running, you should be able to fold the source code into your normal code repositories, as you (probably) would've done with just a source code archive delivered.


答:
I would be worried that there is something configured in the machine that is undocumented, difficult to reproduce, or not acceptable in your standard configuration.

Ymmv, but I don't really consider the development done until the project can be demonstrated to build off the standard dev machines and deployed on the commodity servers/clients.


问:
Few big libraries or many small libraries?
Over the course of some months I've created a little framework for game development that I currently include in all of my projects.

The framework depends on SFML, LUA, JSONcpp, and other libraries. It deals with audio, graphics, networking, threading; it has some useful file system utilities and LUA wrapping capabilities. Also, it has many useful "random" utility methods, such as string parsing helpers and math utils.

Most of my projects use all of these features, but not all of them:

I have an automatic updater that only makes use of the file system and networking features

I have a game with no networking capabilities

I have a project that doesn't need JSONcpp

I have a project that only needs those string/math utils

This means that I have to include the SFML/LUA/JSON shared libraries in every project, even if they aren't used. The projects (uncompressed) have a minimum of 10MB in size this way, most of which is unused.

The alternative would be splitting the framework in many smaller libraries, which I think would be much more effective and elegant, but would also have the cost of having to maintain more DLL files and projects.

I would have to split my framework in a lot of smaller libraries:

Graphics

Threading

Networking

File system

Smaller utils

JSONcpp utils

LUA utils

Is this the best solution?

答:
I'd personally go for many small libraries.

Discourages developers from creating dependencies between otherwise unrelated packages.

Smaller more manageable libraries that are much more focused.

Easier to break up and have separate teams manage each library.

Once you have a new requirement that's sufficiently complex, its better to add a new module
rather than find an existing library to shove the new code in. Small libraries encourage
this pattern.


答:
You've given one side of the trade-off, but not the other one. Without a "fair and balanced" of the pressures you're operating under, we can't possibly tell you.

You say that splitting the libraries will make all your projects smaller. That's a clear plus. I can imagine various minuses:

splitting the libraries is in itself an effort, even if it has to be done only once.

maintaining versions of many libraries consistently is a small but persistent additional effort.

it is not as easy to be sure that every project does in fact really bundle the things it needs

splitting may not be possible as cleanly as you believe at the moment, and introduce extra work, maybe even threaten the conceptual integrity of some modules.

Depending on how probable/important such counterarguments are for you, splitting may or may not be the right choice for you. (Note that the dichotomy between "splitters" and "lumpers" is considered by many to be a fundamental personality trait that is not susceptible to logic in the first place!)

That said, the different tasks you say your modules are doing are so far removed from each other that I'd consider at least some splitting probably called for.

Title: Few big libraries or many small libraries?

Body:
Over the course of some months I've created a little framework for game development that I currently include in all of my projects.

The framework depends on SFML, LUA, JSONcpp, and other libraries. It deals with audio, graphics, networking, threading; it has some useful file system utilities and LUA wrapping capabilities. Also, it has many useful "random" utility methods, such as string parsing helpers and math utils.

Most of my projects use all of these features, but not all of them:

I have an automatic updater that only makes use of the file system and networking features

I have a game with no networking capabilities

I have a project that doesn't need JSONcpp

I have a project that only needs those string/math utils

This means that I have to include the SFML/LUA/JSON shared libraries in every project, even if they aren't used. The projects (uncompressed) have a minimum of 10MB in size this way, most of which is unused.

The alternative would be splitting the framework in many smaller libraries, which I think would be much more effective and elegant, but would also have the cost of having to maintain more DLL files and projects.

I would have to split my framework in a lot of smaller libraries:

Graphics

Threading

Networking

File system

Smaller utils

JSONcpp utils

LUA utils

Is this the best solution?


问:
What changes are too big to be made easy by proper design?
This is a rather vague question, but it's something I've never felt has been answered in a satisfactory way when reading about proper design.

Generally, when learning about Object Oriented programming, abstraction, factoring out, etc, the holy grail of design - and the reason they always claim you're using the development techniques in question - is that it will make your program "easy to change", "maintainable", "flexible", or any of the synonyms used to express such a productive-sounding concept.  By marking ivars private, splitting code up into many small, self-contained methods, keeping interfaces general, you supposedly gain the ability to modify your program with total ease and grace.

For relatively small changes, this has worked well for me.  Changes to internal data structures used by a class to increase performance has never been a major difficulty, and neither have changes to the user-interface end, independent of the API, such as redesigning a text entry system or overhauling the graphics for a gameplay element.

All of these changes seem inherently self-contained.  None of them involve any changes to the behavior or design of the component of your program being modified, as far as outside code it concerned.  Whether or not you're writing procedurally or in an OO style, with large functions or small, these are easy changes to make even if you have only a moderately good design.

However, whenever the changes become big and hairy - that is, changes to the API - none of my precious "patterns" ever come to the rescue.  The big change remains big, the affected code remains affected, and many hours of bug-spawning work lie ahead of me.

So, my question is this.  How big a change does proper design claim to be able to facilitate?  Is there some further design technique, either unknown to me or that I have failed to implement, that truly does make sticky-sounding modification simple, or is that promise (which I have heard made by so many different paradigms) merely a nice idea, completely disconnected from the immutable truths of software development?  Is there a "change tool" I can add to my toolbelt?

Specifically, the problem I am facing that's led me to the forums is this:  I've been working on implementing an interpreted programming language (implemented in D, but that's not relevant), and I've decided that my closures' arguments should be keyword-based, rather than positional as they currently are.  This requires modifying all existing code that calls anonymous functions, which, luckily, is rather small because I am early on in the development of my language (< 2000 lines), but would be enormous if I had made this decision at a later stage.  In such a situation, is there any way that by proper foresight in design I could have made this modification easier, or are certain (most) changes intrinsically far-reaching?  I'm curious if this is in any way a failure of my own design skills - if it is, I'd be very eager to improve them with the necessary reading material if there is a way to ameliorate the severity of the problem.

To be clear, I am in no way skeptical of OOP or any of the other patterns commonly in use. For me, however, their virtues are in the original writing, rather than the maintaining, of code bases.  Inheritance allows you to abstract repetitive patterns out well, polymorphism allows you to separate code by human-understood function (which class) rather than by machine-understood effect (which branch of the switch statement), and small, self-contained functions allow you to write in a very pleasant "bottom-up" style.  However, I'm skeptical of their claims of flexibility.

答:
Sometimes a change is large enough that you have to design a migration path.  Even if the start and end points are well designed, you often can't just switch cold turkey.  A lot of otherwise good designers fail to design good migration paths.

This is why I think every programmer should do a stint writing software for 24/7 production environments.  There's something about losses being quoted on the order of your annual salary per minute that motivates you to learn to write robust migration code.

What people naturally do for a large change is rip out the old way, put in the new way, then spend a couple days fixing a bazillion compile errors, until your code is finally compiling again so you can start testing.  Since the code was untestable for two days, you suddenly have a huge mess of entangled bugs to sort out.

For a large design change like changing from positional arguments to keyword, a good migration path would be to first add support for keyword arguments without removing positional support.  Then you methodically change the calling code to use keyword arguments.  This is similar to how you went about it before, except this time you can test as you go along, because the unchanged calling code still works.  Because your changes are smaller between tests, the bugs are easier to fix earlier on.  Then when all the calling code has been changed, it's trivial to remove the positional support.

This is why publicly published APIs deprecate the old methods instead of removing them cold turkey.  It provides a seamless migration path for calling code.  It might feel like more work to support both for a while, but you make up the time in testing.

So to answer your question as originally phrased, there are almost no changes that are too big to be made easier by proper design.  If your change seems too big, you just need to design some temporary intermediate stages for your code to migrate through.


答: There isn't a clear cut answer. The best driving factor I can think of is how interrelated are the libraries now, and do you expect them to become related later. If you have a complex web of dependencies then one big library will probably be easier, if you have minimal relationships then you can split them up cleanly.</p>


答:
As FrustratedWithFormsDesigner said, you need to know how to set up the machine for yourself. However I would like to add that you could potentially ask them to provide a script that configures the machine for you, rather than an entire VM. If the script is written well enough, you'll have exact up-to-date documentation of how to set up the machine (by reading source code), plus the script will do it for you, saving you time every time you need a new machine.

A tool I'm experimenting with to help standardize/automate setting up a new Windows machine is Chocolatey.

Chocolatey NuGet is a Machine Package Manager, somewhat like apt-get, but built with Windows in mind.

You can potentially build your own Chocolatey packages pretty easily, then create a PowerShell script that will install and configure practically everything.


答:
That's really the sort of thing that should have been worked out in the original contract.  They may already be going above and beyond.  I wouldn't expect to get configuration instructions without paying extra, because it requires more work on their part.

I've been in a similar situation as yours before.  Our development environment is Windows/Cygwin and we had a vendor visit for a week to cowrite some interface code with us.  They primarily use Linux, so we set ourselves up with Linux virtual machines for the week they were here.  It worked out quite well while they were here and we had little trouble porting over to Cygwin after they left.

It sounds to me like you're underestimating your own abilities.  Setting up an IDE is not that hard, even without a working example to compare it to.  I would be more concerned about violating Windows and CodeWarrior licensing agreements.  If you're properly licensed, you should be able to get support from Freescale for any setup issues.


问:
How to interview someone you know well?
How would you interview someone you know well or someone you may even be friends with? What if you already know their strengths and weaknesses. I would prefer to avoid this situation by delegating this task to somebody else, but what if this is not an option. I feel like there is just too much personal feelings involved and it is almost impossible to be unbiased. If you have been in an similar situations, how did you handle them? </p>

答:
Your behavior will be affected. And your judgment too.

I highly suggest you to delegate the task to someone else and then discuss with him privately.

Title: How to interview someone you know well?


问:
Programming style in Perl
I work in Java so basically I use OOP paradigm during coding.
I am about to start working in Perl and I was wondering what is the paradigm that Perl developers follow.
In wiki it mentions that it supports many paradigms but I am not sure I understand this since it is a scripting language.

So my question is:
Are the object oriented patterns I'm familiar with in Java idiomatic in Perl, or will I need significant change to my design style to write effective Perl?

Note: This is not a question to critique Perl. I actually have to work in Perl and would like to understand how the current way I program will change.

答:
Perl's stance on paradigms is TMTOWTDI (there's more than one way to do it).  This is one of the reasons a lot of people jokingly call Perl a write-only language.  It can be a lot easier to write it than read it, because another person's style may be completely different to yours.

That being said, OOP is certainly supported in Perl.  If you're using a lot of third party code, it may or may not be OOP, but for your own code you can do OOP to your heart's content.  I actually first learned OOP in Perl.  I tried C++ first and it didn't "click" for some reason.

Title: Programming style in Perl


问:
What are the reasons for rebuild and redeployment libraries?
It's difficult to understand the meaning of the question from the topic's name.

Here is what I mean.

I'm watching Uncle Bob's Clean Code Episodes. In many episodes where he is talking about SOLID principles he mentions the problem of rebuild and redeployment caused by code changing. He says that bad architecture causes frequent rebuilds and redeployments.

But I have a couple of questions:

Why frequent rebuilds and redeployments is bad?

Can you enumerate causes of rebuilds and redeployments of dll's?

Is there any difference between different languages according to the
second question?

What causes rebuild and redeployment of dll's in C#?

The second question (and the most common) is based on dll's coupling. What should I change in one of two coupled dll's so then I have to rebuild and redeploy the other?

答:
Because it's extra work, and a source of potential errors.  If you don't have to deploy, there is no possibility of error in the deployment process.  Deployment can be expensive if you have to take down one or more servers to do it.

Anything that changes a DLL will cause a rebuild and redeploy.  Specifically, if you make a change to the DLL's code, you will need to rebuild and redeploy it (assuming the change is a significant and desirable one).

Some languages like Erlang have "hot deploy" capabilities, which means that you don't have to take down the server or device to deploy changes.  This is useful for things like phone switches and traffic lights which must be running 24x7.

See 2.

Bad architecture, from Uncle Bob's point of view, means that the code is too tightly coupled.  Code that is too tightly coupled causes increased rebuilds and deployments, because your code has too many dependencies on other code in other DLL's.  Consequently, making changes to one DLL often cascades into changes required in other DLL's.


问:
A class with extra field
Let's say I have an animal class...with fields of name, height and weight.
I want to create a bird class which is an animal, but it has also, say, wing size.
How can I do that?

My general idea is creating the animal class, and the bird class which inherits animal, and has additional field ...but then different kinds of birds would inherit that class.

My Questions:

Is my solution an appropriate OO approach to this type of problem?

Is there a known design pattern for handling data modeling problems of this type?

答:
You would only add members to your Bird class that are common to all birds.  If you want to add a member called Fly(), you must either create a FlyingBird class that inherits from Bird, or inherit from an IFlying interface and implement the Fly() method on it.

```<code>public class Bird : Animal
{
    public float WingSize;
    ...
}

public Interface IFlyable
{
    void Fly()
    void Land();
}

public class FlyingBird : Animal, IFlyable
{
    public void Fly()
    {
         // Flap wings
    }
}
</code>```

Title: A class with extra field

Body:
You would only add members to your Bird class that are common to all birds.  If you want to add a member called Fly(), you must either create a FlyingBird class that inherits from Bird, or inherit from an IFlying interface and implement the Fly() method on it.

public class Bird : Animal
{
    public float WingSize;
    ...
}

public Interface IFlyable
{
    void Fly()
    void Land();
}

public class FlyingBird : Animal, IFlyable
{
    public void Fly()
    {
         // Flap wings
    }
}


问:
Should classes, enums and other entities be placed in separate files?
My company's team lead\architect argues that a large-scale project is easier to understand if "entities connected by logic" are placed in one .cs file.

I quote:

"The whole structure of the logic and the interface and the class can be seen in one place, this is an argument which can't be refute. To see the same thing but with a bunch of files you need to use the tools, class diagram, R# for navigation, etc."

"Following the poor theory I might scream that an army of separated files is cool, but when it comes to making changes to the existing code, especially if you were not a writer of this code, it's very difficult to understand plenty of scattered files. So on forums, you can write that "one enum- one file", but in practice this approach should never be used "

"... As to the separation of code base between developers, nowadays it's not a problem edit simultaneously the same file. The merge is not a problem."

I heard and read many times that we have to create one .cs file per enum, class and so on and this is the best practice.

But I can't convince him. He says that he don't trust to any well-known programmers such as Jon Skeet. By the way here is Skeet's opinion on this topic: Where is the best place to locate enum types?

What do you think? Is there a real problem? Or is it a matter of taste and should be regulated by the coding standard of the organization?

答:
There are a couple of flaws in your Team Lead's argument:

Well-designed classes and enums are intended to be used anywhere in your project, not just where they may make sense logically.

Classes and enums that are properly documented with XML comments are very self-describing, by merely hovering over the item referencing it.

You can always get to a class or enum definition by right-clicking the reference and selecting "Go to Definition," so it really shouldn't matter where you put it.

Putting objects together in a "logical" fashion is arbitrary (i.e. you have to think about what "logical" means.  I'd rather expend those clock cycles doing actual programming).

Setting up each object definition in its own file creates a uniform, disciplined expectation of organization and structure, and doesn't raise questions like "why is this here?"  That's a very nice thing to have.

If two or more objects are logically related, simply put them in their own folder in the Project Explorer.


答:
Yes, you add such a field to a derived class, just like you described. All birds have wings.

It is useful to contemplate how you will use this property.  People new to OO, and especially oldsters who programmed way before the early OO days, may want to write code like (not in any particular language):

```<code>for all Animals a in someListOfAnimals:
   print a.name, " has weight of ", a.weight
   if a is a Bird,
       print " and a wingspan of ", a.wingsize
</code>```

but that is seriously wrong in OO design.  You must always try to think at the right level of abstraction.  The right way will be something more like

```<code>for all Animals a in someListOfAnimals:
   print a.descripion()
</code>```

and define a virtual "description()" method for Animal and for Bird.   The Bird.description() method will, of course, print out the wingsize along with the usual stuff.  Animal.description() doesn't mention wingsize.

In case someday you run across some odd species of bird without wings, no need to make a tangled hierarchy of classes.  The real world is full of exceptions.  Just set wing size to zero, or some bogus value, or add a boolean  haswings member.

Title: A class with extra field

Body:
Let's say I have an animal class...with fields of name, height and weight.
I want to create a bird class which is an animal, but it has also, say, wing size.
How can I do that?

My general idea is creating the animal class, and the bird class which inherits animal, and has additional field ...but then different kinds of birds would inherit that class.

My Questions:

Is my solution an appropriate OO approach to this type of problem?

Is there a known design pattern for handling data modeling problems of this type?

Body:
Yes, you add such a field to a derived class, just like you described. All birds have wings.

It is useful to contemplate how you will use this property.  People new to OO, and especially oldsters who programmed way before the early OO days, may want to write code like (not in any particular language):

for all Animals a in someListOfAnimals:
   print a.name, " has weight of ", a.weight
   if a is a Bird,
       print " and a wingspan of ", a.wingsize

but that is seriously wrong in OO design.  You must always try to think at the right level of abstraction.  The right way will be something more like

for all Animals a in someListOfAnimals:
   print a.descripion()

and define a virtual "description()" method for Animal and for Bird.   The Bird.description() method will, of course, print out the wingsize along with the usual stuff.  Animal.description() doesn't mention wingsize.

In case someday you run across some odd species of bird without wings, no need to make a tangled hierarchy of classes.  The real world is full of exceptions.  Just set wing size to zero, or some bogus value, or add a boolean  haswings member.


答:
Perl's philosophy tends to be that of "do what is practical now."  If you need to use OOP, its there.  It isn't necessary in all solutions and forcing a person to write OOP code when it is a simple "do this then this then this" type problem is often counter productive.

The multi-paradigm nature of perl can be seen in things such as the Schwartzian transformation which has very functional aspects to it (in Lisp it is known as "decorate-sort-undecorate").  OOP exists, as does procedural (C like programming) and imperative (bash like "do this then this").

Design Patterns are reoccurring solutions to common problems.  They exist in every language.  Sometimes these patterns are called idioms, though this may also refer to things that are much more simple than a pattern.

When necessary, many of the classic GOF Design Patterns can be implemented in perl.  Perl Design Patterns will have many common names that people familiar with the GOF.  It isn't necessary the case that all of them are idiomatic perl.

When exploring design patterns in perl, please also take note of "Design Patterns" Aren't by Mark Dominus.

Many consider that the Design Patterns are deficiencies in the language.  In that perspective, Design Patterns such as the Iterator are often unnecessary in perl.  Not always - but often.

First, write idiomatic perl.  Don't try to write C in perl, or lisp in perl, or java in perl.  Perl is perl.  If there is a problem that gets bigger than idiomatic perl can handle and you start needing more complex class structures, then write them.  Know the design patterns to be able to recognize "this problem has now grown to the point of needing an abstract factory" - but don't start out trying to make an abstract factory in perl if you don't need one.

Some libraries exist in both OOP and more traditional forms.  See Should I use the function-oriented or object-oriented CGI interfaces? for an old SO question where one asks which way to use the library.

Title: Programming style in Perl

Body:
I work in Java so basically I use OOP paradigm during coding.
I am about to start working in Perl and I was wondering what is the paradigm that Perl developers follow.
In wiki it mentions that it supports many paradigms but I am not sure I understand this since it is a scripting language.

So my question is:
Are the object oriented patterns I'm familiar with in Java idiomatic in Perl, or will I need significant change to my design style to write effective Perl?

Note: This is not a question to critique Perl. I actually have to work in Perl and would like to understand how the current way I program will change.


答:
Precisely as you described - by delegating to someone else.

If you already know their strengths and weaknesses what are you hoping to learn from the interview?

Title: How to interview someone you know well?

Body: How would you interview someone you know well or someone you may even be friends with? What if you already know their strengths and weaknesses. I would prefer to avoid this situation by delegating this task to somebody else, but what if this is not an option. I feel like there is just too much personal feelings involved and it is almost impossible to be unbiased. If you have been in an similar situations, how did you handle them? </p>


答:
Most likely the team lead cut his teeth in an earlier era when right clicking and choosing "go to definition" wasn't an option. I know when I'm in heavy spike development mode I will grow pretty massive class files until I let resharper fix it for me.

In any case, if you wanted to take the team lead to task, ask him why these classes and enums aren't child classes and enums -- no reason to declare them as independent entities if they are truly dependent entities. This might help him think the fatwa through a bit.

Title: Should classes, enums and other entities be placed in separate files?

Body:
My company's team lead\architect argues that a large-scale project is easier to understand if "entities connected by logic" are placed in one .cs file.

I quote:

"The whole structure of the logic and the interface and the class can be seen in one place, this is an argument which can't be refute. To see the same thing but with a bunch of files you need to use the tools, class diagram, R# for navigation, etc."

"Following the poor theory I might scream that an army of separated files is cool, but when it comes to making changes to the existing code, especially if you were not a writer of this code, it's very difficult to understand plenty of scattered files. So on forums, you can write that "one enum- one file", but in practice this approach should never be used "

"... As to the separation of code base between developers, nowadays it's not a problem edit simultaneously the same file. The merge is not a problem."

I heard and read many times that we have to create one .cs file per enum, class and so on and this is the best practice.

But I can't convince him. He says that he don't trust to any well-known programmers such as Jon Skeet. By the way here is Skeet's opinion on this topic: Where is the best place to locate enum types?

What do you think? Is there a real problem? Or is it a matter of taste and should be regulated by the coding standard of the organization?


问:
How to manage my private key for signing .NET assemblies?
I write open source .NET class libraries as a hobby and thought about signing them. I can get Visual Studio to generate me a password protected public/private key pair and save it as a .pfx file, but I don't think I should do this for each and every project. One key pair should be enough, right?

Obviously I'm not going to put my .pfx file with the source code in my online public repository: only the assemblies I release should be signed with my key pair. Other people can use their own keys if they want.

So I'm left with some .pfx file that supposedly contains my public/private key pair.

How do I manage my key pair effectively?

Where do I store it?

Do I have to import it somewhere?

How can I use it on both my PC and my laptop?

How do I prevent the key pair hell when switching from PC to laptop?

答:
The method of storing the key pair depends very heavily on how badly you want to protect it from undesired use. Personally I store my keys in a folder protected by the standard ACLs (so anybody who manages to get admin access to my machine can get to my key pairs). For me that's good enough given that my key pairs aren't that valuable. Microsoft recommends using a key container.

If you want to avoid having to synchronize your key pairs between machines then it is probably best if you were to build the release version of the libraries on one single machine (either your PC or the laptop) and make that machine the 'build machine'. In that case depending on where you are storing your key pair (in a file protected by ACLs or in a key container) you can use either one of these techniques:

If you keep the key pair in a file:

Create public/private key pairs for both computers. You can copy the key pair but that's not required, generating individual ones for each machine is equally valid.

On each machine create an environment variable that points to the location of the key pair on that specific machine. Make sure the environment variables have the same name on both machines.

To allow you to share code between the machines and still use the machine specific key files add the following section to your C# project file.

```<code><PropertyGroup>
    <SignAssembly>true</SignAssembly>
    <DelaySign>false</DelaySign>
    <AssemblyOriginatorKeyFile>$(YOUR_ENVIRONMENT_VARIABLE_HERE)</AssemblyOriginatorKeyFile>
</PropertyGroup>
</code>```

If you also want the key to show up in the 'properties' section of the project then you can add the following section

```<code><None Include="$(YOUR_ENVIRONMENT_VARIABLE_HERE)">
  <Link>Properties\App.snk</Link>
</None>
</code>```

If you keep the key pair in a key container:

Create public/private key pairs for both computers and store them in the key containers. Make sure you use the same name for the key container.

To allow you to share code between the machines and still use the machine specific key files add the following section to your C# project file.

```<code><PropertyGroup>
    <SignAssembly>true</SignAssembly>
    <DelaySign>false</DelaySign>
    <KeyContainerName>YOUR_CONTAINER_NAME_HERE</KeyContainerName>
</PropertyGroup>
</code>```

In this case I'm not sure if you can link the key from the 'properties' section (I suspect not).

Using either one of these ways allows MsBuild to find your key and use it during the build while still giving you a (semi-)portable way of dealing with different keys on different machines. Just make sure that you always build your release version of the libraries on the same machine (which will have one set of keys), otherwise you get releases done with different keys.

As for key-pair hell, the only thing you can't do is move the bin folders from one machine to another and expect partial builds to work. If you rebuild the libraries then there shouldn't be any problems.

Body:
The method of storing the key pair depends very heavily on how badly you want to protect it from undesired use. Personally I store my keys in a folder protected by the standard ACLs (so anybody who manages to get admin access to my machine can get to my key pairs). For me that's good enough given that my key pairs aren't that valuable. Microsoft recommends using a key container.

If you want to avoid having to synchronize your key pairs between machines then it is probably best if you were to build the release version of the libraries on one single machine (either your PC or the laptop) and make that machine the 'build machine'. In that case depending on where you are storing your key pair (in a file protected by ACLs or in a key container) you can use either one of these techniques:

If you keep the key pair in a file:

Create public/private key pairs for both computers. You can copy the key pair but that's not required, generating individual ones for each machine is equally valid.

On each machine create an environment variable that points to the location of the key pair on that specific machine. Make sure the environment variables have the same name on both machines.

To allow you to share code between the machines and still use the machine specific key files add the following section to your C# project file.

<PropertyGroup>
    <SignAssembly>true</SignAssembly>
    <DelaySign>false</DelaySign>
    <AssemblyOriginatorKeyFile>$(YOUR_ENVIRONMENT_VARIABLE_HERE)</AssemblyOriginatorKeyFile>
</PropertyGroup>

If you also want the key to show up in the 'properties' section of the project then you can add the following section

<None Include="$(YOUR_ENVIRONMENT_VARIABLE_HERE)">
  <Link>Properties\App.snk</Link>
</None>

If you keep the key pair in a key container:

Create public/private key pairs for both computers and store them in the key containers. Make sure you use the same name for the key container.

To allow you to share code between the machines and still use the machine specific key files add the following section to your C# project file.

<PropertyGroup>
    <SignAssembly>true</SignAssembly>
    <DelaySign>false</DelaySign>
    <KeyContainerName>YOUR_CONTAINER_NAME_HERE</KeyContainerName>
</PropertyGroup>

In this case I'm not sure if you can link the key from the 'properties' section (I suspect not).

Using either one of these ways allows MsBuild to find your key and use it during the build while still giving you a (semi-)portable way of dealing with different keys on different machines. Just make sure that you always build your release version of the libraries on the same machine (which will have one set of keys), otherwise you get releases done with different keys.

As for key-pair hell, the only thing you can't do is move the bin folders from one machine to another and expect partial builds to work. If you rebuild the libraries then there shouldn't be any problems.


答:
To test in absolute isolation the commands and queries that the domain objects receive, I'm used to supply each test with a serialization of the object in the expected state. In the arrange section of the test, it loads the object to test from a file that I have previously prepared. At first I started with binary serializations, but json has proved to be a lot easier to mantain. This proved to work well, whenever absolute isolation in tests provides actual value.

edit just a note, some times JSON serialization fails (as in case of cyclic object's graphs, that are a smell, btw). In such situations, I rescue to binary serialization. It's a bit pragmatic, but works. :-)

Title: Unit Testing in a "no setter" world


答:
Here is how a certain large open source software foundation handles it -- and they require everything be in their source control and run through their CI stack while also maintaining the security of these signing documents.

The trick is the source code lives in one public repository while the keys live in a different, private SVN repository. Build service has the credentials to login and download the keys from SVN over HTTP and will do so as part of the final build.

The other successful tactic is to generate a keypair for each project and just let it travel with the code. Since the key is just for that project you aren't risking privacy. And because the key is well-known security generally works out.

Title: How to manage my private key for signing .NET assemblies?

Body:
I write open source .NET class libraries as a hobby and thought about signing them. I can get Visual Studio to generate me a password protected public/private key pair and save it as a .pfx file, but I don't think I should do this for each and every project. One key pair should be enough, right?

Obviously I'm not going to put my .pfx file with the source code in my online public repository: only the assemblies I release should be signed with my key pair. Other people can use their own keys if they want.

So I'm left with some .pfx file that supposedly contains my public/private key pair.

How do I manage my key pair effectively?

Where do I store it?

Do I have to import it somewhere?

How can I use it on both my PC and my laptop?

How do I prevent the key pair hell when switching from PC to laptop?