答:
If I'm a senior project manager, should I still keep learning new technology?

Yes.

For example, every month every year, most language updates themselves, and a lot of new programming concepts become popular. Many new frameworks and patterns are created and make things easily.

Less so.

If you are a PM (in any sense that I understand them to operate) make sure that you are on top of your game with regards to what you need to do first. This probably involves a lot of client liaison, presentation watching and delivery, requirements gathering, specification consuming, requirements analysis, minute taking, ego massaging, tea making, creating or facilitating the creation of SOWs, making huge Gantt charts is MS Project and working with the team to create project backlogs in Jira. That's quite a lot of work.

You have made it to senior so you probably have some of that nailed. So now you put your other head on (and in some places I think this is probably referred to as Technical Project Manager) and you make sure that you understand, high level, what technologies your team is using and what they can do with them. This gives you confidence, should make your team meetings less bewildering, enables you to engage better in project/sprint planning, allows you to call BS on dodgy developers, stops you selling things that your team cannot build and should increase your gravitas in client meetings when you confidently say yes we can - or, when required, no we cannot. Your knowledge need go no further (for professional reason anyway, you might fancy it for fun), you have a team, presumably with TTLs, TDs and TAs; it's their job to advise you when a new technology has entered the fray. Trust them.

Your role should not require you to learn how to code, but that does not mean not learning new technology. For example you should understand what the latest project management tools bring to the table and how that may improve your project lifecycles. Maybe you don't use any project or bug tracking software, so you learn Jira (easy) and you learn how it fits your organisation, clients and project structure (hard).

Be good at Project Managing, manage the clients expectations, if you don't understand the tech, don't promise that you can deliver something and make sure you've got a pocket developer with you in key client meetings and to proof read your E-Mails.

Title: As a senior project manager, should I still keep learning new skill in programming?

Body:
If I'm a senior project manager, should I still keep learning new technology?

For example, every month every year, most language updates themselves, and a lot of new programming concepts become popular. Many new frameworks and patterns are created and make things easily.

But you have to spend a lot of time to keep up with. If there's language which is proved more efficient and you aren't familiar with it, will you plan to learn it and let team members take this language to develop the project?

If there's new framework, most people say that it's helpful to our project, but you know nothing about it, would you learn it and decide it?

But as a PM, you should be a senior level or maybe busier than before. Are you willing to learn something 'not so senior'??


问:
Business Equity for Code. Is it advisable to enter into such agreements?
I have been considering this approach for a project I am about to embark upon and would like to hear from other programmers about their experience in contributing code for equity. Has anyone been truly successful in such an endeavour.</p>

答:
Disclaimer:  This is a one eyed dissertation from a hardened cynic.

In my mind equity is about as valuable as a lottery ticket. Would you trade your code for one?

We all hear about the guy who got given a a 10% stake in Acme corp for a bit of code, a few years later he sold his stake and retired to a remote Pacific atoll full of beautiful young ladies and lived happily ever after........

In reality what happens to the other 99.9999% is that 90% go nowhere. The remaining 9.999%, the company 'succeeds', but by the time its been through a couple of funding rounds, has paid the mortgage and the share holder has paid his legal fees, the original 10% has been whittled down to 0.1% and he walks away with a couple of grand or so. If you work out the hourly rate for the equity stake (you are not an employee anymore, you will be expected to pull 80-100 hours weeks to save your investment) is comes in around $1.00/hour. Sometimes when you try to sell you equity, you find the attached strings mean they are worthless...

By all means, go for it, it suits some people, but do so with you eye open. If you don't have an ounce of business acumen, don't do it.

ContentLicense: CC BY-SA 3.0


问:
My client's QA folks are shafting me. What can I do?
Backstory:

  As the single developer with experience in the chosen technology, a month ago I drafted a component that for all extents and purposes worked within acceptable levels according to the demos that were had.

Four weeks and assorted developers later (that´d be more or less last Thursday), the feature entered QA and since then I´ve been given 8 showstopper bugs, around 25 critical ones, 47 majors and a single minor one.

I´m beginning to harbor a grudge against this people, but then, they're making their best to actually improve the quality of the product, so I really shouldn´t. At the same time, I also think I have a right to sleep/eat without having nightmares of showstoppers appearing on my inbox.

What´s a polite way of handling this situation? I´ve gotten most of the former developers on board with this, but the QA folk continue to report all their bugs to me and upper management keeps asking me what I´m doing about them, so I´m growing considerably more anxious each day that passes by.

More details:  About one in thirteen bug reports are actually addressable by me (about one in three of those is actually caused by code I wrote), the rest of them lay in code that is honestly foreign to me at all. Yet I´m the one getting the reports and being ad-hoc in charge of distributing them to the right developers.  I´m not the team lead.
Judging by the amount of work I´ve been given someone seems to think I´m actually a team of people under my name. All jokes aside, the actual team lead is on extended leave without an explicit replacement, and the most senior dev in the project is actually spearheading another module for the project, and I´ve made it abundantly clear that I´ve had 0 involvement in the project for about four weeks already. The reason I´m posting this is because I´m running out of options for reals, not just imagining things.

答:
I'll echo what other people have said and emphasise that the QA are just doing their jobs and more importantly, you need to remember that QA get blamed for every bug that makes it into production.

I've been in your situation and the best solution I managed (I was getting 100 bug reports a day) was to ensure I sat in on every single triage meeting with QA and the product owner - we quickly pared them down, got a good working relationship and in the process of those meetings - managed to temper QA's quality expectations.

Don't get angry with them, work with them.


问:
Should integration test be included in continuous integration (CI)?
Assume that we are developing a web application, and Hudson does typical jobs such as compile, unit test and static code analysis.

But the tricky part is: Hudson deploys and starts up application server to do integration tests, once the previous jobs done.

That means some difficult things, such as database connection, 3rd part application connection, socket port listening, environment variables, server start up failure handing, etc.  We have to set up and tear down these things correctly each time, it’s hard thing. Worse, the integration tests can break the integration test easily.

Do you think if integration test should be included in continues integration (CI)? Can it be manually? Or simplify integration test?

答:
To first answer your question: Yes, they are definitely a part of Continuous Integration if you're asking me. But I think we need to clarify what integration tests are.

Martin Fowler was talking about continuous delivery as a way to automate the complete build process to deploy rapidly. This requires developers to get rapid feedback provided by the Continuous Integration process. So he defines stages that the build should go through:

a commit build

thorough testing

deployment

The commit build should not take longer than 10 Minutes he states, because of the rapid feedback for developers.

Here is how I see things:
In the first step, fetch the latest commit and build it. If this is successful, you run your unit tests to find out if your classes/class groups are working as defined and expected.

When this is successful you get to the integration test part. Here you test interaction of the just successfully tested units. This involves feeding the units with input and watching their state/interaction/output. Remember that we are still in the commit build, so we want this to be fast as well. So interactions with the file system, a database, network peers and the like have to be stubbed for rapid execution. Martin Fowler also hints the use of in-memory-databases if you require them, just to keep execution on the CI server fast.

After you made sure that the units are working and interacting as required, you usually want to find out about test coverage (just testing a small subsystem usually just isn't enough) and make the tested artifacts available for functional testing/QA/deployment (read: thorough testing) if you think you tests cover enough of your program. Just then, you provision a test environment that mirrors the production environment you are targeting and run tests that involve a real database, real files, real network peers, etc.

In the end, integration tests are about code changes. You want to make sure that the changes you made are not breaking the current system, meaning they integrate well. To find out if they are, you need to make sure that they behave correctly in themselves, then if they interact correctly with their dependencies, and if they were tested at all. You can be quiet confident about your system after you passed all those tests.

If later stages find any problems with your program (like when your database returns a certain value, your network connection will halt) you should try to get these tests stubbed out in the integration tests. The commit build most likely is faster than QA ;)

ContentLicense: CC BY-SA 4.0


问:
Object Oriented Programming Concepts and Interviews
I'm an Object Oriented Programming fanatic. I have always believed in modelling solutions in terms of objects. It is something that comes to me naturally. I work with a services start up that essentially works on application development using OOP languages. So I tend to test understanding of OOP in the candidate being interviewed.

To my shock, I found very very few developers who really understood OOP. Most candidates brainlessly spit out definitions they mugged up from some academic book on object oriented programming but they don't know squat about what they are saying. Needless to say I reject these candidates. However, over the course of time, I ended up rejecting almost 98% of the candidates. Now this gets me thinking if I'm being over critical about their OOP skills. I still believe OOP is fundamental and every programmer MUST GET it. Language knowledge and experience is secondary.

Do you think I'm being over critical or do I just get to interview bad programmers unfortunately?

EDIT:

I usually interview programmers with 2 to 5 years of experience. The position that I usually interview for is Ruby/Ruby on Rails application developer.

答:
Who are you interviewing?

If the answer is fresh out of schools grad, then that's expected. In school a student gets to learn a lot of theory about OOP and the accompanying assignments are hardly long enough to make them understand the advantages of using OOP vs Procedural.

ContentLicense: CC BY-SA 2.5


问:
How do I learn the right approach to implement half a feature?
I lead a development team and I want to release our product as often as possible (Continuous Delivery).

In many cases, we have to implement a feature that takes longer to implement than the time between releases. I still want people to commit their code on a daily basis (Continuous Integration).

Many times implementing a new feature requires existing feature to be changed and the existing features, of course, still need to work, even if the new feature is not finished yet.

If the developer uses the right approach, they can adjust existing features carefully and all of the above is not a problem.

However, what IS the right approach actually? My own programming attuned mind tells me what to do for each individual case, but I need to learn more and I need some reading material that I can read and refer team members to read. Or any other method of learning the right way to learn this approach will do.

