答:
Trying to go against the team's current decisions on a continuous basis is harming the viability of your ideas, regardless of their value.

You have to realize you're struggling with the Overton window, and this is essentially a political battle, not a rational debate. If it were rational, you would have agreed long ago with the team on a good practice.

The trick with getting your ideas accepted is to take a long game approach to move the Overton window:

Initially, you must label yourself "reasonable" in the minds of others. This means adopting current team practice and generally being a "reasonable person". You may offer doubts about these practices, but you cannot refuse them if the team currently feels they are reasonable.

Once you're reasonable in the minds of others, you can start offering your ideas to the team. They will gain credibility because you have gained credibility (it shouldn't work this way, but it does). Gradually you will broaden the window of acceptable ideas to include your own. In this phase you still do not try to force a change in practice, merely make such a change seem like a "reasonable" idea. Repetition of ideas is key here, because each repetition makes the idea seem slightly more reasonable.

In the last phase, you abuse people's inability to pay attention in a balanced way. You have to put negative consequences of current practice front and center of their attention plane, while putting risks of your approach far outside of it (do this by changing the subject of conversation to what you need it to be). Eventually, the team will itself decide that your idea is far better than the current approach. It will become democratically adopted without you having to force your will on anyone, and without ever needing to rationally demonstrate superiority of the idea.

This is how politicians and lobbyists operate. Make no mistake; office politics are just like regular politics. Think like a lobbyist and you can force the hand of those in power without ever confronting them.

Ofcourse, all of this only applies to dysfunctional teams. If you're in a cohesive team run by a good manager (who knows his job is not to tell people what to do, but to allow them to do it), then none of the above applies. If you're not in such a team, consider switching jobs.


问:
Is there an accepted name for a fake object injected via a preprocessor seam?
I am dealing with some old, sloppy C++ code in which there is a structure with a lot of data members and functions. I want to test a class that I have implemented which uses the struct, but this dependency is going to make the unit tests extremely ugly. Inspired by Michael Feather's discussion of preprocessing seams in Working Effectively with Legacy Code, I am getting ready to solve this problem by faking the ugly structure with the preprocessor (not with inheritance) polymorphism as demonstrated in the following notional code.

test.cpp

```<code>#include <iostream>
#include "NotAsUgly.hpp"
#include "DependsOnUgly.hpp"
int main() {
    std::cout << DependsOnUgly().getDescription() << std::endl;
}
</code>```

DependsOnUgly.hpp

```<code>#ifndef _DEPENDS_ON_UGLY_HPP_
#define _DEPENDS_ON_UGLY_HPP_
#include <string>
#include "Ugly.hpp"
class DependsOnUgly {
public:
    std::string getDescription() {
        return "Depends on " + Ugly().getName();
    }
};
#endif
</code>```

Ugly.hpp

```<code>#ifndef _UGLY_HPP_
#define _UGLY_HPP_
struct Ugly {
    double a, b, ..., z;
    void extraneousFunction { ... }
    std::string getName() { return "Ugly"; }
};
#endif
</code>```

NotAsUgly.hpp

```<code>#ifndef _UGLY_HPP_ // Same name as in Ugly.hpp---deliberately!
#define _UGLY_HPP_
struct Ugly { // Once again, duplicate name is deliberate
    std::string getName() { return "not as ugly"; } // All that DependsOnUgly depends on
};
#endif
</code>```

Is there a special name for the type of fake object I'm using here? I'm inclined to call it a stub, but it is rather different than what I would normally think of as a stub. I would expect something called a stub to implement the interface of the class which is to be faked through inheritance. Here the implementation is only partial, and happens through the preprocessor.

Is there already a known name for this kind of fake/testing object? I want to name the header file that contains it (NotAsUgly.hpp in my example) to properly signify to other developers what it is for.

答:
"Mock Object" is a common term.

Fake objects commonly provide a set of method stubs, returning pre-set values.

Mock objects commonly are richer in their behaviour, mimicking a more complete set of the real object behaviour.

ContentLicense: CC BY-SA 3.0


问:
C# Classes instance members vs. enum
What is the difference between private variables in a clsClass type and using enumeration enum to instantiate the variable. This question arose when I was looking at some C# Class code for serial ports. example:  private int SomeClassMember; and                         private enum TransmissionType{TEXT,HEX} ?

Where do the enum statements appear in a Class definition?

答:
Adding to Eldritch Conundrum's answer  (since he has not updated it):

In C#, enums can be declared in the same places as classes (which can
  be nested).

In many cases you might indeed be able to replace Enums
by simple constants or static classes with public constants, but there is more to Enums than meets the eye.

Intellisense (= auto completion in VS, MonoDevelop, etc...) provides support
for enums, it does not do so for constants.

You should use enums to enforce strong typing on parameters, properties and return values
that represent a set of values. The set of values should be closed, not subject to constant change.

You can extend enums:

Taken from: http://damieng.com/blog/2012/10/29/8-things-you-probably-didnt-know-about-csharp

```<code>public enum Duration { Day, Week, Month };

public static class DurationExtensions
{
    public static DateTime From(this Duration duration, DateTime dateTime)
    {
        switch (duration)
        {
            case Duration.Day:
                return dateTime.AddDays(1);
            case Duration.Week:
                return dateTime.AddDays(7);
            case Duration.Month:
                return dateTime.AddMonths(1);
            default:
                throw new ArgumentOutOfRangeException("duration");
        }
    }
}
</code>```

And of course Enums are usefull for Bitwise comparisons with the [Flags] attribute
and in recent versions of .NET they have a .HasFlag method.

Not really an answer, just some extra info.

Title: C# Classes instance members vs. enum

Body:
Adding to Eldritch Conundrum's answer  (since he has not updated it):

In C#, enums can be declared in the same places as classes (which can
  be nested).

In many cases you might indeed be able to replace Enums
by simple constants or static classes with public constants, but there is more to Enums than meets the eye.

Intellisense (= auto completion in VS, MonoDevelop, etc...) provides support
for enums, it does not do so for constants.

You should use enums to enforce strong typing on parameters, properties and return values
that represent a set of values. The set of values should be closed, not subject to constant change.

You can extend enums:

Taken from: http://damieng.com/blog/2012/10/29/8-things-you-probably-didnt-know-about-csharp

public enum Duration { Day, Week, Month };

public static class DurationExtensions
{
    public static DateTime From(this Duration duration, DateTime dateTime)
    {
        switch (duration)
        {
            case Duration.Day:
                return dateTime.AddDays(1);
            case Duration.Week:
                return dateTime.AddDays(7);
            case Duration.Month:
                return dateTime.AddMonths(1);
            default:
                throw new ArgumentOutOfRangeException("duration");
        }
    }
}

And of course Enums are usefull for Bitwise comparisons with the [Flags] attribute
and in recent versions of .NET they have a .HasFlag method.

Not really an answer, just some extra info.


问:
Should you version web applications?
I've recently had a discussion with a coworker about versioning web applications.

I don't think you need it at all, and if you just want a sanity check to confirm your latest release is live, I think a date (YYMMDD) is probably good enough.

Am I off base?  Am I missing the point?  Should I use web application version numbers

答:
Yes you should. For distribution reasons pointed here by other answers.

But I see, why you asking the question. Web apps approach is cost driven. Its opposite to legacy shrinkwrap approach, where costs include physical media, distribution, installation, hardcopy of documentation, training and technical support. Anything which can be excluded, should be excluded.

ContentLicense: CC BY-SA 2.5

Title: Should you version web applications?


问:
"Public APIs are forever: Only one chance to get it right"?
In an OS book I just read that, "Public APIs are forever: Only one chance to get it right". Is it true? Is it applicable only in APIs of Operating Systems or other APIs too? For example, will this be true for the APIs of Android Applications such as Tasker, Locale and Pushover?</p>

答: Although all what we do is to make 'em best at one go, but since time change and improvement comes, sometimes we need to update the information, as many of giant providors have been doing, (like face book several update, twitter one major turning to oAuth and several major, but at most possible all comes with improvement so no frequent changes. And Yes please don't stop supporting older one, It hurts!! :)</p>


问:
Compile GPL-code into a JNI-capable shared library and use it in commercial software
I am developing an application for Android in JAVA which calls GPLed C-code via JNI.

I have modified & capsulated a GPL-software under a JNI-interface and compile it as a shared library (.so) which I can use via JNI from my JAVA-part (the commercial part with closed source).

Because I have stripped the original GPL-software from everything which is not needed by my software, that GPL-software has no more other GPL-dependencies which explicitly forbid using it as a shared library in a closed-source software (like SecretRabbitCode for example forbids it).

I have no problem to set my modified version of the GPL-software online, but I cannot do this with my commercial software.

Because I need the modified version of the GPL-software in my software, I have to bundle it in one package (a APK-file in Android).

Sadly, the GPL-software has 1 or 2 more dependencies to GPL-code (just C-files like aes.c), so it's not as easy as just ask the author of this GPL-software.

Because the Android-way of "packing JAVA and .so-files together, bundle it and distribute it" is quite new, it's not as easy as with pure JAVA or pure C code.

Who can help out?

答: You will have to release your entire Software under the GPL, otherwise you'll be violating the terms of the license. A JNI wrapper most emphatically does not isolate you from the requirements of the GPL.</p>