So that's the question. How do I make sure team members learn the right approach to implement half a feature?

I've searched for people claiming to have strategies regarding this, but haven't found it yet, except people writing a few random thoughts on the topic. Perhaps I'm not using the right search words or perhaps no one has made any authoritative guidelines on this.

答:
The biggest thing that will help you here is having a good separation of concerns so that as far as possible one area of code does not interfere with another.

This is a place where using Dependency Injection and programming to the interface really helps, so that you can have your current implementation of ISupportingFeature on the site and then when you need to create INewFeature that depends on a different implementation, you can just develop with the new implementation and maintain the existing one in production until it is well tested and ready to go live. Assuming you have your DI working off a configuration system of some kind this will allow you to have the same code in parallel in your system and be using stable code at all times.

In fact this configuration approach is described by Martin Fowler as a Feature Toggle.

Of course, the problem only arises if you are deploying all of the code all of the time. This is precisely the type of scenario for which feature branches were designed and although I acknowledge that Mr. Fowler frowns on them, I don't know that they are all that bad, especially if they are created and used in a planned and thought-through way.


问:
May non-GPL-compatible scripts be linked at runtime to a GPLv3 library, by that (GPL) library itself?
First of all, pardon the title, as it's not very clear. I have an application I am writing that is GPLv3, and is in Java, which means that classfiles are generated and linked to for general operation. I am also using a scripting engine which, for performance, links any scripts it runs to my program's scripting libraries(which are class files) at runtime.

Given that a script must be linked at runtime, can a GPLv3-incompatible script be run on the application? Can I legally force the script to be interpreted instead? Just to clarify I'm trying to involve the GPLv3 in restricting non-GPL-compatible licenses to scripts.

The question is whether a technical linking operation functionally equivalent(except in performance) to parsing is actually linking in the legal sense.

Clarification: Scripts will be transmitted to interacting instances of the application. Scripts are loaded from a textual representation in ECMAScript/JavaScript, tokenized and parsed for syntax and then linked. This is what is confusing me. Given the conveyance, is the script being compiled and linked? Or interpreted and the parser actually runtime linking itself?

答:
Yes. GPL covers distribution/conveyance only. As your other comment suggests, you want to restrict your users. It doesn't matter that the script is sent over a network. Conveyance (the GPL defined term) requires the transfer of covered works from one legal person to another. Computers are not legal persons.

This is critically important to LGPL. Those libraries are dynamically linked together by each user, and the derived work (loaded in memory) cannot be distributed anymore. But that's no problem because the user wants to use the result, not convey it.


问:
Immutable Data Structure For Time Series Data
I'm wondering what the best data structure (for storing data on disk) is for storing immutable  time-series data (99% of the data is truly immutable, the 1% is metadata that is separate from the immutable data). I've been looking at log-structured merge-trees in particular because of it's heavy use by Cassandra and the like.

答:
I do not really see what immutable has to do with this.

You simply store it in the normal way and choose not to update it.

Your problem seems to be how to deal with a high insert rate, which unless you are google, amazon or facebook will be easily handled by any modern database.


问:
What is the most obscure sorting algorithm you know?
I just read about cyclesort via a sortvis.org blog post.
This is probably the most obscure one I have heard of so far, since it uses maths that I am not familiar with (detecting cycles in permutations of integer sets).

What is the most obscure one you know?

答:
I don't know if this counts as obscure, but one of the most ridiculous sorting "algorithms" is Bogosort.  The links off the Bogosort page are fun too.

And there's this gem from the section on "quantum bogo-sort".

Arguably, creating 2N universes is also very memory-intensive.

Hmmm ... you could say that :-).


答:
Consider this like an investor who is considering investing money into a startup business. Is it a good bet?

Work out a cash value for your time, using some appropriate salary or hourly rate.

Try to assess the possible payback from the investment. You'll probably be looking at a smallish chance of a largish return. Does the business model make sense to you (can you imagine them making large amounts of money)? Will the founders be personally convincing to future customers and investors?

Are you willing to take a risk? What's the downside? This will probably depend on your personal circumstances. E.g. if you have dependents and few savings, maybe it's not a good idea. If you have no dependents and some savings, maybe it is a good idea.

Does the project excite you? Will it at least look good on your CV if it all goes wrong?

Title: Business Equity for Code. Is it advisable to enter into such agreements?

Body: I have been considering this approach for a project I am about to embark upon and would like to hear from other programmers about their experience in contributing code for equity. Has anyone been truly successful in such an endeavour.</p>


问:
Languages implemented in Python?
AFAIK, Scala and Clojure are implemented in Java and Java is implemented in C. I suppose that many or most languages are implemented in C, for instance Perl, Python and SQL. I don't know much about language implementation but maybe you can tell me the rationale to favor one implementation language Java over another C?

Are there any theories about one language implementing another, or are we resorted to Turing machine theory where a language is regarded are a Turing machine?

答:
It doesn't really matter what the Java or Python engine was implemented in. As long those engines are compatible with the specifications of those languages. There are some Java virtual machines that run natively on CPU hardware. So you can't assume it's always implemented in C.

There is one case where a C/C++ compiler is used to re-compile itself.

For example, let's say the developers of a C++ compiler are working on version 5. This new version fixes bugs and increases performance. They use version 4 to compile this new version 5, and then use that build to rebuild the same compiler. This creates a new compiler that has bug fixes and performance improvements.

When a high level language like Java is used to create another language. It's really just a case of higher degree of usefulness. Clojure is a step above Java in ease of use. The amount of effort to achieve the same level of usage from C++ would make the project ineffective to do, because you would have to reimplement all the underlying Java features it depends upon.

Title: Languages implemented in Python?


问:
Utility Classes in MVC - ASP.NET
So I was wondering today, where would you put utility classes in an ASP.NET MVC app? By utility classes I mean classes that can be static and are just used to perform a function. Like a class to send an email that takes email address , subject, and body as arguments.

I would assume maybe creating a separate folder and namespace would be good enough, but wanted to get everyone opinions

答:
You don't. And your own example is a perfect one to show why not.

You want to send emails, right? So you create somewhere a static class CommunicationUtilities with a static SendEmail() in it. You use this method from some class which does a bunch of stuff, , for example resets the password of a user and sends him a new one by email. Perfect.

Now, what happens if you want to unit-test your class? You can't, because every time you want to test the method which resets the password, it changes the database (which is not suitable for a unit test), and moreover sends an email (which is even worse).

You may have read about Inversion of Control, which has a benefit of making unit testing easier. Articles about IoC will explain you that instead of doing something like:

void ResetPassword(UserIdentifier userId)
{
    ...
    new MailSender().SendPasswordReset(userMail, newPassword);
}
```

<p>you do:</p>

<pre class="lang-cs prettyprint-override"><code>void ResetPassword(IMailSender sender, UserIdentifier userId)
{
    ...
    sender.SendPasswordReset(userMail, newPassword);
}
</code>```

which allows to use mocks and stubs.

Try to apply IoC to your CommunicationUtilities. Right, you can't. That's why it's broken.

Title: Utility Classes in MVC - ASP.NET

Body:
You don't. And your own example is a perfect one to show why not.

You want to send emails, right? So you create somewhere a static class CommunicationUtilities with a static SendEmail() in it. You use this method from some class which does a bunch of stuff, , for example resets the password of a user and sends him a new one by email. Perfect.

Now, what happens if you want to unit-test your class? You can't, because every time you want to test the method which resets the password, it changes the database (which is not suitable for a unit test), and moreover sends an email (which is even worse).

You may have read about Inversion of Control, which has a benefit of making unit testing easier. Articles about IoC will explain you that instead of doing something like:

void ResetPassword(UserIdentifier userId)
{
    ...
    new MailSender().SendPasswordReset(userMail, newPassword);
}

you do:

void ResetPassword(IMailSender sender, UserIdentifier userId)
{
    ...
    sender.SendPasswordReset(userMail, newPassword);
}

which allows to use mocks and stubs.

Try to apply IoC to your CommunicationUtilities. Right, you can't. That's why it's broken.


答:
There are two problems here: one is implementing half a feature; the other is keeping the shipping product working during continuous development.

Implementing half a feature

A strong overarching design will help with this. This lets you implement the feature with its boundaries clearly defined--e.g., APIs to adjacent bits of code, expectations about data structures, and an understanding of how and when the implemented code will be called.

Testing can include mocked up versions of the code for the other parts of the feature; this helps smooth the transition when you go to implement the second half.

Keeping the shipping product working

There are a handful of options here:

Turn the feature 'off' in the shipped product. Just because the code is in the product doesn't mean it has to be executed or presented to users. The downside is that you will not be delivering incremental value to your users, and you will not be getting feedback.

Reveal the edges of the feature to your users. Show what you've got, and provide some indication of what's to come.

Let users switch between new and old functionality. This sometimes requires maintaining two code paths that are end-user-ready.

Finally, if you are having trouble with any of these solutions, consider whether you have split the feature along the right boundaries. If you sliced things a different way, would it be easier to pull apart?

Title: How do I learn the right approach to implement half a feature?

Body:
I lead a development team and I want to release our product as often as possible (Continuous Delivery).

In many cases, we have to implement a feature that takes longer to implement than the time between releases. I still want people to commit their code on a daily basis (Continuous Integration).

Many times implementing a new feature requires existing feature to be changed and the existing features, of course, still need to work, even if the new feature is not finished yet.

If the developer uses the right approach, they can adjust existing features carefully and all of the above is not a problem.

However, what IS the right approach actually? My own programming attuned mind tells me what to do for each individual case, but I need to learn more and I need some reading material that I can read and refer team members to read. Or any other method of learning the right way to learn this approach will do.

So that's the question. How do I make sure team members learn the right approach to implement half a feature?

I've searched for people claiming to have strategies regarding this, but haven't found it yet, except people writing a few random thoughts on the topic. Perhaps I'm not using the right search words or perhaps no one has made any authoritative guidelines on this.


问:
What is the pattern called when getters take responsibility for the setting?
I've been heavily using a pattern for years now, but I don't know what it's called.

It looks like this....

```<code>class xzy
{

  public function getFoo()
  {
    if ( undefined(this.foo) )
    {
       this.foo = new Foo;
    }
    return this.foo
  }

  public function setFoo(foo)
  {
    this.foo = foo;
    return this;
  }

  public function getResult()
  {
    if ( undefined(this.result) )
    {
       this.result = this.getFoo().action();
    }
    return this.result;
  }

}
</code>```

It find it great for testing yet still allows for a high level of encapsulation.  It's also great for drying up code. I also very rarely use a constructor. I'm now in a position where I could really do with specifying the pattern in some documentation but I don't know what it's called and it's a hard thing to try and Google.

答:
lazy initialization

I like to use it to cache a calculation result that is expensive and it allows me to clear the cache easily when one of the variables change (and when there are likely more changes waiting to happen):

```<code>public Rectangle getBoundingRect(){
    if(bbox==null){
    bbox=calculateBBox();
    }
    return bbox;
}

private Rectangle calculateBBox(){
    //expensive operation
    return //...
}

public void updateGeom(){
    bbox=null;
}
</code>```

Body:
lazy initialization

I like to use it to cache a calculation result that is expensive and it allows me to clear the cache easily when one of the variables change (and when there are likely more changes waiting to happen):

public Rectangle getBoundingRect(){
    if(bbox==null){
    bbox=calculateBBox();
    }
    return bbox;
}

private Rectangle calculateBBox(){
    //expensive operation
    return //...
}

public void updateGeom(){
    bbox=null;
}


答:
How do I make sure team members learn the right approach to implement half a feature?

By teaching them. (duh)

Learning will involve iteration: trying something, seeing how it works, and then modifying their approach to achieve better results. For this sort of thing, I would advocate design/code reviews. You get to see how the half-feature is designed/implemented and have the opportunity to give feedback. "This and that won't work because they'll break our CI; how about XYZ?", "Good job here, that's really clean."

Doing the reviews as a team will help everyone learn what you already intuitively know.


答:
Avoid like the plague would be my advice.

View it as a cake. As more people join (or more shares are issued), your slice will get smaller and smaller. There is nothing you can do about this.

Yes, everyone knows a friend of a friend of a friend who this sort of arrangement has worked for - but strangely, nobody ever knows the individual personally...

That isn't to say that the cake itself doesn't grow - it does (or should!). Just that it never (or rarely) grows enough to make your share profitable vs an hourly rate/salary.


问:
How to name nested function?
When you have a function that wraps another one in Scala. What do you call the nested function?

I found this :

```<code>def factorial(i: Int): Int = {

  def fact(i: Int, accumulator: Int): Int = {
     if (i <= 1)
        accumulator
     else
        fact(i - 1, i * accumulator)
  }

  fact(i, 1)

}
</code>```

I usually use just do because it is shorter, generic, and explicit. But is there a better way or a naming convention for nested functions?

```<code>def myFunction() = {

  def do(i: Int) = {
    ...
  }
  do(1)

}
</code>```

答:
A convention I've seen in some other languages is to use a leading or trailing underscore for a private, temporary named function that exists purely as an implementation detail:

```<code>def factorial(i : Int): Int = {
  def _factorial(i : Int, acc : Int): Int = {
    ...
  }
  _factorial(i)
}
</code>```

I don't believe there's an official standard in this case. Just calling it fact or factorialImplementation or something should be fine.

Speaking of factorial, I assume this is being done for the sake of learning right? Because there are a number of shorter and potentially easier-to-maintain ways to get the same results. I like the implementation that uses reduceLeft (or foldl1 if you come from Haskell-land):

```<code>Stream.from(1).take(n).reduceLeft(_*_)
</code>```

Title: How to name nested function?

Body:
A convention I've seen in some other languages is to use a leading or trailing underscore for a private, temporary named function that exists purely as an implementation detail:

def factorial(i : Int): Int = {
  def _factorial(i : Int, acc : Int): Int = {
    ...
  }
  _factorial(i)
}

I don't believe there's an official standard in this case. Just calling it fact or factorialImplementation or something should be fine.

Speaking of factorial, I assume this is being done for the sake of learning right? Because there are a number of shorter and potentially easier-to-maintain ways to get the same results. I like the implementation that uses reduceLeft (or foldl1 if you come from Haskell-land):

Stream.from(1).take(n).reduceLeft(_*_)


答:
Don't create static classes for utilities. Statics are bad in most cases. Don't call them managers either. Whatever it is you are working on, it should be placed in a logical namespace.

For example:

```<code>namespace Application.Notifications.Email
{
   public interface ISendEmailCommand
   {
      void Execute(Email email);
   }
}
</code>```

Email address, subject and body is a separate concern, therefore I would have a class structure for that, hence why I've used Email email in example above.

Title: Utility Classes in MVC - ASP.NET

Body:
So I was wondering today, where would you put utility classes in an ASP.NET MVC app? By utility classes I mean classes that can be static and are just used to perform a function. Like a class to send an email that takes email address , subject, and body as arguments.

I would assume maybe creating a separate folder and namespace would be good enough, but wanted to get everyone opinions

Body:
Don't create static classes for utilities. Statics are bad in most cases. Don't call them managers either. Whatever it is you are working on, it should be placed in a logical namespace.

For example:

namespace Application.Notifications.Email
{
   public interface ISendEmailCommand
   {
      void Execute(Email email);
   }
}

Email address, subject and body is a separate concern, therefore I would have a class structure for that, hence why I've used Email email in example above.


问:
scripting support in a C# application
what is the simplest and fastest way to support simple scripting in a .Net application?
I search a lot but only find many things with practical no documentation or outdated since years.
I only need to transfer a simple .Net Object to the script and get a bool result from it.</p>

答:
Another scripting language you should consider is PowerShell.  There's a fully working example of an application that exposes some of its internal objects to a script environment here.

This is the description of the application from the book (emphasis mine):

The reference application for this chapter, Beaver Music, is a very simple music album management system. It supports create, read, update, and delete (CRUD) actions for albums. Beaver Music has the functionality you’d expect—a couple of dialogs for adding and changing album information, and you can delete albums as well. What we want to focus on is the PowerShell Console button (shown in Figure 5-1), a WPF application that has the PowerShell engine embedded in it. As noted earlier, PowerShell is surfaced as a console, a scripting language, and an API; the custom PowerShell console uses this surfaced API in conjunction with the Beaver Music application so it can be scripted and automated. This works similarly to the way Microsoft Excel can be automated with the embedded Visual Basic for Applications (VBA) scripting language.

Title: scripting support in a C# application


答:
I take a different view from the other answers on here already.  I agree with you that you want to integrate changes from developers as soon as possible, and to keep testing the combined mix of code.

However, I do not agree that its right to ship code developed this morning, just because we are releasing this afternoon.  That is a recipe for disappointed customers.

The solution is to have branches in your version control tree, and that you have a separate process to promote verified deltas from the develop branch to the release branch.

That way you get the best of both worlds.  You have developers doing continuous integration, and the advantages that brings, you have stable code shipping regularly to the customer, and you have a new process that tests completed features in the developer branch, and if they pass testing make them part of the released product.

There are two tools that I am familiar that support these kind of processes well.  If your development structure is simple, then git, with git-flow implements a good branching structure that works well in small to medium sized teams (perhaps 20 developers).

For larger development teams, or where a more complex branching strategy is needed to support multiple 'spins' of your product, accurrev is the best there is. The developers not involved in managing the changes will complain that its harder than sub-version etc...  but it does support complex development environments.


问:
How to Implement Error Handling
Even though I've programmed on a professional level for some years I still do not fully understand error handling. Although my applications work fine, the error handling isn't implemented at a professional level and is a mix and match of a number of techniques.

There is no structure behind my error handling. I'd like to learn and understand how it's implemented at a professional level. This is one area where I lack knowledge.

When should I use an exceptions and when should I return a success status, to be checked in the logic flow? Is it OK to mix exception and returning a status?

I code in C# mainly.

答:
I think MainMa's list is very complete. I'll just add a few of my own:

Read Eric Lippert's article on how he categorizes exceptions.
Particularly important is his point on not catching exceptions that
are in reality bugs in your code. Fix the code instead!

If you know that an exception can occur AND you can do something about it,
handle it, but limit the scope of you try-catch and catch the
specific exception you're expecting. That is, don't do this:

```<code>public void Foo() {
    try {
        //get input from use
        //do calculations
        //open file
    }
    catch (Exception ex) {
       //handle exception
    }
}
</code>```

Instead do this:

```<code>public void Foo() {
    //get input from use
    //do calculations
    try {
        //open file
    }
    catch (FileOpenException ex) {
       //handle exception
    }
}
</code>```

Don't use exceptions for control flow. For example, don't throw a ClientNotFoundException in a lookup dialog (a client not found is non exceptional in this situation) and expect the calling code to show a "No results found" message when this happens.

Don't swallow exceptions!

Keep in mind that truly handling an exception can only mean 3 things:

Retry the operation. Only valid if the problem is transient.

Try an alternative.

Notify someone about the problem. Only valid if the notification is actionable, meaning that the user can do something about it.