问:
Why aren't design patterns added to the languages constructs?
Recently I was talking with a colleague who mentioned that his company was working on adding the MVC design pattern as a PHP extension.

He explained that they wrote C code for adding Controllers, Models and Views to the language constructs to increase performance.

Now I know that MVC is an architectural design pattern that is used widely in web applications, but I still have to come across languages that have a language construct for Controllers for example.

IMHO integrating design patterns into a language can emphasize the importance of good OO design.

So, Why aren't the most used design patterns (MVC, Factory, Strategy,...etc.) added to the language constructs?

If the question sounds too broad then you may limit the question to PHP only.

Edit:

I'm not implying that one must use a design pattern when developing a project. Actually I promote the methodology of keep it simple as long as it works.

答:
Eh, stale question but I disagree with a lot of the answers depending on where you set "Design Patterns" on the semantics dial including the accepted one.

In the GoF Design Patterns book sense, I would say it depends. MVC, for instance (not actually a GoF pattern but fits that mold), is totally inappropriate to express as language constructs for mass consumption (although it might make sense for a specific PHP project). As an architectural pattern there are constant variations on the theme and a wide variety of perfectly legit interpretations on it for different circumstances (although many depart so far from MVC they probably shouldn't call it MVC anymore). For instance, on the web, the http barrier makes it a somewhat awkward fit depending on whether you're trying to include the client-side (no doubt painfully) in the equation and what you're considering "the view" from a more appropriately strictly server-side perspective.

Iterator on the other hand is a highly general concept that can be applied in a very wide variety of ways to a wide variety of constructs.

Where the line should be drawn on whether something belongs in a core language design, even in a server-side-web-specific-language, IMO, is the point where something crosses the line from making it easier to do an incalculable number of things more easily vs. doing an overly specific yet broadly implemented thing like an architecture pattern for you.


问:
Strategy for website with international strings
What things need to be considered for a Website that contains International strings, for instance Simplified Chinese and English mixed.

UTF8 seems to me a natural choice, including a meta tag.  Still, some users may only see white boxes.  What is the best solution do deal with this?

Currently I am thinking to provide an alternative image-based rendering, or even make it default.  But IMHO this seems a weak solution.  Or I could tell the user which OS/Browser combinations are known to work but such a list would probably be endless.

Update: it's a Chinese learning site, most users will not have visited Chinese websites before

答:
You can use fonts hosted on your server (or some font CDN) with css:

```<code> @font-face {
    font-family: SomeName;
    src: url(SomeUrl.ttf) format("truetype");
 }
</code>```

which can then be used like any other font with font-family:'SomeName';.

So you need to find a Chinese font with an acceptable license, and host it on your server. Being careful about the license is important, using unlicensed commercial fonts can be expensive.

Body:
You can use fonts hosted on your server (or some font CDN) with css:

 @font-face {
    font-family: SomeName;
    src: url(SomeUrl.ttf) format("truetype");
 }

which can then be used like any other font with font-family:'SomeName';.

So you need to find a Chinese font with an acceptable license, and host it on your server. Being careful about the license is important, using unlicensed commercial fonts can be expensive.


答:
APIs always change, otherwise what would be the point of system upgrade? Changing internals only?

Each version of system brings new APIs, old APIs become obsolete and obsolete APIs disappear.

API change only has to be very careful both technically and in terms of communication.

Title: "Public APIs are forever: Only one chance to get it right"?

Body: In an OS book I just read that, "Public APIs are forever: Only one chance to get it right". Is it true? Is it applicable only in APIs of Operating Systems or other APIs too? For example, will this be true for the APIs of Android Applications such as Tasker, Locale and Pushover?</p>


问:
Do I have to include the license of a third party library imported as a DLL?
I have code using a third party library, QrCode.Net, in the form of a dll file.

The library is licensed under the MIT License.

Do I have to include the license in my project if I did not use or modify the source code?

Full license text:

The MIT License (MIT)

Copyright (c) 2011 George Mamaladze

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

答:
If you distribute the QrCode.Net DLL as part of your project, then yes, you have to distribute the licence text along with it.

If you use the QrCode.Net DLL, but you don't distribute it (instead, you tell your users to get it from somewhere else, then you don't have to include the MIT licence in your project, as you are not distributing anything uder it (assuming your code uses a different licence).


问:
JavaScript...what to unit test
I would like to hear other people's opinion on what to unit test in JavaScript. I've been thinking about it and experimenting and let me present what seems to me the right thing. First of all, in order to be able to unit test your production code you need to divide the productin code into three layers: (1) DOM/jQuery, (2) Logic, and (3) AJAX. Refer to the attached image.

The Logic layer sits between the DOM/jQuery layer and the AJAX layer, that is, the DOM/jQuery layer is not tied to the AJAX layer. So, in my opinion the only layer that should be unit tested is the Logic. Writing unit tests should be easy, otherwise programmers will not write them. What is the use of writing unit tests for the DOM/jQuery layer - ok, you've added an li element to an ul element, why do I need to assert that, there should be no if statements there. About the AJAX layer, what's there to assert...the URL that was used was "blah", I know it was "blah". Whatever the data that was obtained in the AJAX layer should be given to the Logic layer. Now, the Logic layer is a different story, for example, in a unit test it can be given data that suppossedly came from an AJAX call, and use a mock DOM/jQuery layer to verify that the data was displayed correctly. Let me know what you think.

答:
Why not Ajax?

That strikes me as a great place to unit test. As a point of entry/egress in and out of a given domain, that's one choke point where it's nice to know your code is going to handle bad data in the best possible way. Ideally, a network hiccup or data problem won't throw the kinds of exceptions that break all the code on your page and give user feedback as appropriate. But I would emphasize live-logging validation here as a strategy first.

Semi-Agreed on the DOM Interface

All you can test for is whether something works when all the HTML is correct. You really can't make assumptions about what your code should do when the HTML is broken because validating for every little DOM operation is way too expensive. Also, breakage is typically so obvious it's a wasted effort anyway. It's better to simply have test pages full of in-production variations on fully functional widgets with automated activation of their various features. If that counts as unit testing then I guess I disagree.

Agreed on Unit Testing Data-Juggling/Data-Formatting/Logic

This is definitely the interior layer where it might make the most sense to focus on some sort of a testing strategy.

But Still Not 100% Sold on Extensive Client-Side Web Unit Testing

I'm on the fence about it primarily because it's obscenely easy to test your code before committing it and issues are typically highly visible on the client-side. If you don't get immediate visual cues you'll see problems in the console.

IMO, the critical thing is to focus on testing for how your code reacts to bad stuff from vectors you don't control like what's coming in from Ajax or JSON dropped in by the server on page load. Regression issues of the whack-a-mole bug variety where one "fix" breaks something elsewhere are something any client-side web developer should be loathe to ever allow into their code in the first place by maintaining clean separations of concerns and hand-testing the crap out of all their work in every browser supported before committing. That takes time and I'd argue time is better spent avoiding the problem in the first place than testing to see if you failed to avoid it. JS's flexibility makes it so easy to reduce complexity that I would tend to argue for automated testing only at key bottlenecks and necessarily highly complex data-handling.

In recent work with a very messy codebase that has mostly not been touched by client-side dev hands the most critical debug time-saver IMO, is first establishing a way to very rapidly rule out whether it actually is a client-side problem. If you're validating all data to and from the server and logging issues (silently in production of course) as they happen, this can be a matter of seconds rather than hours. But that's not unit testing of course, it's validation, which I would argue is more important than unit testing when you can run and diagnose your code in a live environment as easily as we can with client-side web code.

Consider a Mixed Strategy

So I'm not saying it's always a bad idea. I just think that with JavaScript being good at what it's very good at and with development on the client-side web being the unique animal that it is, it's better to put time into avoiding the kinds of needless complexity that makes one worry about regression issues in the first place and focus more on aiding rapid diagnosis of problems in your running environment. Widget test-pages are great. Validation of data ingress/egress and perhaps unit testing of failure handling is great. And when dealing with high complexity for data handling/formatting, unit testing could potentially also be great. But 100% unit testing coverage of any given layer, I would argue, is time/effort that might be better focused elsewhere for a typical client-side web app.

Title: JavaScript...what to unit test


答:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

This bit is pretty clear. You must include this if you include the library. There are no exceptions.

Title: Do I have to include the license of a third party library imported as a DLL?

Body:
I have code using a third party library, QrCode.Net, in the form of a dll file.

The library is licensed under the MIT License.

Do I have to include the license in my project if I did not use or modify the source code?

Full license text:

The MIT License (MIT)

Copyright (c) 2011 George Mamaladze

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


答:
My opinion would be that once released, that 'version' of the API is forever, but you can deprecate it by releasing a '2.0' API (there are several examples where this is happening - currently, I can think of Strava who have released a 2.0 version of an API for development against to consume their services).

The problem is supporting that original API ad infinitum... I guess it depends on the usage of the old API, and what the value of those API consumers hold to you.

Going back to 'the old days' of say Windows 3.x and 9x etc., once release, those OS APIs were done and set.  Now, OS updates are pushed all the time, so new APIs can be released, but I think so long as you are running a particular OS flavor (major release), those APIs would only be added to, never removed... may not be the case for the 'next' major release though.

Hmm, maybe I strayed from the original question intent.


问:
Why five dining philosophers?
I was wondering why the Dining philosophers problem is based on a five philosophers case. Why not four?

I guess that we can observe all unpleasant issues that can occur when discussing five philosophers example also when we are given four thinkers. Is it only for a historical reason then?

答:
Because it's odd, not even. So that you don't try to devise an algorythm that relies on symmetry or forming pairs, and only much later realize it doesn't work for the general case.

This is an opinion; I have no historical knowledge of what crossed the author's mind.

Title: Why five dining philosophers?


问:
Is this a variant of the Module pattern?
What is this pattern called? Is this a variant of the Module pattern? I remember there's disadvantage to this pattern and it's related to memory usage. </p>

```<code>var module = function() {

    this.Alert = function() {
        alert("I'm a public");
    }

    function iamPrivate() {
         alert("not callable because I'm private");
    }
}

var inst = new module();
inst.Alert();
</code>```

答:
I call that basic fundamental JS OOP. You have a function constructor, this.publicMethods and internal/"private" instance properties/methods that aren't exposed externally. The key win there is that it's clear to everyone what is expected to only be used by the instance internally and how the object is expected to be handled by external concerns.

It's very simple, and it works. Where people tend to go wrong with it is when they start doing things Java-bean-style, e.g.

```<code>function PersonConstructor(nameArg){

    var name = nameArg; //redundant since arg is same scope but here for clarity

    this.setName = function(newName){
        name = newName;
    };

    this.getName = function(){ return name; };
}

var jim = new PersonConstructor('Jim');
</code>```

In general programming (barring compensated weaknesses in language design), this is completely irrational, pointless and murders OOP. In JS, you might as well just cut out the cruft and do this:

```<code>var jim = {
    name:'Jim'
}
</code>```

Which of course is entirely okay if all you wanted was a basic data structure and not a proper piece of an OOP-based architecture. That's where Java goes wrong for me personally. When everything has to be in a class people start forgetting the point of the class construct in the first place.

Because after all if you're giving full, direct access to a property, it's just a wide open property and contributes nothing to what OOP gives you which is a clear separation of what data domain an object instance is responsible for and what points of contact other constructs are expected to have with it. It's about signalling intent so that people can understand each other's code better, not somehow magically protecting an object by adding a pointless layer of abstraction that just 100% exposes a property anyway. When you expose everything anyway, objects server as little more than namespaces to loosely group like-methods around and you're right back to the kind of pre-OOP spaghetti where all you're tracking is one method after another which is the thing that OOP was supposed to help you avoid in the first place.

The module pattern used as object constructor doing the same dumb thing, as I understand it here is more like this:

```<code>function PersonFactory(nameArg){

    return (function(){
        var name = nameArg;//also redundant since nameArg would persist anyway
        return {
            getName: function(){ return name; }
            setName: function(newName){ name = newName; }
        }
    })()

}
var jim = PersonFactory('Jim');
</code>```

I don't see the point in doing this. It's basically the same closure/scoping mechanism that gives you  that internal var property but you've lost the ability to apply prototypes to a function constructor. There may be other advantages to the module pattern I haven't read for carefully enough yet but it always struck me as being popular with people for object building who maybe haven't quite figured out JS OOP in it's entirety yet as I've often seen it used to reinvent core language mechanics that already had the problem covered.

At the end of the day {} for the most part (literals and function Constructor-built objects have slight differences in JS) gives you the same result as new Object(). It's just shorthand for creating a basic object with public methods attached in one step. In both cases you don't want to touch the instance's constructor or its prototype. Because it's Object in both cases and everything inherits from an Object instance at the top of the prototype chain. So basically the module pattern used this way is only limiting what you can do with your "constructor."

Body:
I call that basic fundamental JS OOP. You have a function constructor, this.publicMethods and internal/"private" instance properties/methods that aren't exposed externally. The key win there is that it's clear to everyone what is expected to only be used by the instance internally and how the object is expected to be handled by external concerns.

It's very simple, and it works. Where people tend to go wrong with it is when they start doing things Java-bean-style, e.g.

function PersonConstructor(nameArg){

    var name = nameArg; //redundant since arg is same scope but here for clarity

    this.setName = function(newName){
        name = newName;
    };

    this.getName = function(){ return name; };
}

var jim = new PersonConstructor('Jim');

In general programming (barring compensated weaknesses in language design), this is completely irrational, pointless and murders OOP. In JS, you might as well just cut out the cruft and do this:

var jim = {
    name:'Jim'
}

Which of course is entirely okay if all you wanted was a basic data structure and not a proper piece of an OOP-based architecture. That's where Java goes wrong for me personally. When everything has to be in a class people start forgetting the point of the class construct in the first place.

Because after all if you're giving full, direct access to a property, it's just a wide open property and contributes nothing to what OOP gives you which is a clear separation of what data domain an object instance is responsible for and what points of contact other constructs are expected to have with it. It's about signalling intent so that people can understand each other's code better, not somehow magically protecting an object by adding a pointless layer of abstraction that just 100% exposes a property anyway. When you expose everything anyway, objects server as little more than namespaces to loosely group like-methods around and you're right back to the kind of pre-OOP spaghetti where all you're tracking is one method after another which is the thing that OOP was supposed to help you avoid in the first place.

The module pattern used as object constructor doing the same dumb thing, as I understand it here is more like this:

function PersonFactory(nameArg){

    return (function(){
        var name = nameArg;//also redundant since nameArg would persist anyway
        return {
            getName: function(){ return name; }
            setName: function(newName){ name = newName; }
        }
    })()

}
var jim = PersonFactory('Jim');

I don't see the point in doing this. It's basically the same closure/scoping mechanism that gives you  that internal var property but you've lost the ability to apply prototypes to a function constructor. There may be other advantages to the module pattern I haven't read for carefully enough yet but it always struck me as being popular with people for object building who maybe haven't quite figured out JS OOP in it's entirety yet as I've often seen it used to reinvent core language mechanics that already had the problem covered.

At the end of the day {} for the most part (literals and function Constructor-built objects have slight differences in JS) gives you the same result as new Object(). It's just shorthand for creating a basic object with public methods attached in one step. In both cases you don't want to touch the instance's constructor or its prototype. Because it's Object in both cases and everything inherits from an Object instance at the top of the prototype chain. So basically the module pattern used this way is only limiting what you can do with your "constructor."


问:
Avoiding "Smart Guy" Syndrome on Team Projects
A lot of bad practices were being committed at the beginning of a project, and I recognized them and fought against all of them. Since I didn't pick and choose my battles, my boss now assumes anything out of my mouth is an over complicated response, and spends a lot of time defending himself personally, instead of looking out for the best interest of the project.

How do I push the team in the right direction, without waiting four months for everyone to come to the consensus I was trying to get in place all along, or scarring my reputation on the team as a difficult know-it-all?

答: I love the way this was flagged "teamwork", when the question seems to be "how do I make everybody do everything my way and like it?". If that's not really the question you're asking, the answer is very simple. Pick and choose your battles. Compromise. Use actual teamwork to get the team to agree on something, even if they all agree on something you personally feel is a bad practice. Being stubborn and insisting any way other than your way is "bad practice" is just going to get you exactly the reputation you're trying to avoid.</p>


问:
Convert an interpreter to a compiler?
First off, I know this is a question asked by MANY other programmers before me. But I couldn't find any usable resource that could help me.

Well, I'm creating an programming language called "Light" the syntax is comparable to python but it has a strict object-orientated concept.

I have made an interpreter ( in C++ ) for this language yet, my problem is how to turn this into an executable. ( Or simply: how do I make a compiler ? )

Thanks for your attention

P.S.: I've found some links to a very old tutorial but it is in Pascal...

EDIT:
Well, well. Now I have found a suitable tutorial for C++.
About the project: There have been some changes. Now the language is called "Q." ( kju Dot ).

答: The first couple of steps lexing/parsing (and analysis, depending on how that's structured) can be the same. But you will need to convert your representation to a code-generating representation. Typically LLVM is used for hobbyists as it is pretty much the only remotely decent free code-generating library around.</p>

ContentLicense: CC BY-SA 4.0

Title: Convert an interpreter to a compiler?


问:
Should the variable be named Id or ID?
This is a bit pedantic, but I've seen some people use Id as in:

private int userId;
public int getUserId();
```

<p>and others use:</p>

<pre class="lang-cs prettyprint-override"><code>private int userID;
public int getUserID();
</code>```

Is one of these a better name than the other? Why? I've seen this done very inconsistently in large projects. If I were to set a standard which would most people be familiar with? Which is the conventional standard?

答:
First,  eschew abbreviation.

Second, If the abbreviation is super well known, I recommend to use camel case.

That's because you're not need to consider the meaning of that. just treat as a normal word

Title: Should the variable be named Id or ID?


答:
It depends on what kind of API it is (and I am assuming breaking changes, otherwise the statement is obviously not true).

If the caller can choose what version they're using (e.g. with libraries/frameworks that are bundled with the calling application), then changing the API is not a huge problem - but still bad for the reputation of the software. People like to to upgrade seamlessly.

On the other hand, when people cannot keep using the old version of the API (such as with an online service, or things like a browser or OS where running old versions is very undesirable), then changing APIs in an incompatible way is very bad indeed, since it will break all software that uses it and is not updated as well. This imposes a maintenance cost on developers, and they'll hate you for it. And software that isn't maintained and breaks will reflect badly on you as well.

On the gripping hand, there is at least one API provider who constantly introduces breaking changes in the API and is ridiculously successful anyway: Facebook. But they do manage the changes very carefully: there is a published policy, breaking changes are announced and explained at least 90 days beforehand, and developers can choose to activate them early within that timeframe.


答:
If all you really want is an executable, you can append the script to the end of an interpreter executable and have it run that.

See: https://stackoverflow.com/questions/5795446/appending-data-to-an-exe

Alternately, you can just have the interpreter load the code from a file in the same directory as the interpreter and get largely the same result, just with multiple files.

A true compiler would convert the code into some other language and use the compiler for that language. But if you just want to distribute executables, there's no need to do that.

Title: Convert an interpreter to a compiler?

Body:
First off, I know this is a question asked by MANY other programmers before me. But I couldn't find any usable resource that could help me.

Well, I'm creating an programming language called "Light" the syntax is comparable to python but it has a strict object-orientated concept.

I have made an interpreter ( in C++ ) for this language yet, my problem is how to turn this into an executable. ( Or simply: how do I make a compiler ? )

Thanks for your attention

P.S.: I've found some links to a very old tutorial but it is in Pascal...

EDIT:
Well, well. Now I have found a suitable tutorial for C++.
About the project: There have been some changes. Now the language is called "Q." ( kju Dot ).


问:
How should you TDD a Yahtzee game?
Let's say you're writing a Yahtzee game TDD style. You want to test the part of the code that determines whether or not a set of five die rolls is a full house. As far as I know, when doing TDD, you follow these principles:

Write tests first

Write the simplest thing possible that works

Refine and refactor

So an initial test might look something like this:

public void Returns_true_when_roll_is_full_house()
{
    FullHouseTester sut = new FullHouseTester();
    var actual = sut.IsFullHouse(1, 1, 1, 2, 2);

    Assert.IsTrue(actual);
}
```

<p>When following the "Write the simplest thing possible that works", you should now write the <code>IsFullHouse</code> method like this:</p>

<pre class="lang-csharp prettyprint-override"><code>public bool IsFullHouse(int roll1, int roll2, int roll3, int roll4, int roll5)
{
    if (roll1 == 1 && roll2 == 1 && roll3 == 1 && roll4 == 2 && roll5 == 2)
    {
        return true;
    }

    return false;
}
</code>```

This results in a green test but the implementation is incomplete.

Should you unit test every possible valid combination (both of values and positions) for a full house? That looks like the only way to be absolutely sure that your IsFullHouse code is completely tested and correct, but it also sounds quite insane to do that.

How would you unit test something like this?

Update

Erik and Kilian point out that using literals in the initial implementation to get a green test might not be the best idea. I'd like to explain why I did that and that explanation does not fit in a comment.

My practical experience with unit testing (especially using a TDD approach) is very limited. I remember watching a recording of Roy Osherove's TDD Masterclass on Tekpub. In one of the episodes he builds a String Calculator TDD style. The full specification of the String Calculator can be found here: http://osherove.com/tdd-kata-1/

He starts with a test like this:

public void Add_with_empty_string_should_return_zero()
{
    StringCalculator sut = new StringCalculator();
    int result = sut.Add("");

    Assert.AreEqual(0, result);
}
```

<p>This results in this first implementation of the <code>Add</code> method:</p>

<pre class="lang-csharp prettyprint-override"><code>public int Add(string input)
{
    return 0;
}
</code>```

Then this test is added:

public void Add_with_one_number_string_should_return_number()
{
    StringCalculator sut = new StringCalculator();
    int result = sut.Add("1");

    Assert.AreEqual(1, result);
}
```

<p>And the <code>Add</code> method is refactored:</p>

<pre class="lang-csharp prettyprint-override"><code>public int Add(string input)
{
    if (input.Length == 0)
    {
        return 0;
    }

    return 1;
}
</code>```

After each step Roy says "Write the simplest thing that will work".

So I thought I would give this approach a try when trying to do a TDD-style Yahtzee game.

答:
There are already lots of good answers to this question, and I've commented and upvoted several of them. Still, I'd like to add some thoughts.

Flexibility isn't for novices

The OP clearly states that he's not experienced with TDD, and I think a good answer must take that into account. In the terminology of the Dreyfus model of skill acquisition, he's probably a Novice. There's nothing wrong with being a novice - we are all novices when we start learning something new. However, what the Dreyfus model explains is that novices are characterized by

rigid adherence to taught rules or plans

no exercise of discretionary judgement

That's not a description of a personality deficiency, so there's no reason to be ashamed of that - it's a stage we all need to go through in order to learn something new.

This is also true for TDD.

While I agree with many of the other answers here that TDD doesn't have to be dogmatic, and that it can sometimes be more beneficial to work in an alternative way, that doesn't help anyone just starting out. How can you exercise discretionary judgement when you have no experience?

If a novice accepts the advice that sometimes it's OK not to do TDD, how can he or she determine when it's OK to skip doing TDD?

With no experience or guidance, the only thing a novice can do is to skip out of TDD every time it becomes too difficult. That's human nature, but not a good way to learn.

Listen to the tests

Skipping out of TDD any time it becomes hard is to miss out of one of the most important benefits of TDD. Tests provide early feedback about the API of the SUT. If the test is hard to write, it's an important sign that the SUT is hard to use.

This is the reason why one of the most important messages of GOOS is: listen to your tests!

In the case of this question, my first reaction when seeing the proposed API of the Yahtzee game, and the discussion about combinatorics that can be found on this page, was that this is important feedback about the API.

Does the API have to represent dice rolls as an ordered sequence of integers? To me, that smell of Primitive Obsession. That's why I was happy to see the answer from tallseth suggesting the introduction of a Roll class. I think that's an excellent suggestion.

However, I think that some of the comments to that answer get it wrong. What TDD then suggests is that once you get the idea that a Roll class would be a good idea, you suspend work on the original SUT and start working on TDD'ing the Roll class.

While I agree that TDD is more aimed at the 'happy path' than it's aimed at comprehensive testing, it still helps to break the system down into manageable units. A Roll class sounds like something you could TDD to completion much more easily.

Then, once the Roll class is sufficiently evolved, would you go back to the original SUT and flesh it out in terms of Roll inputs.

The suggestion of a Test Helper doesn't necessarily imply randomness - it's just a way to make the test more readable.

Another way to approach and model input in terms of Roll instances would be to introduce a Test Data Builder.

Red/Green/Refactor is a three-stage process

While I agree with the general sentiment that (if you are sufficiently experienced in TDD), you don't need to stick to TDD rigorously, I think it's pretty poor advice in the case of a Yahtzee exercise. Although I don't know the details of the Yahtzee rules, I see no convincing argument here that you can't stick rigorously with the Red/Green/Refactor process and still arrive at a proper result.

What most people here seem to forget is the third stage of the Red/Green/Refactor process. First you write the test. Then you write the simplest implementation that passes all tests. Then you refactor.

It's here, in this third state, that you can bring all your professional skills to bear. This is where you are allowed to reflect on the code.

However, I think it's a cop-out to state that you should only "Write the simplest thing possible that isn't completely braindead and obviously incorrect that works". If you (think you) know enough about the implementation on beforehand, then everything short of the complete solution is going to be obviously incorrect. As far as advice goes, then, this is pretty useless to a novice.

What really should happen is that if you can make all tests pass with an obviously incorrect implementation, that's feedback that you should write another test.

It's surprising how often doing that leads you towards an entirely different implementation than the one you had in mind first. Sometimes, the alternative that grows like that may turn out to be better than your original plan.

Rigour is a learning tool

It makes a lot of sense to stick with rigorous processes like Red/Green/Refactor as long as one is learning. It forces the learner to gain experience with TDD not just when it's easy, but also when it's hard.

Only when you have mastered all the hard parts are you in a position to make an informed decision on when to deviate from the 'true' path. That's when you start forming your own path.

Title: How should you TDD a Yahtzee game?


问:
Handling false positives and legacy code warnings in static-analysis of C++ code?
We have a large "legacy" C++ code base on which no static analysis is run at the moment.

Every now and then, we are thinking about at least using cppcheck, maybe via Visual Lint. (I've also briefly checked the sites of Coverity or Klocwork or RedLizards/Goanna.)

However, I do expect a huge number of found warnings and probably also false positives (in that the error does not actually cause an observable bug in the application).

We simply do not have the resources available to address these all on rollout of any analysis tool, especially as we would very much only like to touch "code that works (well enough)" if we really have to.

So what I am looking for are experiences and user stories of adding C++ static analysis to legacy code bases:

We had this product, consisting of xxx lines of code over zzz C++ projects and we started using static analysis tool yyy in development. Rooting out the legacy code warnings took aaa effort, (temporarily) ignoring them was hard/easy/impossible. Ignoring warnings selectively for the code base really worked well/didn't work at all. Etc.

Something like this. Thanks!

答:
Here are some studies on cost-benefit of static analysis tools.

http://collaboration.csc.ncsu.edu/laurie/Papers/TSE-0197-0705-2.pdf

The gist of the study is that static analysis tools are in the same order of magnitude of cost/benefit ratio as inspection on an established code-base. In the end, the cost of finding the bug was about 1/2 inspection (but this is obviously highly dependent on the code-base - and why they concluded that the cost was in the same order of magnitude).


问:
Developing on a production server
Today I got yelled at for developing an application on a production server. Quote, "developing on a production server is not acceptable - ever!"

Here is the situation.

I set up a development instance: http://example.com:3000

The production instance is: http://example.com

I complete all my development work on http://example.com:3000 and when the client is pleased with the changes, I move them over to http://example.com.

The application I am working with is an old Ruby on Rails application, and I have to say that initially, I did try to set up an development environment locally, but I could never get it running. After trying for a while, I gave up and decided to develop on the production server.

Again, am I an idiot? Probably so, but I've been doing web development for a couple of years now, and I have never encountered a situation like this. Who is right and why?

答:
Rules that use "always" or "never" are usually ill defined. There will be edge cases where breaking a best practice will be justified. Much better advice will be "Don't touch the production servers unless you have very good reasons"

In my career I have found only two reasons to change code on production servers:

Bugs or behavior that happen only there and are not reproducible on the development environment. These are rare but can be very annoying and hard to find.

Directly fixing critical bug that you just cannot afford to wait to pass trough the normal deployment process if it takes more than a few minutes. After this has been cleared with management. If you are lucky you should only have few of those for your entire career.

Both are best left to senior developers that know the systems intimately.

Title: Developing on a production server


问:
How can I deal with a team member who dislikes making comments in code?
One of my team members consistently avoids making comments in his code.

His code is not self-documenting, and other programmers have a difficult time understanding his code.

I have asked him several times to comment his code, however he just gives excuses or claims that he will do it later. His concern is that adding comments will take too much time and delay the projects.

What argument can I present to him to convince him to properly document his code?

On that note, am I wrong to focus on the code comments or is this indicative of a larger problem which should be addressed?

答: In one of my past projects were missing dozens of comments (algorithm, results or some basic JavaDoc), so I just decided to make 130 issues for him, e-mail notification about each of issue every 4days. After 3weeks he had 280 issues, then he decided to write comments.</p>


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Testing can only prove the presence of bugs, not their absence.

— Edsger W. Dijkstra

LastEditorDisplayName: Roger Pate


答:
I went through this several years ago (introducing lint to a 12-year-old legacy code base). Although I ended up with an overwhelming flood of errors, I decided to ignore the problems which were most common (with hundreds or thousands of instances), and concentrated on the messages which occurred only a small number of times, my logic being that a lint problem found in hundreds of places is probably harmless (it's possible that all the observable problems had been fixed, but more likely the message is just noise), but problems I saw rarely might be genuine problems we'd never had reported.

This lead to fixing some shocking array boundary problems and loop problems, and then I ended up disabling messages for the most common problems.

Awk and I became good friends as I analysed lint output. I'd use perl now if I were to do it again.

Title: Handling false positives and legacy code warnings in static-analysis of C++ code?

Body:
We have a large "legacy" C++ code base on which no static analysis is run at the moment.

Every now and then, we are thinking about at least using cppcheck, maybe via Visual Lint. (I've also briefly checked the sites of Coverity or Klocwork or RedLizards/Goanna.)

However, I do expect a huge number of found warnings and probably also false positives (in that the error does not actually cause an observable bug in the application).

We simply do not have the resources available to address these all on rollout of any analysis tool, especially as we would very much only like to touch "code that works (well enough)" if we really have to.

So what I am looking for are experiences and user stories of adding C++ static analysis to legacy code bases:

We had this product, consisting of xxx lines of code over zzz C++ projects and we started using static analysis tool yyy in development. Rooting out the legacy code warnings took aaa effort, (temporarily) ignoring them was hard/easy/impossible. Ignoring warnings selectively for the code base really worked well/didn't work at all. Etc.

Something like this. Thanks!


答:
At a minimum test at the interfaces.  On your diagram you should have two arrows, one at jQuery|Logic and one at Logic|Ajax.

Work your way inward as the design solidifies.  You don't want to spend alot of time unit testing some piece of internal logic that will only get ripped out and replaced by something else later.

Of course, as you granulate your design, the Logic box will look like lots of little boxes or stripes.  Again test at the interfaces between the components.

Title: JavaScript...what to unit test

Body:
I would like to hear other people's opinion on what to unit test in JavaScript. I've been thinking about it and experimenting and let me present what seems to me the right thing. First of all, in order to be able to unit test your production code you need to divide the productin code into three layers: (1) DOM/jQuery, (2) Logic, and (3) AJAX. Refer to the attached image.

The Logic layer sits between the DOM/jQuery layer and the AJAX layer, that is, the DOM/jQuery layer is not tied to the AJAX layer. So, in my opinion the only layer that should be unit tested is the Logic. Writing unit tests should be easy, otherwise programmers will not write them. What is the use of writing unit tests for the DOM/jQuery layer - ok, you've added an li element to an ul element, why do I need to assert that, there should be no if statements there. About the AJAX layer, what's there to assert...the URL that was used was "blah", I know it was "blah". Whatever the data that was obtained in the AJAX layer should be given to the Logic layer. Now, the Logic layer is a different story, for example, in a unit test it can be given data that suppossedly came from an AJAX call, and use a mock DOM/jQuery layer to verify that the data was displayed correctly. Let me know what you think.


问:
Predicting advantages of database denormalization
I was always taught to strive for the highest Normal Form of database normalization, and we were taught Bernstein's Synthesis algorithm to achieve 3NF. This is all very well and it feels nice to normalize your database, knowing that fields can be modified while retaining consistency.

However, performance may suffer. That's why I am wondering whether there is any way to predict the speedup/slowdown when denormalizing. That way, you can build your list of FD's featuring 3NF and then denormalize as little as possible. I imagine that denormalizing too much would waste space and time, because e.g. giant blobs are duplicated or it because harder to maintain consistency because you have to update multiple fields using a transaction.

Summary: Given a 3NF FD set, and a set of queries, how do I predict the speedup/slowdown of denormalization? Link to papers appreciated too.

答:
One of the several major reasons to normalize is that it optimizes for general use cases while denormalization tends to optimize performance for specialized use cases (with significant penalties for other use cases).  This is one reason why usually OLTP workloads benefit primarily from normalization (there are exceptions here but they are rare).

In order to predict advantages, what you really have to know is what exactly you are denormalizing and for what workflows.  There are also questions about the size of your data set and what the impacts of caching are likely to be.  So the answer is likely to depend on a very large number of things including database size, what portion is likely to still be in memory, planning overhead of complex queries, and the like.  This is a very complicated, implementation-specific matter, and it depends very much on both your database and your RDBMS.  These advantages will be greatest in OLAP workloads, and typically the disadvantages will be greatest in OLTP workloads.

So I don't see that there is a single answer here other than to watch query plans, and consider the possibility of materialized views for denormalized data.  In my view the best approach is to have relatively normalized OLTP database and denormalize for reporting purposes as needed only.


答: You may also want to consider using System.Reflection.Emit from the .NET runtime to generate a .NET executable. This will give you access to an existing object-oriented environment which has already solved some problems for you, and the resulting exe can be platform-independent. The runtime will compile the intermediate code in the .exe to machine code as needed, so performance should be comparable to what you'd get from compiling directly to native code.</p>

Title: Convert an interpreter to a compiler?


问:
C# Classes instance members vs. enum
What is the difference between private variables in a clsClass type and using enumeration enum to instantiate the variable. This question arose when I was looking at some C# Class code for serial ports. example:  private int SomeClassMember; and                         private enum TransmissionType{TEXT,HEX} ?

Where do the enum statements appear in a Class definition?

答:
I would first encourage you to read this small post by Microsoft.

In C#, enums cannot have a behaviour. If it helps, you can think of enums as members of a special class where instances just have names but no methods [this is strictly speaking not a correct visualization].

Class members however can have useful methods embedded into them.

Example,

```<code>public struct Color {
    public static readonly Blue = new Color (0, 0, 255);
    public static readonly Red  = new Color (255, 0, 0);
    //...etc.

    public int GetHue() {
        //Return the hue of the color
    }

    public int GetSimilarityCoefficient(Color another_) {
        //Some really ingenious algo to identify similarity of colors
    }
}
</code>```

vs.

```<code>public enum Color {
    Blue,
    Red,
    Green
} //Cannot do anything much but use if-else/switch-case and make decisions in those blocks
</code>```

This shows enums in a bad light and hence comes the question —when to use enums? And thus comes a highly personal, though I hope not widely rejected, answer.

I personally prefer to use enums when my members are supposed to only have token meanings (i.e., they are pure states) and when I want them to be extremely lightweight and when I want to ensure that all enumerations can be accounted for.

Example in a form that has several radio button choices (let's say to choose which type of copy to run),

```<code>public enum UserChoice {
    Copy,
    DeepCopy,
    PreviewOnly
}
…
//Somewhere
UserChoice userChoice = form.GetUserChoice();
switch (userChoice) {
    case UserChoice.Copy:
        //Run the copy algorithm
        break;
    case UserChoice.DeepCopy:
        //Run the deep copy algorithm
        break;
    //Forgot to handle PreviewOnly —> gives a compile exception
}
</code>```

Note that I can accomplish the same using class variables too:

```<code>public class UserChoice {
    public static UserChoice Copy = new UserChoice();
    public static UserChoice DeepCopy = new UserChoice();
    public static UserChoice PreviewOnly = new UserChoice();
}
…
//Then somewhere
UserChoice userChoice = form.GetUserChoice();
if (userChoice == UserChoice.Copy) {
    //Run the copy algorithm
}
else if (userChoice == UserChoice.DeepCopy) {
    //Run the deep copy algorithm
}
//Forgot to handle preview only. No compile exception.
</code>```

Also, enums can be Flags.

```<code>[Flags]
public enum  UserChoice{
    Copy = 0,
    Deep = 1,
    Preview = 2,
    NoActualOp = 4
} //Thus, DeepCopy = Copy | Deep; DeepCopyWithPreview = Copy | Deep | Preview; CopyWithPreviewOnly = Copy | Preview | NoActualOp etc..
</code>```

Title: C# Classes instance members vs. enum

Body:
I would first encourage you to read this small post by Microsoft.

In C#, enums cannot have a behaviour. If it helps, you can think of enums as members of a special class where instances just have names but no methods [this is strictly speaking not a correct visualization].

Class members however can have useful methods embedded into them.

Example,

public struct Color {
    public static readonly Blue = new Color (0, 0, 255);
    public static readonly Red  = new Color (255, 0, 0);
    //...etc.

    public int GetHue() {
        //Return the hue of the color
    }

    public int GetSimilarityCoefficient(Color another_) {
        //Some really ingenious algo to identify similarity of colors
    }
}

vs.

public enum Color {
    Blue,
    Red,
    Green
} //Cannot do anything much but use if-else/switch-case and make decisions in those blocks

This shows enums in a bad light and hence comes the question —when to use enums? And thus comes a highly personal, though I hope not widely rejected, answer.

I personally prefer to use enums when my members are supposed to only have token meanings (i.e., they are pure states) and when I want them to be extremely lightweight and when I want to ensure that all enumerations can be accounted for.

Example in a form that has several radio button choices (let's say to choose which type of copy to run),

public enum UserChoice {
    Copy,
    DeepCopy,
    PreviewOnly
}
…
//Somewhere
UserChoice userChoice = form.GetUserChoice();
switch (userChoice) {
    case UserChoice.Copy:
        //Run the copy algorithm
        break;
    case UserChoice.DeepCopy:
        //Run the deep copy algorithm
        break;
    //Forgot to handle PreviewOnly —> gives a compile exception
}

Note that I can accomplish the same using class variables too:

public class UserChoice {
    public static UserChoice Copy = new UserChoice();
    public static UserChoice DeepCopy = new UserChoice();
    public static UserChoice PreviewOnly = new UserChoice();
}
…
//Then somewhere
UserChoice userChoice = form.GetUserChoice();
if (userChoice == UserChoice.Copy) {
    //Run the copy algorithm
}
else if (userChoice == UserChoice.DeepCopy) {
    //Run the deep copy algorithm
}
//Forgot to handle preview only. No compile exception.

Also, enums can be Flags.

[Flags]
public enum  UserChoice{
    Copy = 0,
    Deep = 1,
    Preview = 2,
    NoActualOp = 4
} //Thus, DeepCopy = Copy | Deep; DeepCopyWithPreview = Copy | Deep | Preview; CopyWithPreviewOnly = Copy | Preview | NoActualOp etc..


答:
Normally you den-normalize your data model to optimize performance for a particular use case. This will usually have an adverse effect on the performance of other use cases. e.g. repeating data in several rows may speed up query processing by eliminating a join, but, your update processing will be slow down.

In effect 3NF gives optimum performance for any number of arbitrary accesses to your database, but, for particular joins and selects there may be a better models.

So treat de-normalization like you would any other optimization. i.e. don't do it unless you actually have a performance problem, and, make sure your 'fix' does not cause more problems than it solves.

Title: Predicting advantages of database denormalization

Body:
I was always taught to strive for the highest Normal Form of database normalization, and we were taught Bernstein's Synthesis algorithm to achieve 3NF. This is all very well and it feels nice to normalize your database, knowing that fields can be modified while retaining consistency.

However, performance may suffer. That's why I am wondering whether there is any way to predict the speedup/slowdown when denormalizing. That way, you can build your list of FD's featuring 3NF and then denormalize as little as possible. I imagine that denormalizing too much would waste space and time, because e.g. giant blobs are duplicated or it because harder to maintain consistency because you have to update multiple fields using a transaction.

Summary: Given a 3NF FD set, and a set of queries, how do I predict the speedup/slowdown of denormalization? Link to papers appreciated too.


问:
How do I convince my boss (and other devs) to use/consider Unobtrusive JavaScript
I'm pretty new in our develepors team.

I need some strong arguments and/or "pitfall" examples, so my boss will finally understand the advantages of Unobtrusive JavaScript, so that he, and the rest of the team, stops doing things like this:

```<code><input type="button" class="bow-chicka-wow-wow"
       onclick="send_some_ajax(); return false;" value="click me..." />
</code>```

and

```<code><script type="text/javascript">

function send_some_ajax()
{
  // bunch of code ... BUT using jQuery !!!
}
</script>
</code>```

I suggested using a pretty common pattern:

```<code><button id="ajaxer" type="button">click me...</button>
</code>```

and

```<code><script type="text/javascript">

// since #ajaxer is also delivered via ajax, I bind events to document
//  -> not the best practice but it's not the point....

$(document).on('click', '#ajaxer', function(ev) {
var $elem = $(this);
ev.preventDefault();

});
</code>```

The reason why my boss (and others) do not want to use this approach is that the Event-Inspection in FireBug (or Chrome Dev Tools) isn't simple anymore, e.g. with

```<code><input type="text" name="somename" id="someid" onchange="performChange()">
</code>```

he can immediately see what function executes on change-event and jump right to it in a huge JS file full of spaghetti-code.

In the case of Unobtrusive JavaScript the only thing he would see is:

```<code><input type="text" name="somename" id="someid" />
</code>```

and he has no idea whether some events, if any, were bound to this element and which function will be triggered.

I was looking for a solution and found it:

```<code>$(document).data('events') // or .. $(document).data('events').click
</code>```

but, this "approach" caused it to take "too long ..." to find out which function fires on which event, so I was told to stop bind events like that.

I'm asking you for some examples or strong advantages or any other kind of suggestions for "Why we should use UJS"

UPDATE: suggestion to "change the job" is not an ideal solution.

UPDATE 2: Ok, I've not only suggested to use jQuery event-binding, I did so. After I wrote all Event-Delegation, the Boss came to me and asked me, why am I doing event delegation with different approach and approach he dind't know

I mentioned some obvious benefits, like - There are 15 input-fields and all of then have an onchange event (not only, some of them have also onkeyup) So it's more pragmatic to write this kind of event-delegation ones for ALL input-fields, instead of doing it 15 times, especially if all of the HTML will be rendered with PHP's echo -> echo '... <input type="text" id="someid" ... />...'

答:
Inline event handlers stink because:

No event delegation - which is great when you want to be able rip elements in and out of a page dynamically without having to rebind.

You've bound behavior to HTML tags rather than class/ID attributes of HTML tags. Let's say you have a class of "combo_box" all across your app. Suddenly, on half your old pages, you want a slight variation on your combo boxes when they're in a different container. Tied to a class, you can alter that behavior based on container context, e.g. "#special_container .combo_box". Bound inside the damned HTML you could find yourself tracking down every little select box with a .combo_box class in any number pages to change those handler references one by one rather than tweaking or writing a couple new lines of code to filter from a single file location.

If you want multiple handlers, you have wrap them in a function and then bind that unnecessarily to specific HTML files. How maintainable is that?

A subtler point is that it is much easier/more maintainable/flexible and robust to handle behavior with more of a control panel mentality. By binding from a central location, you've got a place where you can get an overview of all behavior happening on the page all at the same time, which is handy when, for instance, you need to figure out why certain pages occasionally run into a certain bug that's hard to understand but not others.

This is the client-side. We have multiple browsers all interpreting heavy complexity in their own ways to account for. Slop-it-all-together and let the IDE sort it out for you mentalities do not work well here. Keeping your code tight, minimal, loosely coupled and clean is not fashionable, it's absolutely essential in order to establish a maintainable front end that's easy to modify and update and yes, that's where the $$$s come in assuming your manager actually has foresight.

It's not !@#$ing 2002 anymore. This argument is as old as tables as layout. Get over it and start trusting experienced client-side-specialized dev you yourself hired expressly because you lacked their expertise (not that I'm channeling any anger from personal experience or anything).

And to rebutt your boss's argument, it's really not that hard to track down what class or ID is being used in event delegation or handler binding with CTRL+F and a tool that lets you view all JS on the page like my own personal embarrassingly jquery/prototype-only bookmarklet version I hastily cobbled together when web dev toolbar's started crapping out on me (damned color-coding). Bookmark from the link at the js fiddle page or copy the JS and make your own.

A JS fiddle link that will presumably expire eventually


问:
Should developers be responsible for testing other developer and contractor/vendor code?
I have been working (~ 5 years & first IT job) as an application developer at a large financial institution  with a strict corporate hierarchy, multiple LOBs, and heavily process-laden IT departments.

Now, one aspect of this culture is to use a lot of external contractors and vendors to port legacy code to current technologies. However, the internal developers are made to test (black-box) their code. A majority of the time these external developers do not ensure that their apps work end-to-end properly before releasing their code and wait for us (internal developers) to investigate issues/collect logs/any screen shots of failure/database logs etc.

I am wondering if anybody else has encountered such a situation in their role as developers in IT shops/orgs. Do you really improve technically or intellectually, especially, on large complex projects where testing can go on for more than 6 months ?
For instance, I went a whole 7 months QC'ing and acting as a non-coding team-lead thinking that I should not let the team down. However, I see now that this is detrimental to my coding skills.

答:
In an ideal world, developers should not be doing this type of testing.

Ideally, you would have a test team who would carry out this function.

Developers in general are not very good at this type of thing, it does not interest them. Testers are.

In some workplaces however, "techies" have to wear many hats. Often this will be because IT is under funded, or management do not believe in having a separate testing function. Some people enjoy being involved in multiple functions of course.

If you as a developer are being forced into long periods of testing poorly written external vendor code, this is a massive job smell for me.


问:
Is BDD scalable for medium to large projects?
In every Website you read about BDD (Behaviour Driven Development) you find a very simple nice example showing you how obvious and easy is it to define your requirements. But trying to implement this process in a big product (not a calculator example) showed me that things can get (or will get) pretty complex and unreadable; especially changing requests at a later point means a lot of work to correct the Integration tests for this.

So I'm wondering, is BDD really worth it? Does it solve a problem that other techniques don't!

答:
It might help to realise that BDD's focus is the conversations. BDD is really an analysis tool which happens to provide some regression testing as a nice by-product.

I've used scenarios at all kinds of levels in conversation; from identifying different stakeholders to see if a release is likely to be well-received, to working out how a module or class should behave.

There are a couple of hints and tips I can suggest for making this easier.

If you've never done it before, it's going to change.

Anything which is new to the domain, or the business, is likely to change. You might realise you're in this space if you're talking through the scenarios, questioning them, and the business say, "Oh, I'm not sure." That's a good sign to stop trying to do BDD and spike something out to get faster feedback, to help the business work out what it is they want. Once the ideas have stabilized, scenarios can be written in retrospect.

All projects have some aspect to them that's new, or you wouldn't be doing them.

If you've done it before, it's boring.

As well as new, differentiating aspects, projects usually have some commoditised aspects to them which are similar to those already done. For instance, if I was producing a new mobile phone, it would still need to make calls. "Make a phone call" is such a well-known scenario that we wouldn't need to talk through it. Similarly, things like "login" or even "user registration" are boring.

Wherever possible, use libraries for these, and then you won't have to write scenarios around them. Also, do the other bits first - have an already-logged in user and work out what he's logging in for. These areas are unlikely to change, so you may be able to get away with manual testing anyway.

If someone has done it before, talking through scenarios can help.

There's a bit between where we have domain-specific requirements, stuff which is relatively well-understood by someone, and where the real uncertainty is mostly around scope rather than the actual behavior of the system.

Talking through scenarios can help the dev team to discover behavior, to draw on an expert's knowledge, and to ensure that the known, valuable behavior is captured.

This is the bit where BDD works best. My tip is to write the most interesting scenarios at the top of the feature file (or wiki, if you're not automating) and delete any scenarios which are duplicated or easy to infer as a result.

Wherever possible, use the scenarios just as examples of how the application works. For instance, if you want to show how validation works, show a couple of examples of how the application helps the user fill in a form. Check that validation is rigorous using unit testing, which is much easier to maintain and quicker to run.

Further reading

If you're interested in this, here are some things I wrote which might help.

BDD in the large

Cynefin for devs, which goes into these three areas in more detail

My tutorial slides, which are all nice and annotated for you, and cover the whole stack too.


问:
How can my code structure be improved?
I am looking for advice on the neatest way to structure my code.

```<code>class Password
{
    private string cipher;

    Password(string cipher)
    {
        this.cipher = cipher;
    }

    public string HashPassword()
    {

    }

    public bool VerifyPassword()
    {

    }
}
</code>```

The idea behind the class is to abstract away the password hashing process. The class will present two functions to the user, HashPassword() and VerifyPassword(), which will perform completely different hashing algorithms depending on the value of the cipher variable.

Currently, I am using a set of if/else conditional statements within the two functions itself to determine which hashing algorithm to perform. However, it felt quite inelegant to me.

Is there a better way of structuring my code?

答:
Have a base class - PasswordHasher or such that will be abstract (or, if you find that implementation vary too much for implementations to share anything, use an interface).

From it, inherit a class for each hash algorithm you are going to use.

Using dependency injection, you can use either algorithm by simply passing in the relevant class.

Title: How can my code structure be improved?


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
If you want to explain pointers you have to explain memory first. I usually do that using graph paper/squared paper with rows and columns. If the "student" understands memory she can understand what an address is. If you got address you got pointers.

You can play with this abstraction. E.g. write the address (number) of one square into another square. Now draw an arrow from the pointer square to the destination square. Now overwrite the pointer (e.g. increment it) and adjust the arrow. Write an address into another square and let the student draw the arrow...

Next step: Give certain squares (like the pointer) a name. Now you can explain dereferencing.
That's it.

Title: What's a nice explanation for pointers?


问:
1 Interface 2 Implementations and an EJB exception
In my JavaEE project I have an interface like this:

```<code>@Local
public interface DataAccess { ... }
</code>```

And two stateless beans implementing it:

```<code>@Stateless
public class DataAccess_Online implements DataAccess { ... }

@Stateless
public class DataAccess_Offline implements DataAccess { ... }
</code>```

And I get the exception:

Cannot resolve reference Local ejb-ref....
  because there are 2 ejbs in the application with interface ...DataAccess

The problem is clear, there may only be one class implementing DataAccess. But it would be convenient if I could use two. In the client I want to work on the Interface DataAccess only, so I don´t have to distinguish between online/offline in my code, they both offer the same methods.

In the client I have an dependency injection:

```<code>@EJB
DataAccess da;
</code>```

And I see how this is a problem with two implementations for DataAccess, but what should I change to make it work? The client always starts with the online version of DataAccess, but after a while he could request the offline version, so the offline version only needs the same interface, if I need a DataAccess injection it will always be the online version.

How can I use two implementations of an interface together with @EJB dependency injection?

答:
Well the solution was simple, I just had to introduce a new interface:

```<code>public interface DataAccessOffline extends DataAccess
</code>```

The error is gone and I can inject into DataAccess with @EJB, but I can still switch between the online and offline implementations.

Body:
Well the solution was simple, I just had to introduce a new interface:

public interface DataAccessOffline extends DataAccess

The error is gone and I can inject into DataAccess with @EJB, but I can still switch between the online and offline implementations.


答:
You can use:</p>

```<code>@Stateless(name="online")
public class DataAccess_Online implements DataAccess { ... }

@EJB(beanName="online")
DataAccess da;
</code>```

Title: 1 Interface 2 Implementations and an EJB exception

Body:
In my JavaEE project I have an interface like this:

```<code>@Local
public interface DataAccess { ... }
</code>```

And two stateless beans implementing it:

```<code>@Stateless
public class DataAccess_Online implements DataAccess { ... }

@Stateless
public class DataAccess_Offline implements DataAccess { ... }
</code>```

And I get the exception:

Cannot resolve reference Local ejb-ref....
  because there are 2 ejbs in the application with interface ...DataAccess

The problem is clear, there may only be one class implementing DataAccess. But it would be convenient if I could use two. In the client I want to work on the Interface DataAccess only, so I don´t have to distinguish between online/offline in my code, they both offer the same methods.

In the client I have an dependency injection:

```<code>@EJB
DataAccess da;
</code>```

And I see how this is a problem with two implementations for DataAccess, but what should I change to make it work? The client always starts with the online version of DataAccess, but after a while he could request the offline version, so the offline version only needs the same interface, if I need a DataAccess injection it will always be the online version.

How can I use two implementations of an interface together with @EJB dependency injection?

Body:
You can use:

@Stateless(name="online")
public class DataAccess_Online implements DataAccess { ... }

@EJB(beanName="online")
DataAccess da;


问:
Writing a TCP protocol or use HTTP for file transfer?
I want to write a server side application which allows several users to exchange files (not above 3MB) in the following way: user A connects to (server) S. User B connects to S. User C connects S. User A sends a file. Users B and C "see" that a file was/is being uploaded and start downloading it.

My main concern is responsiveness. I want the file to arrive at B and C not long after A started uploading.

I thought of doing it using HTTP: user A sends raw bytes to the server and the server saves the file locally. At this point users B and C see that a file was uploaded and start downloading it.

My question: is HTTP the best way to go here? Or should I write an app that uses TCP sockets, and write my own protocol? If I go with sockets. How can I estimate the RAM requirements of the VPS so that I can allow N file-transfer connections simultaneously?

答: I would probably do a proof of concept using http and check the performance. No point in reinventing the wheel if it isn't necessary.</p>


问:
When would using a scripting language within a larger program be useful?
I have heard of several situations of people using say, JavaScript or Python (or something), inside a program written in C#. When would using a language like JavaScript to do something in a C# program be better then just doing it in C#? </p>

答:
When? Between 1948 and 2008 - initially compiled languages took significant time to compile and link, so it was commonplace to create a scripting language to allow user customisation and configuration.  If you look at the history of AutoLisp, then the answer is  initially AutoCAD shipped with a scripting language within it, but this was phased out in favour of exposing an scriptable interface to VBA then .net.

With CLR, enabling a C# program or a Lua program call into an existing system are not significantly different in development cost, and the .net runtime ships with the tools to generate and compile on the fly.

You no longer need to have a scripting language within the larger program, but instead expose the larger program to the scripting facilities of the runtime.

In environments which don't offer on the fly code generation and compilation, and it is seen as desirable to offer a general-purpose automation language rather than a domain specific one, you will still get Lua or Python scripting. For tools offering a COM interface, then that scripting language will be C# or VB.net ( MS Office, Sparx Enterprise Architect ). So having a scripting language for a program written in a language which is itself simple enough to be a scripting language is a unnecessary.


问:
Relation of CPU Hz's and network speed in clusters
In cluster the Amdahl's law, Gustafson's law exists.

I though that there might be some law which states the relation between CPU Hz's and network speed: maximum network speed after which no additional Mbps would increase the calculations. Does such limits exists and what it depends on?

答:
Mbps is not the only measure to measure network speed, the other arguable more important one is setup time (how long it takes for a pair of CPUs to be ready to send a packet) which is in many cases an order of magnitude larger than straight up bandwidth.

This is the reason why most algorithms try to chunk as much sending as possible

This means that as soon as the packet size times the bandwidth becomes too small compared to the setup time it stops mattering how fast the network is.

The network topography and placement of the various info being calculated is very important to how fast sending can happen, (as each packet blocks the path it is traveling along unless a store and forward method is used).

I'll have to dredge up my parallel programming course to give more info on this if you want.


答:
What's wrong with plain old garden variety FTP (File Transfer Protocol), or even TFTP (Trivial File Transfer Protocol)?

Granted, they're older than your father's memory of his first kiss, but they still work.

Now, both FTP and TFTP want the file to be on the server before they serve it to download clients.  If what you want is to stream the file from A directly, or proxied through your server, FTP and TFTP may not be quite the way to go.

Title: Writing a TCP protocol or use HTTP for file transfer?

Body:
I want to write a server side application which allows several users to exchange files (not above 3MB) in the following way: user A connects to (server) S. User B connects to S. User C connects S. User A sends a file. Users B and C "see" that a file was/is being uploaded and start downloading it.

My main concern is responsiveness. I want the file to arrive at B and C not long after A started uploading.

I thought of doing it using HTTP: user A sends raw bytes to the server and the server saves the file locally. At this point users B and C see that a file was uploaded and start downloading it.

My question: is HTTP the best way to go here? Or should I write an app that uses TCP sockets, and write my own protocol? If I go with sockets. How can I estimate the RAM requirements of the VPS so that I can allow N file-transfer connections simultaneously?


问:
Are there open source alternatives to Bitbucket, Github, Kiln, and similar DVCS browsing and management tools?
I am aware of several tools/services that provide DVCS browsing and management such as Bitbucket, Github, Kiln, SCM-Manager and Rhodecode.

However, the use case I am considering is one such that:

Any source code must reside on an employers internal servers.

The solution must be open source.

It should provide a Bitbucket or Github like experience, including a project wiki, repository browsing and management, and social coding aspects such as code review.

The solution should have mercurial support (if not support for other DVCSs).

Of these, only SCM-Manager and RhodeCode come close as they can be installed on your own servers and are open source. However they do not have the Bitbucket or Github experience. There is no issue tracker or wiki and the UI, while functional, is not up to par with Github or Bitbucket.

I can get close with Trac or Redmine with their repository browsers but unfortunately they do not have any repository management capabilities.

Are there other open source tools out there that would provide a similar experience to Bitbucket, Github or Kiln?

答:
Consider using GitLab https://about.gitlab.com/ since it meets most of your requirements:

You can install it on-premises

It is MIT expat licensed

It has a wiki (backed by git), repository browsing, detailed access management (multiple accesses levels, protected branches, ldap integration, etc.) and has merge requests for code review and discussion (including line comments)

It does not support mercurial but only git

It also has a good issue tracker or you can link to an external issue tracker. You can test your merge requests with GitLab CI if you want to. GitLab has been growing fast and is in use by more than 25.000 organizations.

Disclosure: I'm the CEO & co-founder of GitLab B.V.


问:
what to make of a Microsoft Most-Valued-Professional who believes that .NET types are either primitive or complex?
I thought that in .NET types are either value types or reference types. But this guy, when asked about .NET types, talked about "primitive types" and "complex types".

I understand that people sometimes use different names to refer to the same concepts, but isn't it strange that a Microsoft certified professional would use this kind of terminology?

答:
It's not strange at all.  "Primitives" is a bit of standard terminology in the programming world.  It means a thing that is not built out of simpler things, but serves as a building block to create more complex things.  So "primitive types and complex types" is a completely valid way to talk about them.

It can be used in other contexts as well.  For example, synchronization primitives are low-level constructs that are not actually primitive data types, but are still not built out of other synchronization objects, and can be used to build higher-level synchronization objects, such as monitors.


答:
First of all: I think this might just be confusing terminology.

Primitive types, value types and reference types are 3 different things:

Primitive types are those that are built into the language as a primitive. (int, bool and so on). MSDN often refers to them as just "built in types".

Value types are those that are allocated by value on the stack. They include most of the primitive types. The formal definition is all types that derive from System.ValueType; this also includes all structs.

Reference types are allocated on the heap and variables of that type are said to be references to the object. It's like pointers from C, but C# takes care of all the type and memory safety for you.

While I haven't seen any formal definition for a "complex type" in C#, I would guess it means all defined types that are not primitives. This includes both value types and reference types.

See more info on types on MSDN.

Title: what to make of a Microsoft Most-Valued-Professional who believes that .NET types are either primitive or complex?

Body:
I thought that in .NET types are either value types or reference types. But this guy, when asked about .NET types, talked about "primitive types" and "complex types".

I understand that people sometimes use different names to refer to the same concepts, but isn't it strange that a Microsoft certified professional would use this kind of terminology?


问:
Library vs. framework vs API?
What is the difference between a library, framework, and API? They all seem the same to me. I would like to hear peoples thought of this. </p>

答:
The application is developed using libraries based upon a framework and communicates through a API.

If you building a app say a online image processing application,

You can use some pre written image processing libraries.

on any framework you know which will guide you to construct the
application.

You will be providing  the application some way to
interact with outside world..that would be your applications API to
rest of the world.

When a call comes in to your application

it would be handled in a way how you designed with guidance of framework

processing the call carried by library

these functions will be accessed through the your API from outside world

to the calling person

reasons why these exist:

library    : saves you from reinventing the wheel

framework  : saves you from unexpected traps of system design and handling unless the
           framework itself has flaw's

API        : ensures the security of application by interfacing the core from the real
           world access

Title: Library vs. framework vs API?


问:
Does it make sense and is it to acceptable to say ".NET code"?
There is C# code, VB.NET code... Can I also say ".NET code" as an umbrella term that covers all the languages you can use with the .NET framework?

I've seen people using it as well as people saying it shouldn't be used...

答:
A lot of such umbrella terms I've seen, like C/C++ or C++/C#/Java, or C-family, don't work at all. However, in the case of .NET, it's a lot more sane. This is because the Framework imposes a type system, base classes libraries, and such on every .NET language. So strictly, all languages which lower into CLR bytecode must have a fair chunk in common with each other.

You could also argue that .NET code would refer to the CLR's bytecode.


答: C# code could be running via Mono which isn't .NET. Thus something along the lines of CLI (Common Language Infrastructure) Code would be a better way of referring to it. The CLR is Microsoft's implementation of the CLI which is an open standard.</p>

Title: Does it make sense and is it to acceptable to say ".NET code"?

Body:
There is C# code, VB.NET code... Can I also say ".NET code" as an umbrella term that covers all the languages you can use with the .NET framework?

I've seen people using it as well as people saying it shouldn't be used...


答:
I'd say the .Net code term fits binary code (CIL Byte code) allot better then source code - and at that stage you're no longer talking about languages.

With .Net it makes some sense to use an umbrella word for all the languages that could be compiled into CIL targeting the CLR, but .Net languages sounds allot better then .Net code. This expression would of course tell you something about the binary compatibility of the resulting code, and almost nothing about the languages themselves. It's like calling all the languages that can compile code compatible with the Intel x86 a name: There was a time when that was useful, but not any more. There might also have been a time when that could have told you something about the languages themselves (along the lines of: they probably support pointers, they probably support function calls) - but again, not any more.