If none of these options apply then you probably shouldn't catch that exception. You should log it, though, and then either cancel the operation or shut down. Of course this depends what your requirements are in regards to correctness vs robustness.

Title: How to Implement Error Handling

Body:
I think MainMa's list is very complete. I'll just add a few of my own:

Read Eric Lippert's article on how he categorizes exceptions.
Particularly important is his point on not catching exceptions that
are in reality bugs in your code. Fix the code instead!

If you know that an exception can occur AND you can do something about it,
handle it, but limit the scope of you try-catch and catch the
specific exception you're expecting. That is, don't do this:

public void Foo() {
    try {
        //get input from use
        //do calculations
        //open file
    }
    catch (Exception ex) {
       //handle exception
    }
}

Instead do this:

public void Foo() {
    //get input from use
    //do calculations
    try {
        //open file
    }
    catch (FileOpenException ex) {
       //handle exception
    }
}

Don't use exceptions for control flow. For example, don't throw a ClientNotFoundException in a lookup dialog (a client not found is non exceptional in this situation) and expect the calling code to show a "No results found" message when this happens.

Don't swallow exceptions!

Keep in mind that truly handling an exception can only mean 3 things:

Retry the operation. Only valid if the problem is transient.

Try an alternative.

Notify someone about the problem. Only valid if the notification is actionable, meaning that the user can do something about it.

If none of these options apply then you probably shouldn't catch that exception. You should log it, though, and then either cancel the operation or shut down. Of course this depends what your requirements are in regards to correctness vs robustness.


问:
Is my application vulnerable to SQL injection if I don't specify each type in Doctrine2?
I thought Doctrine 2 DBAL prepared statements were safe from SQLi. But I found this confusing bit in the docs:

By default the Doctrine DBAL does no escaping. Escaping is a very
  tricky business to do automatically, therefore there is none by
  default. When you use the Doctrine DBAL as standalone, you have to
  take care of this yourself.

What does that mean exactly? If someone tries to inject malicious code, will the query fail (as opposed to insert escaped) because the RDBMS protects me? Or I'm not protected at all?

I'm using PostgreSQL as my RDBMS.

答:
I would like to clarify whether you're just using the DBAL part of Doctrine, or all of it. From my understanding, DBAL is a "lower-level" part of Doctrine, that just focuses on communicating with the database.

If you are using Doctrine with Symfony (the most commonly used way I have seen it used), and have created the appropriate entity / repository / query builder classes, then you should not need to escape any values manually. This is because values entered using those classes would be automatically escaped using prepared statements (behind the scenes, by Doctrine).


答:
Languages aren't implemented in anything. A language is a set of mathematical rules and restrictions. It is specified, typically in a semi-formal subset of English, sometimes in a specialized specification language.

Compilers and interpreted are implemented, and they can be implemented in anything, provided the language is powerful enough to express the necessary concepts. If the language is Turing-complete, then there is no problem. If you are trying to write an interpreter for a Turing-complete language in a language which isn't Turing-complete, you will have to get creative, though. But even that might be possible, e.g. if you are using a Total Functional Language, you might be able to model the interpreter as co-recursion over co-data.

AFAIK, Scala and Clojure are implemented in Java

Like I said: Scala and Clojure are languages, they aren't implemented in anything.

However, both languages only have one implementation (AFAIK, anyway). The Scala compiler and libraries are written completely in Scala, the Clojure compiler is written completely in Clojure, the Clojure libraries are written almost completely in Clojure with some small bits of the core datastructures written in the host platform's native systems programming language (Java for the Java port, C# for the CLI port, ECMAScript for ClojureScript).

and Java is implemented in C.

Again, Java is a language. It has a specification, it isn't implemented in anything.

There are many implementations of Java. Almost all of them are written in Java. For example, the javac implementation of Java that ships with Oracle JDK is written in Java (and interestingly was written by Martin Odersky, the designer of Scala).

Well, actually, if you take the entire "Java Platform", then "Java" is actually three things:

the Java programming language

the Java Virtual Machine (JVM)

the Java Runtime Environment (JRE)

In almost all implementations of the Java Platform, both the Java language and the JRE are implemented in Java. The implementation language of the JVM differs from platform to platform: the HotSpot JVM which ships with Oracle JDK is implemented in C++, but the Maxine JVM (also by Oracle) is implemented in Java. There is an experimental JVM implemented in ECMAScript, I believe, and there is a sort-of "toy" implementation of a subset of the 1st Edition JVM in Ruby.

Also, not all implementations of Java are implemented as compilers to JVML bytecode. There are compilers which compile Java to AMD64 machine code, for example, or ECMAScript or Lisp or …

I suppose that many or most languages are implemented in C, for instance Perl, Python and SQL.

I'm not very familiar with Perl, but I'm pretty sure that not all implementations of Perl are written in C. Ponie, for example, is written in PASM and NQP and uses the PGE. No C anywhere. Implementations of Perl6 are all over the place: Pugs was written in Haskell, Rakudo is written in Perl6, NQP and PASM, there's an implementation written in CommonLisp, one in Scheme and probably many others.

For Python, there are currently four major production-ready implementations. CPython is written in C, IronPython is written in C#, Jython is written in Java and PyPy is written in RPython, which is a statically typed language somewhat similar to Java but a proper syntactic and semantic subset of Python.

The first prototype for the new JIT compiler in PyPy was written in Prolog.

SQL also has many implementations that are not written in C. The Apache Derby database, HSQLD and H2, for example, are written in Java, so their SQL compiler/interpreter is written in Java as well. SharpHSQL and VistaDB are examples of SQL databases written in C#.

I don't know much about language implementation but maybe you can tell me the rationale to favor one implementation language Java over another C?

The reasons for choosing a language to implement an interpreter or compiler are the same as for any other application, really. Familiarity. Curiosity. Hype. Superstition. Technical Superiority. Management Pressure. Peer Pressure. You name it.

There are, however, three classes of languages which make more sense than others to implement a compiler or interpreter:

the source language of the compiler or interpreter, e.g. writing a Python interpreter in Python

a language specifically designed for writing compilers or interpreters, e.g. ML

(this is actually less relevant for an compiler and more relevant for writing an interpreter or a language runtime) a native systems programming language of the target platform.

The reason why #1 is a good idea is that it reduces the barrier to entry for help in your project. If you write your Python interpreter in Python, then every Python programmer can help you write it. In order to write an interpreter, you need to know the language being interpreted; if you write it in a different language, you need to know two languages. The downside is that the language may actually not be well-suited to writing an interpreter or compiler: imagine, for example, writing a SQL interpreter in SQL (or even more extreme: write a CSS engine in CSS, which isn't even possible).

I guess the reason why #2 is a good idea is obvious: if a language is designed for writing interpreters or compilers, then writing an interpreter or compiler will be much easier than in a language not designed for writing interpreters or compilers. The downside is that your collaborators need to learn two languages. Examples of languages designed for writing language implementations are ML and OMeta, Haskell and Scala are also good, even though they are not specifically designed for it, they share many characteristics with ML.

Choice #3 allows you to achieve tight integration with the target platform. For example, when writing a Ruby implementation which should integrate closely with the Unix platform, then it makes sense to write at the least the low-level language runtime in C, C++, D or a similar language. The disadvantages here are again that you need to know two languages and that that language may not be particularly good at writing language implementations.

Sometimes, you can hit the sweet spot, though. For example, F# was designed to be a native systems programming language for the CLI platform, and it borrows heavily from ML, so it is very good at writing compilers. So, if you write an F# compiler in F#, you have all the advantages and none of the disadvantages of #1, #2 and #3.

Note that you can take #2 to a much more extreme level. Why use just one language which is good at writing compilers? Why not use different languages which are good at writing different parts of compilers? Use lex for the lexer, yacc for the parser, Prolog for the type checker, Haskell for the semantic analyzer.

For example, the GHC Haskell compiler and libraries are written in Haskell, but the runtime system is written in C. Actually, a piece of the compiler is even written in Perl! The GCC backend generates C source code from Haskell. This C code is then handed off to GCC and compiled to assembly code. The assembly code is processed by a Perl script that makes some adjustments so that the generated code complies with the Haskell calling conventions (this cannot be expressed in C, therefore it is impossible to include that in the generated C source). Lastly, the assembly is handed off to the GNU assembler.

Title: Languages implemented in Python?

Body:
AFAIK, Scala and Clojure are implemented in Java and Java is implemented in C. I suppose that many or most languages are implemented in C, for instance Perl, Python and SQL. I don't know much about language implementation but maybe you can tell me the rationale to favor one implementation language Java over another C?

Are there any theories about one language implementing another, or are we resorted to Turing machine theory where a language is regarded are a Turing machine?


问:
How to elegantly work with a lot of print functions?
I'm working on a Python project that is executed on a terminal (or console) for which I am planning to implement a GUI.

I did not major in CS so I really have no idea how to effectively design a terminal GUI such that:

the user interface looks good

in GUI, it is directed to a certain widget, let's say, a text label, or a bottom bar, or a hide-able frame.

Do you have any suggestions?

Currently, I am using the print function to provide essential information on STDOUT during execution, so a lot of print calls are distributed here and there in the code.

I'm thinking of using macro-like variables such as 'FILE_NOT_EXISTS_MESSAGE' for printing, and all of them and their values would be defined in one file.

Is that a standard way to do this?

Should I introduce a logging system?

In summary, I'm looking for a pattern for handling console output that is effective and adaptable.

答:
May I suggest that you have a look at a Model / View / Controller style architecture.

That way you can write a Model and Controller implementation that does what your application needs to do, and then you can write two separate views.  A GUI view and a console view.

Have a look at the curses package for python as a way of doing a GUI interface on a console app (if its appropriate), or you could use a command line style interface to define a defined script of actions on the data if the cmd tool is designed to be non interactive in its use.


问:
Machine Learning Algorithm for Heating/Lighting Optimization
I'm working on a project where I'm developing an interface that learns how you typically use a space, and tries to create the most appropriate control strategy for heating/lighting. I've done some research into the area of machine learning techniques, but I was wondering if there were any recommendations on which learning algorithm would work best for this scenario. I have a lot of different input parameters: I designed a low-cost wireless sensor which reports light, temperature, humidity, and motion detection every 8 seconds... I also tap into live weather feeds through the internet for exterior conditions... And I'm also storing all of the different UI changes (toggles, sliders, etc...) so hopefully I can tell when people are actually changing certain settings and adapt accordingly. As far as learning algorithms... there's a lot of different options including (to name just a few):

K-Means

Decision Tree

Naïve Bayes

Neural Networks

Hidden Markov Models

Nearest Neighbors

Which of these would be most ideal for the scenario I'm referring to of: Having multiple data sources and correlating them with user input to predict future desires and plan accordingly.

答:
Monte-Carlo methods may work for you. In a nutshell: define the boundaries of the results you are looking for, for example energy consumption(derived from measured system parameters) within a range, and run a simulation where the free variables are allowed to vary to simulate a physical system. The sets that fall within the solution space will define the acceptable input ranges.

If your search space is manageable (depends on your system constraints), then you can fit curves to these parameters.

Alternately, you can use a minmax approach if you can define your search space in a way suitable for local minimization.


答:
Leaving logging scattered throughout your code and trying to do the right thing in each instance, is probably impractical.

There are a couple of popular approaches, differing mostly in how structured the internal/intermediate data is.

The Model-View-Controller scheme would split your application into roughly these components:

Model is your internal application state and logic: it shouldn't print anything (except perhaps fatal errors, to stderr), but should be able to send events by calling methods on object

View would be an abstract base class in a statically-typed language: in Python you don't need it at all, except as an idea of the interface called by the Model and implemented by:

TerminalView, which will print something suitable to the terminal when Model calls a method

GraphicalView, which will display the information graphically instead

A possible problem with this approach is that you have to come up with some format for the data passed from the Model to the View object, and it's impossible for me to say how complex this is for your application, how flexible it needs to be, etc.

The porcelain/chrome scheme, as used by git:

this keeps the idea of a back-end (Model) that avoids thinking about how to present information, but it's output is machine-parseable text.

You may still want a front-end to turn that machine-readable text output back into human-readable text output (as well as the new GUI front-end to display it graphically), in which case these are exactly equivalent to the two concrete View types described previously.

If you can format text output that's human-readable and easily machine-parseable, so much the better: you can skip the terminal front-end and just make the GUI a wrapper around the existing terminal application.

Note that I've omitted the Controller part of MVC entirely, because it isn't clear whether you actually need interaction and feedback, or just pretty output.

Title: How to elegantly work with a lot of print functions?

Body:
I'm working on a Python project that is executed on a terminal (or console) for which I am planning to implement a GUI.

I did not major in CS so I really have no idea how to effectively design a terminal GUI such that:

the user interface looks good

in GUI, it is directed to a certain widget, let's say, a text label, or a bottom bar, or a hide-able frame.

Do you have any suggestions?

Currently, I am using the print function to provide essential information on STDOUT during execution, so a lot of print calls are distributed here and there in the code.

I'm thinking of using macro-like variables such as 'FILE_NOT_EXISTS_MESSAGE' for printing, and all of them and their values would be defined in one file.

Is that a standard way to do this?

Should I introduce a logging system?

In summary, I'm looking for a pattern for handling console output that is effective and adaptable.


问:
XSLT and possible alternatives
I had a look at XSLT for transforming one XML file into another one (HTML, etc.). Now while I see that there are benefits to XSLT (being a standardized and used tool) I am reluctant for a couple of reasons

XSLT processors seem to be quite huge / resource hungry

XML is a bad notation for programming and thats what XSLT is all about.

It do not want to troll XSLT here though I just want to point out what I dislike about it to give you an idea of what I would expect from an alternative.

Having some Lisp background I wonder whether there are better ways for tree-structure transformations based upon some lisp. I have seen references to DSSSL, sadly most links about DSSSL are dead so its already challenging to see some code that illustrates it. Is DSSSL still in use? I remember that I had installed openjade once when checking out docbook stuff.

Jeff Atwood's blog post seems to hint upon using Ruby instead of XSLT.

Are there any sane ways to do XML transformations similar to XSLT in a non-xml programming language? I would be open for input on

Useful libraries for scripting languages that facilitate XML transformations

especially (but not exclusively) lisp-like transformation languages, or Ruby, etc.

A few things I found so far:

A couple of places on the web have pointed out Linq as a possible alternative. Quite generally I  any kind of classifications, also from those who have had the best XSLT experience.

For scheme http://cs.brown.edu/~sk/Publications/Papers/Published/kk-sxslt/ and http://www.okmij.org/ftp/Scheme/xml.html

答:
Without additional information about the context, it's difficult to answer.

Still, I don't understand why you don't want to use XSLT. It's the right tool for the job, and a powerful one. It is done specifically to transform one XML into another.

XSLT processors seem to be quite huge / resource hungry

Do you have hard data to support that? Have you implemented the solution using XSLT and found that XSLT is the bottleneck which makes it impossible to deliver the product while fulfilling all the non-functional requirements related to performance?

Without statistical data and profiling, you can't reasonably assert that a given solution won't work. Are the non-functional requirements reasonable enough? Would you prefer wasting, say, ten days of developers' work to gain a few hundreds of milliseconds by replacing XSLT by another alternative? Does it worth it?

XML is a bad notation for programming and thats what XSLT is all about.

So you want to transform one XML into another, but don't want to use XSLT because "XML is a bad notation"?

If it's the fact that you use XML as a sort of programming language which annoy you so much, see it not as programming, but rather a bunch of transformation rules.

You don't even need to write XSLT by hand. There are plenty of ETL editors which can let you map graphically one XML into antother: no programming required whatsoever. Some of them use XSLT as output.

Title: XSLT and possible alternatives


答:
XML is not a Programming Language

XML is a way to Transfer/Transport Data.

what an XSLT instruction does is use Xpath to query the Data in a specific way and put it into another Data Transport Object/Document.

AND/OR

XSLT can transform your XML into HTML, which is another way to display/transport the Data contained in an XML Document.

if you are looking to Change the XML, or Create an XML Document then you could use any number of languages: C#, VB, Ruby, Etc.

usually when you use an XSLT file to transform an XML Document you still have the original XML Document, you don't actually change the original Document, you really create a new one.

Title: XSLT and possible alternatives

Body:
I had a look at XSLT for transforming one XML file into another one (HTML, etc.). Now while I see that there are benefits to XSLT (being a standardized and used tool) I am reluctant for a couple of reasons

XSLT processors seem to be quite huge / resource hungry

XML is a bad notation for programming and thats what XSLT is all about.

It do not want to troll XSLT here though I just want to point out what I dislike about it to give you an idea of what I would expect from an alternative.

Having some Lisp background I wonder whether there are better ways for tree-structure transformations based upon some lisp. I have seen references to DSSSL, sadly most links about DSSSL are dead so its already challenging to see some code that illustrates it. Is DSSSL still in use? I remember that I had installed openjade once when checking out docbook stuff.

Jeff Atwood's blog post seems to hint upon using Ruby instead of XSLT.

Are there any sane ways to do XML transformations similar to XSLT in a non-xml programming language? I would be open for input on

Useful libraries for scripting languages that facilitate XML transformations

especially (but not exclusively) lisp-like transformation languages, or Ruby, etc.

A few things I found so far:

A couple of places on the web have pointed out Linq as a possible alternative. Quite generally I  any kind of classifications, also from those who have had the best XSLT experience.

For scheme http://cs.brown.edu/~sk/Publications/Papers/Published/kk-sxslt/ and http://www.okmij.org/ftp/Scheme/xml.html


答:
You should split UI and the logic, that's for sure.

There are more pattern for this, one of them is MVC which @Ptolemy already mentioned. There are more of them. MVC may look too hard to grasp (a bit jokingly, no one really knows how to do MVC right; but that's mainly because it has lots of distinct flavours during its long history), but even if you do some more naive system at the beginning, it is fine.

The goal you should have, is to split, as much as possible, the process of showing the data from the logic of the application. If you do not want to study MVC and all its variants (MVP, MVVM), you may do the simple blackboard and let both model (the logic part) as well as view (the printing part) access only the blackboard (blackboard is data abstraction where data are put into a store ("blackboard") and more pieces of software ("agents") are observing it for changes, each agent interested only in its own subset, and then take the data from the blackboard, do some action and put the result back). Blackboard-type of data is good to keep different parts of SW separated but still give them controlled way to communicate.

But, there are many ways to achieve the split.


答:
I think the bubble sort would be the wrong answer in this situation too</p>

<p>:) </p>

Title: What is the most obscure sorting algorithm you know?

Body:
I just read about cyclesort via a sortvis.org blog post.
This is probably the most obscure one I have heard of so far, since it uses maths that I am not familiar with (detecting cycles in permutations of integer sets).

What is the most obscure one you know?

Body:
I think the bubble sort would be the wrong answer in this situation too

:)


问:
a lot of small objects - OO pasta
In the code I am working on, there are a lot of really small objects like:

```<code>    class HasFieldLameSetter
    {
     public:
        HasFieldLameSetter(field& p_):m(_p){}
        void set(bool p2)
        {
            m.hasLame = p2;
        }
       field& m;
   };
</code>```

Having lots of small classes creates a hard-to-read and complicated "code pasta". Sometimes, reading it is really really hard because I spend a lot of time jumping from file to file to find out that the class did something trivial like in the example setting bool to true.  In addition, those objects are being passed around everywhere by "dependency injection" which makes reading it even more difficult.

How do I persuade the author of the code to write slightly bigger objects?

In my opinion too many small objects is just a nightmare for programmers. Am I missing something, or is there a mistake in my thinking? I would be happy to read any papers that might change my point of view.

答:
Could I agree with it? Not often.

It is universally excepted best practice that an object have one, and only one responsibility to change (Single Responsibility Principle). For something like this, the code very likely needs to be very granular in order to compose these little teeny objects into more meaningful things.

It is also very common in older C++ and Java where the tiny objects are essentially functors/delegates/function objects, but the language does not support nice syntax to cut down on this sort of boilerplate.

A bunch of tiny objects can get over-engineered or "too" abstracted, but it's not a nightmare and occasionally necessary. I'd rather have too small objects than too large any day.

Title: a lot of small objects - OO pasta


问:
Main method templating
Now that I've gotten into a dependency injection groove, I find main methods for different applications all look basically the same. This is similar to stuff you might find on the Guice documentation, but I'll put an example here:

```<code>public class MyApp {
    public static void main(String... args) {
        Injector inj = Guice.createInjector(new SomeModule(),
                       new DatabaseModule()
                       new ThirdModule());
        DatabaseService ds = inj.getInstance(DatabaseService.class);
        ds.start();

        SomeService ss = inj.getInstance(SomeService.class);
        ss.start();

        // etc.
    }
}
</code>```

For multiple applications I have main methods that all look just like that. But now, lets say I want to make a brand new app, that, say, reuses my DatabaseModule. I pretty much have to copy and paste the main method and make appropriate changes... I view copy-paste as a code smell. Further, lets say I realize I should probably be putting shutdown hooks in, now I have to go through and change every main method in all my applications to attach shutdown hooks to each service.

Is there some good way to template this process and minimize the boilerplate?

答:
Nothing about the code example in your question suggests the need for automation. Every Main method is going to be different.

Of course, if you had a database, and you were writing data access code, you might realize that a lot of this code looks almost exactly the same ("CRUD" methods), and you might be tempted to write a code generator that reads your database table schemas and generates classes that correspond to the entities in each table (customers, for example).  You would then have the equivalent of an Object-Relational Mapper, arguably a worthy pursuit.

Some programming environments such as Visual Studio have the ability to store code snippets, and even come with a template code generator (T4).  But the point of automation is to save time.  Consult this chart first, before writing the template:

http://xkcd.com/1205/

Title: Main method templating


问:
Is Pair Programming also used to train less experienced developers and bring them up to speed?
I am familiar with Agile and Pair Programming (http://en.wikipedia.org/wiki/Pair_programming).  I thought Pair Programming was used if there was a complex requirement i.e. two sets of eyes is better than one.

Is Pair Programming also used to train less experienced developers and bring them up to speed?

Also, how often is it used e.g. all the time i.e. the two developers will work together at one screen permanently or perhaps one day per week? I have read an Agile book, which talks about this concept but it does not mention frequency of use.

答:
I use PP in my work in a similar way -  with newcomers (not necessarily unexperienced pragrammers). Usually this is one week period. After this all the goals listed below are usually met.

Goals:

Period of familiarization of a newcomer with the code base will be significantly reduced. When you need a man to be involved in your project and to get a result in two weeks this works perfectly.

You as a manager will understand how a man thinks. This will help you to work out an approach to work with him.

Newcomer will have an introduction of a coding culture of the project.

Unexperienced guy will catch how an experienced one works during coding. This will help to understand where to improve.

Experienced guy will teach you a couple of nice how-to's.


答:
It's difficult to assess technologies when you don't have deep experience of them, but of course that's exactly when you have to make your decisions, so there's no simple answer to that dilemma.

You cite two concerns: performance and usability. I'll try to address both below.

Firstly, performance. Performance of course depends not only on the language but also on the implementation, and also on the expertise of the users. Different XSLT processors can vary widely in performance, and the same processor can vary widely depending on how it is used (with Saxon, for example, people who have performance problems are very often found to be using it with DOM, which is a poor combination, and performance can increase ten-fold if you use Saxon's native tree model instead). So the first advice is don't take performance on hearsay, measure it; and the second advice is to make sure that the person doing the measuring has enough experience not to make silly mistakes. More easily said than done.

Crudely, you can separate transformation jobs into two categories: simple and complex. For simple transformations, with a good XSLT processor the time is all spent parsing and serializing and the XSLT processing time hardly comes into the picture. Since any other technology is going to incur the same parsing and serialization costs, the choice of transformation technology isn't going to make a big difference (except perhaps very for very low-level coding using streaming, but not many people can afford the programming time and skills needed to implement that). For complex transformations on large documents, you start to get the same issues as with SQL programming: achieving good performance requires good interaction between the skills and knowledge of the programmer, and the capabilities of the optimizer. As with SQL, it's very easy in such a high-level language to write a few simple statements that result in the processor having to do a very large amount of work. But also as with SQL, programmers who know what they are doing will do much better than novices.

Second, usability. The XML-based syntax for XSLT is very off-putting to a lot of people on first encounter with the language. But there are good reasons and real benefits for doing it this way: there is the "template" argument, that a lot of the code consists of XML to be written to the result document, and the best way to write XML is in XML. And there is the "reflection" argument; in large complex systems, it is very common to find stylesheets that generate stylesheets. Then there is the "tools" argument; if you are in an XML shop, you probably have a lot of XML tooling such as syntax-directed editors, and it's good to be able to use the same tools to handle your programs and your data. The disadvantages turn out to be fairly cosmetic in comparison: there's the number of keystrokes involved in editing (easily fixed with a good editing tool), and there's the verbosity of the code (reducing its readability). The verbosity is vastly reduced in XSLT 2.0 with the introduction of features such as regular expressions and stylesheet functions: many stylesheets are reduced to a half or a third in size when they take full advantage of XSLT 2.0.

Your mention of DSSSL leaves me with a wry smile. I've never used DSSSL, but the stories I heard were that it was unsuceessful because its syntax was arcane, and unrelated to the syntax of the data (SGML). The use of an XML syntax for XSLT was strongly motivated by experience with DSSSL.

There are people who love XSLT and there are people who hate it. Unsurprisingly, those who use it a lot tend to fall into the first category. Those who dislike it are generally those who haven't learnt to "think the XSLT way". You could argue that a programming language shouldn't affect the way you think, but it does: writing in a rule-based language takes a different mindset from writing in an imperative language. The first reaction of many programmers is that they feel less in control (describing the problem, rather than telling the computer what to do step by step). It's very similar to the reaction you used to see when people were first introduced to SQL. These days, people learn SQL earlier in their careers so there's less mental readjustment required.

Ultimately, you should choose a technology based on objective measurable criteria, not on love/hate reactions. It's difficult to make those measurements. But there are lots of people using XSLT very intensively and very successfully, so there is no doubt that it can be done.

Title: XSLT and possible alternatives


问:
Update strategy for a software framework once it has been deployed
I need to update a software framework once it has been deployed.

The framework we are creating is made up of .NET 4.0 libraries (in Visual Studio). This common set of code libraries will be available for 2 .NET Windows services, a standalone .NET application, and a .NET MVC 4 website. (The services will run on a single server, and the standalone application will be used by a select few individuals.)

We are in the early stages of the project, and the big questions that have come up are:

What happens when we have to make a change to 1 or more of the framework files?

How do we deploy patches and/or updates to each part that relies on the framework?

What considerations can we make early on to make the update/patching process easier later on?

This is the first time our small team has tackled a problem like this and we're not sure what the best practices are.

edit

We have 4 software pieces that rely on the framework: 2 services, 1 app, 1 website. Once this all hits production, there are already upgrades and updates planned. The updates will require changes to the framework files and the programs. My question was intended to refer to that later process of redeploying the upgrades. Once we're in production, and we've coded the updates/upgrades to the framework files, the applications, and the website, deploying those updates will need to happen as quickly as possible. What do we need to do to streamline that process?

答:
Edited to reflect comments:

For development you want Nuget...

You can easily run your own nuget repository (can be a folder, TeamCity has one built in, etc).

Build the libraries with a self contained suites of tests, use semantic versioning, update and deploy at will - semver and the nuget systems will give you enough control to avoid updates you want to defer for a given application.

The rest hangs off standard good practice - automate your deployments up front (ideally be able to spin up desired state for your servers automatically), run a build server, automated tests at many levels... it should then all "just work" (-:

So - following comments - the key in the above is automate your deployments. For websites this is generally not particularly hard, there are a wide variety of options (I have had success with WebDeploy but my needs are not complex). For applications you can look at ClickOnce or variations thereon (or at things like windows store apps that are geared to automated updates). the services are probably the hardest to automate deployment for, but again there's scope within MSDeploy as well as other systems. The other big issue tends to be database schemas - but migrations (that's the key word!) can be automated so its not a show stopper and if you start on the basis that your schema changes are automated then you'll have a high level of confidence in any given instance of that schema being what you expect it to be.

The more you're able to automate your deployment processes up front the less stressful the whole process is liable to be (because its trivial to set up a test/qa/staging environment) - especially if you remember to regularly test both clean deployments and updates.

Again I have to confess to being a some way from this happy state for some of the stuff I look after - but that's kinda why I understand the desirability of getting there.


问:
Why isn't `length` generic by default?
Haskell often provides two versions of a given function f, i.e:

```<code>f :: Int ...
genericF :: Integral i => i ...
</code>```

There exist many standard library functions with those two versions: length, take, drop, etc.

Quoting the description of genericLength:

The genericLength function is an overloaded version of length. In particular, instead of returning an Int, it returns any type which is an instance of Num. It is, however, less efficient than length.

My question is: where does the efficiency loss comes from? Can't the compiler detect that we are using genericLength as an Int and therefore us length for better performance? Why isn't length generic by default?

答:
It's the same reason as why we have map and fmap. Error messages/usability for newbies.

It'd by mighty confusing for many a new programmer to write

```<code>myLength = subtract 1 . genericLength

x = myLength [1, 2, 3] :: Int
y = myLength [1, 2, 3] :: Integer
</code>```

and get an error complaining about the monomorphism restriction. Plus which do you prefer

```<code>Couldn't match expected type "Integer" with type "Bool"
</code>```

or

```<code>No instance for Num Bool arising from usage ....
</code>```

It's simply a matter of usability.

Furthermore, in a lot of cases you end up just wanting defaulting anyways, such as with function composition

```<code>evenElems = even . subtract 1 . genericLength
</code>```

vs

```<code>default ()
evenElems = even . genericLength -- Error ambiguous type variable.
</code>```

Here we just want GHC to "pick" a random Num type and we really don't care which (it's Integer IIRC).

If everything was fully generic the defaulting rules would get um.. murky. Since  As of right now there are only 4 things that are automatically available as defaults and no way to set anything fine grained (per function).

As for efficiency, typeclasses means lugging potentially lugging typeclass's dictionary and defaulting to Integer which is much more expensive than Int.

There are alternative preludes (I think classy prelude is unmaintained, but interesting) that do attempt to be as generic as possible. Using them is as simple as

```<code> {- LANGUAGE NoImplicitPrelude #-}
 import My.Super.Awesome.Prelude
</code>```

Title: Why isn't `length` generic by default?

Body:
It's the same reason as why we have map and fmap. Error messages/usability for newbies.

It'd by mighty confusing for many a new programmer to write

myLength = subtract 1 . genericLength

x = myLength [1, 2, 3] :: Int
y = myLength [1, 2, 3] :: Integer

and get an error complaining about the monomorphism restriction. Plus which do you prefer

Couldn't match expected type "Integer" with type "Bool"

or

No instance for Num Bool arising from usage ....

It's simply a matter of usability.

Furthermore, in a lot of cases you end up just wanting defaulting anyways, such as with function composition

evenElems = even . subtract 1 . genericLength

vs

default ()
evenElems = even . genericLength -- Error ambiguous type variable.

Here we just want GHC to "pick" a random Num type and we really don't care which (it's Integer IIRC).

If everything was fully generic the defaulting rules would get um.. murky. Since  As of right now there are only 4 things that are automatically available as defaults and no way to set anything fine grained (per function).

As for efficiency, typeclasses means lugging potentially lugging typeclass's dictionary and defaulting to Integer which is much more expensive than Int.

There are alternative preludes (I think classy prelude is unmaintained, but interesting) that do attempt to be as generic as possible. Using them is as simple as

 {- LANGUAGE NoImplicitPrelude #-}
 import My.Super.Awesome.Prelude


问:
Object Oriented Programming Concepts and Interviews
I'm an Object Oriented Programming fanatic. I have always believed in modelling solutions in terms of objects. It is something that comes to me naturally. I work with a services start up that essentially works on application development using OOP languages. So I tend to test understanding of OOP in the candidate being interviewed.

To my shock, I found very very few developers who really understood OOP. Most candidates brainlessly spit out definitions they mugged up from some academic book on object oriented programming but they don't know squat about what they are saying. Needless to say I reject these candidates. However, over the course of time, I ended up rejecting almost 98% of the candidates. Now this gets me thinking if I'm being over critical about their OOP skills. I still believe OOP is fundamental and every programmer MUST GET it. Language knowledge and experience is secondary.

Do you think I'm being over critical or do I just get to interview bad programmers unfortunately?

EDIT:

I usually interview programmers with 2 to 5 years of experience. The position that I usually interview for is Ruby/Ruby on Rails application developer.

答:
If you interviewed a fresh graduate, than you absolutely too critical.

I think what is important for a fresh graduate related to OOP are: medium - deep OOP knowledge, interest in programming and OOP, hard worker and some OOP college assignment. Some fresh graduates are lack of OOP experience in medium - large project. So I think a medium knowledge and interest in OOP will be enough.


答:
There is no need for a convention.  Local functions are not exposed to the rest of the code, so nothing anybody else writes will care about it.  I say choose something that makes sense in context, rather than worry about a convention which may work well in one place, not in another.

Here is a tail-recursive fibonacci implementation:

```<code>def fib (n: Long): Long = {
  def loop(current: Long, next: => Long, iteration: Long): Long = {
    if (n == iteration)
      current
    else
      loop(next, current + next, iteration + 1)
  }
  loop(0, 1, 0)
}
</code>```

I could have called it fibloop, but I don't really think that adds anything. It's not accessible anywhere else, so why bother "namespacing" it?  Perhaps calling it forwardloop might be clearer, but not fibloop.  If anything, calling it loop emphasises that it is local.

If your methods/functions are so long that you've forgotten where a helper/local function was defined by the time you see it again, I could see the need for a naming convention (although if the function is named so as to make its purpose clear, how often will it matter?).  Personally, I try to avoid writing anything that verbose, but if you do, then I suggest you save special conventions for those methods where this actually becomes a problem.  Even then, I bet a well chosen name will be more helpful than any number of underscores.

If a method is succinct enough, (and the local function also simple) I confess I sometimes use a function literal just to avoid having to worry about the name.

Now, you might counter that prefixing local functions with an underscore definitively avoids the possibility of shadowing an external function.  To which I would respond by asking what happens if you have a local function inside another local function?  Use two underscores?  If you re-organise your code, how much search-and-replace are you prepared to do, to chase after this problem you created for yourself?

Title: How to name nested function?

Body:
When you have a function that wraps another one in Scala. What do you call the nested function?

I found this :

```<code>def factorial(i: Int): Int = {

  def fact(i: Int, accumulator: Int): Int = {
     if (i <= 1)
        accumulator
     else
        fact(i - 1, i * accumulator)
  }

  fact(i, 1)

}
</code>```

I usually use just do because it is shorter, generic, and explicit. But is there a better way or a naming convention for nested functions?

```<code>def myFunction() = {

  def do(i: Int) = {
    ...
  }
  do(1)

}
</code>```

Body:
There is no need for a convention.  Local functions are not exposed to the rest of the code, so nothing anybody else writes will care about it.  I say choose something that makes sense in context, rather than worry about a convention which may work well in one place, not in another.

Here is a tail-recursive fibonacci implementation:

def fib (n: Long): Long = {
  def loop(current: Long, next: => Long, iteration: Long): Long = {
    if (n == iteration)
      current
    else
      loop(next, current + next, iteration + 1)
  }
  loop(0, 1, 0)
}

I could have called it fibloop, but I don't really think that adds anything. It's not accessible anywhere else, so why bother "namespacing" it?  Perhaps calling it forwardloop might be clearer, but not fibloop.  If anything, calling it loop emphasises that it is local.

If your methods/functions are so long that you've forgotten where a helper/local function was defined by the time you see it again, I could see the need for a naming convention (although if the function is named so as to make its purpose clear, how often will it matter?).  Personally, I try to avoid writing anything that verbose, but if you do, then I suggest you save special conventions for those methods where this actually becomes a problem.  Even then, I bet a well chosen name will be more helpful than any number of underscores.

If a method is succinct enough, (and the local function also simple) I confess I sometimes use a function literal just to avoid having to worry about the name.

Now, you might counter that prefixing local functions with an underscore definitively avoids the possibility of shadowing an external function.  To which I would respond by asking what happens if you have a local function inside another local function?  Use two underscores?  If you re-organise your code, how much search-and-replace are you prepared to do, to chase after this problem you created for yourself?


问:
help in theory regarding prefix_suffix_set
I found this question at codility.com, but I don't understand the question. Can you help me figure out what do they want? I am more interested in the theory than a code.

A non-empty zero-indexed array A consisting of N integers is given. A prefix_suffix_set is a pair of indices (P, S) such that 0 ≤ P, S < N and such that:

every value that occurs in the sequence A[0], A[1], ..., A[P] also occurs in the sequence A[S], A[S + 1], ..., A[N − 1],

every value that occurs in the sequence A[S], A[S + 1], ..., A[N − 1] also occurs in the sequence A[0], A[1], ..., A[P].

The goal is to calculate the number of prefix_suffix_sets in the array. For example, consider array A such that:

A[0] = 3

A[1] = 5

A[2] = 7

A[3] = 3

A[4] = 3

A[5] = 5

There are exactly fourteen prefix_suffix_sets: (1, 4), (1, 3), (2, 2), (2, 1), (2, 0), (3, 2), (3, 1), (3, 0), (4, 2), (4, 1), (4, 0), (5, 2), (5, 1), (5, 0).

Write a function:

function solution(A);

that, given a non-empty zero-indexed array A of N integers, returns the number of prefix_suffix_sets.

答:
If I read things correctly:

(1,4) designates the portion of the array

```
i   0 1 2 3 4 5
A   3 5 7 3 3 5
p/s p p     s s
```

In this set, everything that occurs in A[0..1] also occurs in A[4..5].

The set is not concerned with the multiplicity of a number (1,3) shows:

```
i   0 1 2 3 4 5
A   3 5 7 3 3 5
p/s p p   s s s
```

3 occurs twice in the 's' set and once in the 'p' set.

These can be overlapping (2,2)

```
i   0 1 2 3 4 5
A   3 5 7 3 3 5
p   p p p
        s s s s
```

and (2,1)

```
i   0 1 2 3 4 5
A   3 5 7 3 3 5
p   p p p
      s s s s s
```

The question is asking "how many of these pairings (suffix and prefix) exist where the set of numbers in the prefix part of the array matches the set of numbers in the suffix part of the array?"

Body:
If I read things correctly:

(1,4) designates the portion of the array

i   0 1 2 3 4 5
A   3 5 7 3 3 5
p/s p p     s s

In this set, everything that occurs in A[0..1] also occurs in A[4..5].

The set is not concerned with the multiplicity of a number (1,3) shows:

i   0 1 2 3 4 5
A   3 5 7 3 3 5
p/s p p   s s s

3 occurs twice in the 's' set and once in the 'p' set.

These can be overlapping (2,2)

i   0 1 2 3 4 5
A   3 5 7 3 3 5
p   p p p
        s s s s

and (2,1)

i   0 1 2 3 4 5
A   3 5 7 3 3 5
p   p p p
      s s s s s

The question is asking "how many of these pairings (suffix and prefix) exist where the set of numbers in the prefix part of the array matches the set of numbers in the suffix part of the array?"


问:
Why does Java not put the filename in args?
In C and C++, the main method holds the filename in the first position of the array at argv[0]. In Java, however, the filename is not included in the args string array.

Is there a practical reason for this? I understand that this makes iterating through command line arguments 0-based instead of 1-based, but is there a benefit? Was the filename just deemed to be useless?

答:
In some cases a program can be run in different ways and exhibit different behavior on how it is called.  If you call vim as vi, it runs in a compatibility mode.  Sometimes it is to try to maintain one version of several related programs - for example mailq and newaliases on many unix systems are a link to sendmail so that these programs stay in sync)

Java programs are typically invoked as:

```
% java -jar foo.jar args
% java Foo args
```

The first version is where you have a Manifest file that indicates the main class, the second version runs the main method in the class Foo found in the class path.

The information presented for Java is either a path to the jar or the name of the class being invoked.

The location of the jar isn't important enough to be something to code from (and was actually not part of the original spec).  A Jar can be named anything really, and often includes version numbers.  Whats more, there's no guarantee that the class was even stored in a .jar (it could have been extracted).

Invoking a Java application with -jar has only one way to enter it - the class defined in the Manifest.  There's no renaming that can be done.

The other option, of invoking it with the class name points directly to the execution unit.  Furthemore, it can't be named multiply - you can't have Bar.class be the code for class Foo it just doesn't work that way.

This should show that there's really no point to passing the information of argv[0] in the C sense to a Java application - its either going to be java, meaningless and arbitrary, or the name of the class that is being invoked (that you are already executing code out of (you could do something like getClass().getEnclosingClass().getName() if you were desperate...)).

There is a point here, you can define multiple Main methods in classes in a .jar or on the class path.  And you could have them behave differently just as if there was a series of if statements based on what argv[0] was.

I have in the past had code akin to java -cp Foo.jar com.me.foo.Test which invoked the Test class's Main method rather than the one defined in the one defined in the Manifest.

Body:
In some cases a program can be run in different ways and exhibit different behavior on how it is called.  If you call vim as vi, it runs in a compatibility mode.  Sometimes it is to try to maintain one version of several related programs - for example mailq and newaliases on many unix systems are a link to sendmail so that these programs stay in sync)

Java programs are typically invoked as:

% java -jar foo.jar args
% java Foo args

The first version is where you have a Manifest file that indicates the main class, the second version runs the main method in the class Foo found in the class path.

The information presented for Java is either a path to the jar or the name of the class being invoked.

The location of the jar isn't important enough to be something to code from (and was actually not part of the original spec).  A Jar can be named anything really, and often includes version numbers.  Whats more, there's no guarantee that the class was even stored in a .jar (it could have been extracted).

Invoking a Java application with -jar has only one way to enter it - the class defined in the Manifest.  There's no renaming that can be done.

The other option, of invoking it with the class name points directly to the execution unit.  Furthemore, it can't be named multiply - you can't have Bar.class be the code for class Foo it just doesn't work that way.

This should show that there's really no point to passing the information of argv[0] in the C sense to a Java application - its either going to be java, meaningless and arbitrary, or the name of the class that is being invoked (that you are already executing code out of (you could do something like getClass().getEnclosingClass().getName() if you were desperate...)).

There is a point here, you can define multiple Main methods in classes in a .jar or on the class path.  And you could have them behave differently just as if there was a series of if statements based on what argv[0] was.

I have in the past had code akin to java -cp Foo.jar com.me.foo.Test which invoked the Test class's Main method rather than the one defined in the one defined in the Manifest.


问:
things to think of when moving into C-land
Hello

Over the years have I made a programming journey from C in 1990 to Pascal, C++ with I programmed commercially, java VHDL, C# and now I'm taking a look on F#.

In the spring I will go back to study embedded programming in C in a university course so before I do that I will refresh my knowledge in C.

I don't remember much of the C that I learnt and I think I am thankful for that for probably learned some bad habits back then.

I have some questions to get me on the way.

--edit--

To clarify: I am thankful for tips that have been given regarding embedded programming but now I am more interested in relearning C in general. Sorry if my question was unclear,

Compiler, Debugger, IDE? As a microslave I was thinking about 2010 C++ Express, any alternatives?

Where do you find good libraries with code for C. I'm thinking something similar to Boost, POCO in C++

Source for procedural programming patterns and best practices. Where can you find good code learn from?

Thanks in advance

Gorgen

答:
In terms of an IDE to use, I'm a big fan of using Microsoft's IDE products for EDITING files, but using Makefiles and gcc to compile.

I know you've indicated you're interested in non-embedded specific stuff, but your library and compiler questions are still influenced by what you're going to be doing.

As such, I'd definately be thinking against linking against uClibc for embedded programming:
http://www.uclibc.org/

If you're not targeting x86, you'll want to think about your cross-compile environment - I've been looking at some options for this recently, and it looks like scratchbox might be the best way to go, but YMMV:
http://www.scratchbox.org/

Besides that, you shouldn't really have to 're-learn' C, rather just look at changing up your toolchain for the specific task at hand.

Hope this helps.


答: actually there's no benefit with it, it really depends on the syntax of the programming language you are using if it is 0-based or 1-based. the variable (you refer to as filename) also depends on the language, it can be different in other languages just follow the correct syntax of the language you are using. </p>

Title: Why does Java not put the filename in args?

Body:
In C and C++, the main method holds the filename in the first position of the array at argv[0]. In Java, however, the filename is not included in the args string array.

Is there a practical reason for this? I understand that this makes iterating through command line arguments 0-based instead of 1-based, but is there a benefit? Was the filename just deemed to be useless?


问:
When is it okay to log filename/line information for errors?
We have a closed-source commercial C++ application. Some of our logged error messages are in plain English like "ERROR: could not read file 'foo'". While others use a macro to print filename/line information like ""SplineReticulator.cpp(423): out of bounds". This is not an assert or a crash, the application recovers fine, but it's an error we want to log.

What is a good rule of thumb when plain-English error message is appropriate vs. a filename/line one? Or are filename/line type errors even appropriate for closed-source commercial software? We've heard the argument they are unprofessional looking, but they are handy for debugging.

答:
If your application produces a log file, then put all your module name/line number stuff in there. The errors for the user should be in plain $usersLocalLanguage whenever possible. If you need the detailed info while trouble-shooting a client's problem, you can get the user to email the log file to you, and dissect that all you want.

If you don't have a log file, then you might want to have a dialogue box that has a simple error for the user, and then a "details" panel (closed, by default) where they can copy the tech details (with filename/line number) and paste into an email and send it to you.


问:
Does an in-code enumeration provide a stronger domain model than a static table?
Does an in-code enumeration provide a stronger domain model than a static database table?

As an example, say I have an Marble entity, with a Color attribute. The color attribute has a finite set of possible values—say red, green, blue. Say the database team recommends having a static S_ValidColors table, to the effect of:

```<code>-----------------------
| ColorId | ColorName |
-----------------------
|    0    |    Red    |
-----------------------
|    1    |   Green   |
-----------------------
|    2    |    Blue   |
-----------------------
</code>```

Whereas I'm thinking more along the lines of (this is just a sketch for the general concept):

public class Color {
    public static const Color Red = Color(0);
    public static const Color Green = Color(1);
    public static const Color Blue = Color(2);

    private Color(uint typeCode) {
        ...
    }
    ...
}
```

Aside from the question of which is better (which probably depends on any number of other factors not represented here), is this a question that touches how strong the domain model is? Is one way more anemic than the other?

答:
We had exactly same discussion few years back at my old work. In the end, we choose the 2nd option. The reasoning is :

When you change something in DB, you expect those changes to work without having to re-deploy the application. But in case of these kind of enumerations, the code might depend on the fact, that there are exact values for this enumeration. Lets say you have switch that uses this enumeration and if invalid value is provided, it throws an exception. By having the values hard-coded, you can ensure your code doesn't cause errors around those enums. Even when some "clever" administrator decides to add their own values.

Of course, this depends. If you are only working with list of all values, then this doesn't really make sense. But it does make sense if you work with specific individual values in your code.

Also, having to read those values from DB can impact performance or create complex code, even thought they are not really changing.