答:
As far as performance goes: In a fully-compiled language like C or C++, with optimizations on, the difference is probably zero. In other languages (interpreted, byte-code-compiled, or jit-compiled) there may be a difference, but 1. it's not going to be much and 2. it's not going to be your bottleneck. There are exceptions, but those are rare, and if you encounter one of them, you're probably fiddling with fine-grained profiling and instruction-level optimizations; in all the other cases, either is going to be fast enough.

So, as always, your first choice should be to optimize for readability, not for runtime performance. Which brings us to the question when you should use one or the other; well, opinions differ. One camp says the ternary operator simply shouldn't be used at all, for clarity's sake; and they certainly have a point, because it has the tendency to make for really complicated one-liners, especially if you nest it, but also because its precedence can lead to undesirable results. However, I think there are situations where a ternary operator makes the code more readable, and I don't see anything wrong with using it in such a situation; a textbook example is simple text pluralizing:

```<code>printf("%i %s deleted.", num_files, (num_files > 1) ? "files" : "file");
</code>```

The same code written with an explicit if statement would have taken 5 additional lines without substantially contributing to readability.

That said, IIf in VB has a nasty caveat: unlike If, which is a proper language statement and evaluates only one branch, IIf is a built-in function, so both branches get evaluated, no matter what the condition says. As long as the branches don't have side effects, you won't notice, but when they do, you're in for some serious face-palming.

Body:
As far as performance goes: In a fully-compiled language like C or C++, with optimizations on, the difference is probably zero. In other languages (interpreted, byte-code-compiled, or jit-compiled) there may be a difference, but 1. it's not going to be much and 2. it's not going to be your bottleneck. There are exceptions, but those are rare, and if you encounter one of them, you're probably fiddling with fine-grained profiling and instruction-level optimizations; in all the other cases, either is going to be fast enough.

So, as always, your first choice should be to optimize for readability, not for runtime performance. Which brings us to the question when you should use one or the other; well, opinions differ. One camp says the ternary operator simply shouldn't be used at all, for clarity's sake; and they certainly have a point, because it has the tendency to make for really complicated one-liners, especially if you nest it, but also because its precedence can lead to undesirable results. However, I think there are situations where a ternary operator makes the code more readable, and I don't see anything wrong with using it in such a situation; a textbook example is simple text pluralizing:

printf("%i %s deleted.", num_files, (num_files > 1) ? "files" : "file");

The same code written with an explicit if statement would have taken 5 additional lines without substantially contributing to readability.

That said, IIf in VB has a nasty caveat: unlike If, which is a proper language statement and evaluates only one branch, IIf is a built-in function, so both branches get evaluated, no matter what the condition says. As long as the branches don't have side effects, you won't notice, but when they do, you're in for some serious face-palming.


问:
What is the supposed productivity gain of dynamic typing?
I often heard the claim that dynamically typed languages are more productive than statically typed languages. What are the reasons for this claim? Isn't it just tooling with modern concepts like convention over configuration, the use of functional programming, advanced programming models and use of consistent abstractions - all of which could be used in statically typed languages as well? Admittedly there is less clutter because the (for instance in Java) often redundant type declarations are not needed, but you can also omit most type declarations in statically typed languages that use type inference, without losing the other advantages of static typing. And all of this is available for modern statically typed languages like Scala as well.

So: what is there to say for productivity with dynamic typing that really is an advantage of the type model itself?

Clarification: I'm more interested in big / medium sized projects than in quick hacks. :-)

答:
The big advantage of dynamic typing is productivity.

Python, Ruby etc. have lots of other productivity boosters besides dynamic typing (default parameters, dictionaries as built in types etc.etc.) the cumulative effect on programmer productivity is impressive.

The penalties in terms of speed (or lack of!) and resource consumption are not as bad as you would expect and in most cases are more than compensated for by development speed and flexibility.

There is a (very old!) paper on the subject here. It is one the the few properly conducted studies on programmer productivity and many of the conclusions are still valid.

What would (probably) be different were the study to be conducted today:-

Java JVMs have improved beyond recognition.

Modern IDEs would have improved the C++, and Java coders productivity, but, made very little difference to the scripting languages.

C# would be included and probably be in the same ball park as Java but slightly better.

So the message is unless performance is a really serious issue dynamic languages will boost your productivity.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Suggestion for setting web application parameters
I'm creating a web application on GWT. I'm using MVP pattern with activities and places. I have a xml config file containing some parameters to be used by the application. Content of this xml file is sent to the client using HttpRequest; I'm using a singleton class to hold the  information from the xml file.

Right now, the application is getting the data when the user starts the application in the home page, that is working well. Now, since I'm using activities and places, a user can bookmark a page and starts the application in any other page (Place). And here comes the problem: Since I'm using some of the information from the xml file to set some ui widgets, I have to check if the xml config file was read and the application already has the parameters (I do this by checking the singleton class). But the xml file is read by using an HttpRequest, so I got errors 'cause the application needs some parameters to initialize some ui widgets, but these parameters aren't ready on time.

I was thinking on using an synchronous request to fix the problem, but it seems complicated and not recommendable to do that. So, I'd like to hear some other suggestions.

Thanks.

答:
Could you use a dynamic host page to seed the page with the configuration parameters?   See the GWT wiki article:

Using a Dynamic Host Page for Authentication and Initialization

You might have to switch to using JavaScript to hold the initialization data in the page using this approach.


问:
What would you do if your client required you not to use object-oriented programming?
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?

答: Explain to your client that if he wants functional programming, he should hire someone who specializes in that. Functional programming is very different from OOP, and you will be mistaken if you think you can easily pick it up and deliver a complex solution of high quality.</p>


问:
How to deal with checked exceptions that cannot ever be thrown
Example:

```<code>foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
</code>```

Since the encoding is hardcoded and correct, the constructor will never throw the UnsupportedEncodingException declared in the specification (unless the java implementation is broken, in which case I'm lost anyway). Anyway, Java forces me to deal with that exception anyway.

Currently, it looks like that

```<code>try {
    foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
}
catch(UnsupportedEncodingException e) { /* won't ever happen */ }
</code>```

Any ideas how to make it better?

答:
If I had been given a cent for every time I've seen an log/error, "This should never happen", I would have...  well, two cents.  But still...

Empty catch blocks makes my spider senses tingle and most good code analyzer tools complain.  I would avoid at all costs to leave them empty.  Sure, now you know the error can never happen, but a year from now someone does a global search-replace of "ISO-8859-1" and suddenly you may have an extremely hard to find bug.

The assert false suggestion is good, but since assertions can be disabled at runtime, they are no guarantee. I'd use a RuntimeException instead. Those won't have to be caught by calling classes and if they ever occur you will have a stack trace to give full information.


问:
How to document and teach others "optimized beyond recognition" computationally intensive code?
Occasionally there is the 1% of code that is computationally intensive enough that needs the heaviest kind of low-level optimization. Examples are video processing, image processing, and all kinds of signal processing, in general.

The goals are to document, and to teach the optimization techniques, so that the code does not become unmaintainable and prone to removal by newer developers. (*)

(*) Notwithstanding the possibility that the particular optimization is completely useless in some unforeseeable future CPUs, such that the code will be deleted anyway.

Considering that software offerings (commercial or open-source) retain their competitive advantage by having the fastest code and making use of the newest CPU architecture, software writers often need to tweak their code to make it run faster while getting the same output for a certain task, whlist tolerating a small amount of rounding errors.

Typically, a software writer can keep many versions of a function as a documentation of each optimization / algorithm rewrite that takes place. How does one make these versions available for others to study their optimization techniques?

Related:

Clean readable code vs fast hard to read code. When to cross the line?

答:
As a researcher I end up writing quite a bit of the "bottleneck" code. However, once it is taken into production, the onus of integrating it into the product and providing subsequent support falls to the developers. As you can imagine, communicating clearly what and how the program is supposed to operate is of the utmost importance.

I have found that there are three essential ingredients in completing this step succesfully

The algorithm used must be absolutely clear.

The purpose of every line of implementation must be clear.

Deviations from expected results must be identified as soon as possible.

For the first step, I always write a short whitepaper that documents the algorithm. The aim here is to actually write it up so that another person can implement it from scratch using only the whitepaper. If it's a well-known, published algorithm it's enough to give the references and to repeat the key equations. If it's original work, you will need to be quite a bit more explicit. This will tell you what the code is supposed to do.

The actual implementation that is handed off to development must be documented in such a manner that all the subtleties are rendered explicit. If you acquire locks in a particular order to avoid deadlock, add a comment. If you iterate over the columns instead of over the rows of a matrix because of cache-coherence issues, add a comment. If you do anything even slightly clever, comment it. If you can guarantee the whitepaper and the code will never be separated (through VCS or similar system), you can refer back to the whitepaper. The result can easily be over 50% comment. That's alright. This will tell you why the code does what it does.

Finally, you need to be able to guarantee correctness in the face of changes. Fortunately we a handy tool in automated testing and continuous integration platforms. These will tell you what the code is actually doing.

My most hearty recommendation would be not to skimp out on any of the steps. You will need them later ;)


答:
I've always done it like this:

```<code>try {
    foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
} catch(UnsupportedEncodingException e) {
    throw new AssertionError(e);
}
</code>```

May be a bit verbose (Java is...), but at least you'll get an assertion error when the impossible happens.

If the Java implementation is broken, you'll want to get as good error message as possible, as quickly as possible, instead of just ignoring the impossible. And even if the Java implementation isn't broken, someone could have changed your code to "UTF8" (oops - should it have been "UTF-8"?).

This should have been a runtime exception in the first place. JDK is full of this sort of wrong choices.

Title: How to deal with checked exceptions that cannot ever be thrown

Body:
Example:

```<code>foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
</code>```

Since the encoding is hardcoded and correct, the constructor will never throw the UnsupportedEncodingException declared in the specification (unless the java implementation is broken, in which case I'm lost anyway). Anyway, Java forces me to deal with that exception anyway.

Currently, it looks like that

```<code>try {
    foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
}
catch(UnsupportedEncodingException e) { /* won't ever happen */ }
</code>```

Any ideas how to make it better?

Body:
I've always done it like this:

try {
    foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
} catch(UnsupportedEncodingException e) {
    throw new AssertionError(e);
}

May be a bit verbose (Java is...), but at least you'll get an assertion error when the impossible happens.

If the Java implementation is broken, you'll want to get as good error message as possible, as quickly as possible, instead of just ignoring the impossible. And even if the Java implementation isn't broken, someone could have changed your code to "UTF8" (oops - should it have been "UTF-8"?).

This should have been a runtime exception in the first place. JDK is full of this sort of wrong choices.


问:
Why is Perl 5's smart-match operator considered broken?
I've seen a number of comments across the web Perl's smart-match operator is broken.
I know it originally was part of Perl 6, then was implemented in Perl 5.10 off of an old version of the spec, and was then corrected in 5.10.1 to match the current Perl 6 spec.

Is the problem fixed in 5.10.1+, or are there other problems with the smart-match operator that make it troublesome in practice?

What are the problems?

Is there a yet-more-updated version (Perl 6, perhaps) that fixes the problems?

Edit: To clarify, I'm not asking about bugs, but rather the opinion that the intended behavior of ~~ is bad.

答:
The smart match operator wasn't "broken", but it had lots of bugs. Perl v5.12 fixed that, and Perl v5.14 perfected it IMHO. So, to answer your question, Perl v5.12 and up fixes this problem. You can try it with later versions of Perl v5.10, but I know it works better in Perl 5.12+.

Edit: To answer your edit, see this blog. After reading the article, I believe it sufficiently answered your question.


答:
After talking it over with the client, if he still wants it his way, you either do a professional job, or if you can't then you either don't take the contract or find some way out of it.

Producing "crappy code" just because you disagree would be highly unprofessional.

Title: What would you do if your client required you not to use object-oriented programming?

Body:
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?


问:
How can I convince cowboy programmers to use source control?
I work on a small team of devs, 4 guys.  They have all used source control.  Most of them can't stand source control and instead choose not to use it. I strongly believe source control is a necessary part of professional development. Several issues make it very difficult to convince them to use source control:

The team is not used to using TFS.  I've had 2 training sessions, but was only allotted 1 hour which is insufficient.

Team members directly modify code on the
server.  This keeps code out of sync.  Requiring comparison just to be sure you are working with the latest code.  And complex merge problems arise

Time estimates offered by developers exclude time required to fix any of these problems.  So, if I say nono it will take 10x longer...I have to constantly explain these issues and risk myself because now management may perceive me as "slow".

The physical files on the server differ in unknown ways over ~100 files.  Merging requires knowledge of the project at hand and, therefore, developer cooperation which I am not able to obtain.

Other projects are falling out of sync.  Developers continue to have a distrust of source control and therefore compound the issue by not using source control.

Developers argue that using source control is wasteful because merging is error prone and difficult.  This is a difficult point to argue, because when source control is being so badly mis-used and source control continually bypassed, it is error prone indeed.  Therefore, the evidence "speaks for itself" in their view.

Developers argue that directly modifying server code, bypassing TFS saves time.  This is also difficult to argue.  Because the merge required to synchronize the code to start with is time consuming.  Multiply this by the 10+ projects we manage.

Permanent files are often stored in the same directory as the web project.  So publishing (full publish) erases these files that are not in source control.  This also drives distrust for source control.  Because "publishing breaks the project".  Fixing this (moving stored files out of the solution subfolders) takes a great deal of time and debugging as these locations are not set in web.config and often exist across multiple code points.

So, the culture persists itself.  Bad practice begets more bad practice.  Bad solutions drive new hacks to "fix" much deeper, much more time consuming problems.  Servers, hard drive space are extremely difficult to come by.  Yet, user expectations are rising.

What can be done in this situation?

答:
You obviously have the technical skills to identify and fix your situation, your problems are human and process related.

People tend to respond far better to example than vision, so I would suggest "fixing" it yourself:

Take a copy of the latest source, re-structure it to be version control friendly, create a new project with a useful, forward looking structure (work out how you're going to handle branches, where you put 3rd party dependencies etc). You'll probably have to do that in your own time.

Then drag your co-workers and management into a room and show them what software development looks like in the 21st century. Illustrate the failures with your current system and show how they're eliminated with your new structure.

You'll also have to have to set yourself up as the Keeper of the Source - since you appear to be the only one who cares, it's up to you to force people (with whatever technical or psychological means at your disposal) to stick to the plan. Ensure that the only thing going to a customer has come from a build machine out of source control. Ritually humiliate people who break the rules and cause havoc. Bribe them with donuts... whatever works.

If that all seems like too much effort then (as has been said in just about every other answer) - get another job. They're not worth your time.


问:
What would be the prototype of printf?
look at these calls closely:

```<code>printf("hello, world\n");
printf("%d", 2);
printf("%d%g\n", 2, 2.3);
</code>```

we see that printf can accept any type and any number of args.
however we know that functions in c only take fixed length args and should have a compatible prototype to match the arg.
what would be the prototype of printf ?

答:
we know that functions in c only take fixed length args

So you know it incorrectly. printf (and several other standard library functions) use a language feature called variable argument list.

Btw its signature declaration looks more or less like this (may be different on your platform):

```<code>int printf ( const char * format, ... );
</code>```

Title: What would be the prototype of printf?

Body:
we know that functions in c only take fixed length args

So you know it incorrectly. printf (and several other standard library functions) use a language feature called variable argument list.

Btw its signature declaration looks more or less like this (may be different on your platform):

int printf ( const char * format, ... );


答:
```<code>extern int printf (__const char *__restrict __format, ...);
</code>```

The ellipsis indicate that this function uses a variable argument list.

Title: What would be the prototype of printf?

Body:
look at these calls closely:

```<code>printf("hello, world\n");
printf("%d", 2);
printf("%d%g\n", 2, 2.3);
</code>```

we see that printf can accept any type and any number of args.
however we know that functions in c only take fixed length args and should have a compatible prototype to match the arg.
what would be the prototype of printf ?

Body:
extern int printf (__const char *__restrict __format, ...);

The ellipsis indicate that this function uses a variable argument list.


答:
This is a good example of a project where bad practices have been used so pervasively that it becomes practically impossible to fix it up. Fixing it would require a freeze, so everything can be cleaned up without interruption. Unfortunately, such projects usually are (for obvious reasons) too buggy to be frozen for several months, critical bugs must be fixed every other day.

You might be tempted to fork the project to create a clean version while the dirty version is treated with those daily bugfixes; but the most likely result is that after several months, when the "clean" version is finished, nobody can tell you which bugfixes and changes have been incorportated since the fork (because the same mindset that lets people slip into such practices makes it unlikely that they keep records about the changes they make). The clean version is outdated, the dirty version still kinda works, so what happens? The clean version is dumped, the naysays proven right.

Title: How can I convince cowboy programmers to use source control?

Body:
I work on a small team of devs, 4 guys.  They have all used source control.  Most of them can't stand source control and instead choose not to use it. I strongly believe source control is a necessary part of professional development. Several issues make it very difficult to convince them to use source control:

The team is not used to using TFS.  I've had 2 training sessions, but was only allotted 1 hour which is insufficient.

Team members directly modify code on the
server.  This keeps code out of sync.  Requiring comparison just to be sure you are working with the latest code.  And complex merge problems arise

Time estimates offered by developers exclude time required to fix any of these problems.  So, if I say nono it will take 10x longer...I have to constantly explain these issues and risk myself because now management may perceive me as "slow".

The physical files on the server differ in unknown ways over ~100 files.  Merging requires knowledge of the project at hand and, therefore, developer cooperation which I am not able to obtain.

Other projects are falling out of sync.  Developers continue to have a distrust of source control and therefore compound the issue by not using source control.

Developers argue that using source control is wasteful because merging is error prone and difficult.  This is a difficult point to argue, because when source control is being so badly mis-used and source control continually bypassed, it is error prone indeed.  Therefore, the evidence "speaks for itself" in their view.

Developers argue that directly modifying server code, bypassing TFS saves time.  This is also difficult to argue.  Because the merge required to synchronize the code to start with is time consuming.  Multiply this by the 10+ projects we manage.

Permanent files are often stored in the same directory as the web project.  So publishing (full publish) erases these files that are not in source control.  This also drives distrust for source control.  Because "publishing breaks the project".  Fixing this (moving stored files out of the solution subfolders) takes a great deal of time and debugging as these locations are not set in web.config and often exist across multiple code points.

So, the culture persists itself.  Bad practice begets more bad practice.  Bad solutions drive new hacks to "fix" much deeper, much more time consuming problems.  Servers, hard drive space are extremely difficult to come by.  Yet, user expectations are rising.

What can be done in this situation?


问:
Creating A Library That Requires Other Libraries (PHP)
Let's says that I am creating a PHP library that is using PHP 5.3 and namespaces and my library requires another library to work (this case it is the sfYaml library). I am trying to think of the best way to include this library.

Is it considered good/acceptable practice to include the third party libraries directly in my code (assuming the license allows which sfYaml does) or is it better to not include the third party libraries and just have the user make sure the libraries are somewhere on their system and have them configure the path?

I mean that only issue I have had in the past with including that third party libraries in my libraries is that if the user also has the same library for their project, there would be issues with including it twice however now with PHP 5.3 and namespace, that is not an issue.  I am just try to think if there are any other issues with including third party libraries directly in my code (with having them namespaced under my main namespace).

答:
The main issue with redistributing a third party library with your code is licencing. You should make sure that:

The third party library is licenced under a licence that allows redistribution,

The third party library is licenced under a licence that allows modification,

The licence of your code is not incompatible with the third party library licence.

Point 2 applies for the small changes to convert the third party library into your namespace hierarchy. Now you may assume that the MIT Licence, allows for all three points, but if you don't tell us your choice of licence we can't be certain.

If everything is fine with the licences, then I'd say it's a good practice to distribute all dependencies with your code. Users of your code may already have some of them, but you can't be sure which version they have. Better give users everything they'll need and everything you tested against, namespaces work wonders in those situations. You could have a \your_top_level_namespace\3rd_party namespace and put all dependencies under it.


答:
Why are we all assuming the client knows the difference between functional and imperative programming? A lot of people don't know the names or specifics of non OO programming paradigms and will readily interchange terms like "procedural" "imperative" and "functional".

Do not walk how others tell you to walk unless you believe you should walk that way. Therefore if you don't believe functional programming is suitable then don't set yourself up to fail or take on a project half-heartedly.

If the client writes the spec then implement the spec, otherwise you write the spec and implement your spec.

The best strategy to influence clients' decisions is to make the undesirable option significantly more expensive. It works everytime.

If you are the expert (relative to the client), then you should be able to persuade them.

In order to really know whether the client has a valid point, you need to gain more experience with functional programming, either so you can shoot it down with confidence or realise that your bias towards OO is due to your inexperience.

Why not do it both ways then let the client see both implementations and decide which is easier to maintain. Just factor all this into your project estimates so you can enjoy the learning curve while you get paid.


答:
You are mixing up data-structures and object-oriented-programming (a common confusion in this OO infested world)

If all you need to do is "track data attributes" in a data structure and modify them then almost any language made after the 70s will have good suppot for it, OO or not.

The things that are easier to do in OO are roughfly

Class based inheritance  (its easy to create a new class that pretends to be an old one)

Class based polymorphism (its easy to add new kinds of ant to the simulation afterwards)

If you don't have a pressing need of one of these then basically any programming paradigm should solve this without too many problems.


问:
Is there any reason to use VARCHAR sizes rounded to a 128/256/4096 byte offset?
In database schema's, I often notice VARCHAR sizes are rounded to the byte offsets 128/256 or 4096. I've done it before as well, and the idea behind it was probably something with efficiency.

However, is there still a valid reason to do so nowadays?
I often use '50', '100' or '200' as VARCHAR sizes these days,
as they are more natural and typically also shown in validation checks to the user.

答:
It probably doesn't really matter, since you'd really only see some storage efficiency if the size of your entire row happened to be a power of 2.  It's possible that sticking with powers of 2 could make it more likely that your row size would work out to a power of two (since most native data types tend to be power-of-2-sized [depending on database]), but I wouldn't make it a hard-and-fast rule.

It might make more sense if you were working with large (4K or larger) columns, since those could possibly be stored separately, and sizing them so that they fit within one storage block (whatever your database uses for on-disk storage) would gain you something.


问:
Increase Performance of VS 2010 by using a SSD
After searching on the internet for performance improvements when using Visual Studio 2010 with a solid state hard drive, I heard a lot of different opinions.

A lot of people said that there isn't really a benefit when using a SSD, but in contrast others said the exact opposite. I am a bit confused with the contrasting opinions and I cannot really make a decision whether buying a SSD would make a difference.

What are your experiences with this issue and which SSD did you use?

答:
I think a lot of it comes down to what languages you're planning on programming in on VS2010.

For example I know that on fast machines, C# compiles in under 5 seconds on a relatively large project.

On the other hand, programming Native C++, takes ~45 seconds for a project of the same size.

In my own experience, for compile times I don't think an SSD will make much of a difference.

That being said, the launch time of VS2010 on your computer will definitely be shorter than using a conventional hard drive if you use an SSD, but whether that's worth it or not to you is your choice.

Hope that helps.

EDIT: I may be able to play around with this today if anyone is interested. I own an OCZ Vertex 3 120GB, I can install Visual Studio on it and give you a rough estimate in comparison to my work PC, which is roughly equivalent PC specs. I'll make a copy of my project and hope that I can have it compile at home. I will update you sometime later today

OwnerDisplayName: Brutick


问:
How is the facade pattern different from abstraction layers?
I just read about the facade pattern and found this example where a client (user of a computer) invokes a startComputer() method which calls on all the complex stuff:

Source: wikipedia

```<code>/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}

class Memory {
    public void load(long position, byte[] data) { ... }
}

class HardDrive {
    public byte[] read(long lba, int size) { ... }
}

/* Facade */

class Computer {
    private CPU cpu;
    private Memory memory;
    private HardDrive hardDrive;

    public Computer() {
        this.cpu = new CPU();
        this.memory = new Memory();
        this.hardDrive = new HardDrive();
    }

    public void startComputer() {
        cpu.freeze();
        memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
        cpu.jump(BOOT_ADDRESS);
        cpu.execute();
    }
}

/* Client */

class You {
    public static void main(String[] args) {
        Computer facade = new Computer();
        facade.startComputer();
    }
}
</code>```

Here we can see the client class (You) creating a new facade, calling the startComputer() method. This method instantiates several objects and invokes their methods, encapsulating it inside the facade class where it 'glues it together'.

Question 1:

But exactly how is this different from layers of abstraction?

Yesterday I made login functionality for a web application where a doLogin($username, $password) encapsulated a 'complex' lower-layer method call that updated login info about the user, set sessions to log in with and instantiated several objects etc. to do this job.

This layer would also call another even lower level which would deal with CRUD-like operations such as checking activation status, account existance and other things like processing strings through hashing algorithms. This method (on model level, look 'layer overview' below) would return an array with either a 'success' key or a 'error_message' key, acting as a boolean of sorts to the layer calling it.

This is what I understand is known as 'abstraction layers', hiding complex procedures from the higher-level architecture, but when I read about the facade pattern it seems like I have been using it all along?

Question 2:

Would my approach to abstracting the login mechanism be a bad choice in a MVC architecture? (if not, please give examples why)

Taken into consideration it should be very easy to decide where the end result goes (HTML, AJAX, etc.), wouldn't this be a wise choice to avoid alot of IFs as this can be dealt with on a controller layer?

Layer overview:

Controller layer: $model->doLogin(POST VARIABLES HERE)

Model layer: (Is this a facade?) Sets sessions, updates login information in database etc., calls independent components for information: $user_id = $user->getId(); and $session->sessionExists();

Independent class layer: Each class on this layer is independent and has little to no coupling. After all, why would it? It's the layer above's job to build the application and lend an API to control it with.

Question 3:

Is the facade pattern only used for routing calls to sub-classes in an API-like form, or perhaps just most commonly?

With this I mean: Object A instantiates object B and lends a method to control object B's methods through a method of it's own:

```<code><?php

class A {
    private $_objectB;

    public function __construct()
    {
        $this->_objectB = new B();
    }

    public function callMethodB()
    {
        $this->_objectB->methodB();
    }
}

class B {
    public function methodB()
    {
        die('Wuhu!');
    }
}

// --------------------------
$objectA->callMethodB(); // Wuhu!
</code>```

instead of:

```<code>$objectA->objectB->methodB(); // Wuhu!
</code>```

答:
The relationship between the two: The Facade pattern is a subset of "layers of abstraction". A Facade is an added level of abstraction. Not all abstractions are Facades.

Specifically, a Facade is where we offer a simplified interface to a complex API. Sometimes we are wrapping numerous complex classes in one simple one; sometimes we are just taking one class with a complex API and simplifying it for the calling code.

If you are simply forwarding one call to another class with the same interface, that is more accurately the Proxy pattern. This is another type of abstraction layer.

Is it a good idea to abstract logging out in an MVC pattern? Yes (most MVC frameworks will do this for you). But whether you should be abstracting it using a Proxy or a Facade depends very much on the login API.


问:
What benefits are there to native JavaScript development?
Given how much simpler jQuery development is, when compared to native JavaScript, what makes people forgo libraries like jQuery altogether?

Is this because jQuery has limitations or it is slow? I mean, if jQuery is so easy compared to native javascript, what reasons do people have to still use pure javascript?

答:
In the browser environment you need a cross browser normalization tool. Such a tool comes in two flavours

wraps host objects with new objects which behave the same way across browsers

extend host objects to implement the DOM API.

Generally you can use these utilities in one of three ways

use small functions like addClass or setText throughout your code when and where you need them

write your own cross browser normalization library

use an existing one.

You need some mechanism of normalization otherwise you get zero cross browser support.

As for using an existing one, that's fine. I just wouldn't use jQuery. Personally I'm currently writing my own library (DOM-shim it fixes browsers without exposing a foreign propietory API. It turns your browsers into a single well behaved standardized browser).

OwnerDisplayName: Mike


答:
I think it makes a huge difference. VS (like windows) is constantly writing to the disk. This is surprising slow, even for small amounts of data. I put a SSD in an old laptop and it made it about 5 times faster. You can see the results.

Although I don't have any first-hand experience with VS and SSD's, I am sure it will make everything much faster.

One thing to be aware of: SSD's have very high failure rates (including the first one I purchased). Buy one that is highly rated such as this one. Also, you don't need a particularly large SSD. Just big enough to hold the OS, program files and your project with at least 20% free is fine. So perhaps 128GB.

Title: Increase Performance of VS 2010 by using a SSD

Body:
After searching on the internet for performance improvements when using Visual Studio 2010 with a solid state hard drive, I heard a lot of different opinions.

A lot of people said that there isn't really a benefit when using a SSD, but in contrast others said the exact opposite. I am a bit confused with the contrasting opinions and I cannot really make a decision whether buying a SSD would make a difference.

What are your experiences with this issue and which SSD did you use?


答:
There are several good aspects in their request to use functional programming:

You have a client, it's always a good sign

The client expects you to be very good at what you're doing. This is why they ask functional programming. So your sales organisation is doing a good job or you're asking very high price for your services.

Client organisation has some people who know functional programming is a good thing and will be big in the future

But there are some alarming signs also:

You don't seem to be prepared to implement it in functional programming. You're already slightly outdated in your skills and cannot keep up with the changes.

Or the client is expecting you to be better programmer than you really are. This means you might need to downgrade their requirements until you can do it properly.


答:
The only rational explanation I can think of would be: If the DBMS stores the values of a column sequentially, and the sizes are not rounded to a power of 2, then some elements may have to be "split" into two pages on the hard drive (e.g. the first 10 bytes in page n and the next 40 bytes in page n+1), which might in some cases lead to two reads from the hard drive instead of one.

More likely is @Jan Hudec's point that, many programmers think of "128" or "256" as "nice round numbers", which makes them a more natural choices than odd numbers like 137, 19 or 100.

Title: Is there any reason to use VARCHAR sizes rounded to a 128/256/4096 byte offset?

Body:
In database schema's, I often notice VARCHAR sizes are rounded to the byte offsets 128/256 or 4096. I've done it before as well, and the idea behind it was probably something with efficiency.

However, is there still a valid reason to do so nowadays?
I often use '50', '100' or '200' as VARCHAR sizes these days,
as they are more natural and typically also shown in validation checks to the user.


问:
Add an ID in every table even if it's not needed?
Is this good or bad design to add, by default, ID field in every table in a database, even when you don't see currently to usage of this ID (For instance in a MxN table) ?</p>

答:
Every table should have a PK,a an Unique identifier, or and ID as you are calling it.
In the Case of MxN you have PK, (a Compound one). So there is no need to have another.

Also See:
One or Two Primary Keys in Many-to-Many Table?

My Personal Preference pertaining to a related topic: PKs should not have another use aside from being a PK. So I would not use data a a PK, Even if the data is "Naturally unique"
IE: SSN, Date, Zip Code Ect.


问:
Does your company have a written policy about personal (technical) blogging?
Does your company have a written policy about personal (technical) blogging?

Care to share?

We encourage our developers to keep personal blogs and talk about technical problems they've encountered at work that are not core competency or core IP. We've been doing it "don't ask don't tell" style, but it's time to write something down.

Update: thank you all for your answers, we've implemented a policy for this last week - the full text is here.

答: I work for a Federal government agency.  The overall policy on any kind of social networking and blogging is that we should present ourselves as individuals and not as employees of the agency.  Pretty straightforward stuff.  They don't mind the exchange of "tips and techniques" as long as some internal things are not published.  That's never been a problem, as far as I know.</p>

ContentLicense: CC BY-SA 2.5


答:
From design point of view, go with the natural, compound primary key and don't invent a synthetic one. Anything that does not have to be there only makes the schema more complicated to understand.

From performance point of view in many databases it's faster to access table by integer primary key than by any other indexed column. These databases will also implicitly add such synthetic key to any table that does not have one (usually called "rowid" or "oid" or similar), so adding it explicitly will cost nothing at all.

For MxN (relation) tables it does not make sense to access them by primary key; you access them by either component and get the set of related entities from the other side. So for these tables it makes no sense to add synthetic primary key.

For other tables with good composed or non-integer primary key I would still not add synthetic one initially, but would consider adding it during performance tuning for tables accessed in performance critical tables.

Title: Add an ID in every table even if it's not needed?

Body: Is this good or bad design to add, by default, ID field in every table in a database, even when you don't see currently to usage of this ID (For instance in a MxN table) ?</p>


答:
In many cases, having an artificial ID on every table is very conveniant; in some cases, it's just a pain in the a**.

Generally, I do that on every project I'm working on.

Advantages:

It's generally easier to write or generate access code when each and every table can be accessed by a key field called ID, type Integer.

Sometimes, natural keys are volatile. For example, in an already very complex warehouse management system, we were faced with the task that product codes change, e.g. what has been product 001234 will be known as 002345 in the future. Unfortunately, that system didn't use artificial IDs, but the product code as the primary key. Naturally, the product code was also a foreign key in dozens of other tables. Therefore, renumbering was really difficult and expensive and couldn't be done during work hours. The next version of the software used artificial IDs, so it was just a simple UPDATE on the product table.

Sometimes, natural keys are not unique even if they should be. In my countries, for some reasons, a few SSN have been issued twice.

Concetentated keys become cumbersome when the data structure is complex; having a sub-sub-sub-table with a key concetenated of 4 parts is rather painfull to work with.

Disadvantages:

By their nature, those IDs have no meaning outside the system, so you need a lot of lookups to translate those IDs to natural keys.

Getting the top key from said sub-sub-sub-table requires a big join through the whole hierachy.

Merging incoming data with the existing records is more difficult, because again more lookups are needed.


问:
How are interrupts implemented in practice?
Consider an USB device that is receiving data over a wireless network and an application running on the PC is reading this data. Now, on many languages (consider C# DataReceived), we have event handling mechanisms to detect if Data has arrived or not.

My question is, how is this event detecting mechanism implemented?

Is it like, a running timer which periodically checks to inspect arrival of data, or is this something the hardware has to support?

In general, how are these changes in hardware state events implemented?

答:
Interrupts are a hardware mechanism similar to events.

Whenever a specific condition arises in the physical world (e.g. data arriving on USB), a line switches from one level to the other. This is an interrupt request.

The CPU is built to detect this change and to respond by jumping to an Interrupt Service Routine. This routine in turn generates a software event.


答:
USB is quite complicated because various parts of the protocol may be implemented in hardware depending upon the platform being used.  It might be easier to consider something a little simpler, perhaps a serial port controller.

The precise series of actions that are performed will depend upon the processor interrupt handling mechanism (some processors are more automated in servicing interrupts than others).  The description below is typical for the processors that I have used over the years.

Normally the serial controller receives a character it is programmed to raise an interrupt signal to the processor.  This is a physical signal that indicates to the CPU that there is some external event needing to be serviced.  This signal causes the processor to complete the current instruction and then to place its current execution address and processor status registers onto the stack.

The processing address is changed to the interrupt service routine.  There may be one service routine for all interrupts, or a number of interrupt routines one for each of the interrupt sources that the processor supports.  These interrupt functions have to poll the interrupting device to determine he reason for the interrupt and then perform the appropriate actions, in this case to read the character from the serial port and move it to the input serial data buffer to be used by the processor main application.

Once the interrupt processing has been completed the processor status and execution address are restored and processing then continues from the instruction after the last instruction executed before the interrupt happened.  It is extremely important that all of the processor registers used by the interrupt processing are restored to exactly the same state before the routine terminates so that the only effect of the interrupt on the main code is to insert a short delay into the main line processing code.

The interrupt code has to set event indicators to the main code so that the high level application code can detect that the interrupt event has happened.

Title: How are interrupts implemented in practice?

Body:
Consider an USB device that is receiving data over a wireless network and an application running on the PC is reading this data. Now, on many languages (consider C# DataReceived), we have event handling mechanisms to detect if Data has arrived or not.

My question is, how is this event detecting mechanism implemented?

Is it like, a running timer which periodically checks to inspect arrival of data, or is this something the hardware has to support?

In general, how are these changes in hardware state events implemented?


问:
Possibility Program for number of pieces
I would like to put a program together to calculate the number of 60' pieces would be needed from a list of shorter pieces.  For example, I sell rebar cut to length from our standard length of 60'-0".  Now the length the customer requires are as follows:

```<code>343 pc @ 12.5'
35 pc @ 13'
10 pc @ 15'
63 pc @ 15.5'.......
</code>```

There are 56 total lengths ranging from 12.5' to 30.58'

The idea is to limit the amount of waste from the 60' piece.
The input from the user would be:

number of differnt lengths

Length of piece to cut from

count of different lengths

The result would be the number of prime pieces needed to fulfill the order.

What well-known algorithms exist that could help me solve this problem?

答: This appears to be a variant of the Knapsack Problem - there's already a similar question here on Programmers.</p>


问:
What's the worst programming book you've ever read?
What's the worst programming-related or technical book you've ever read? This can be any book which one way or another can be connected to programming, as long as it's not fiction.</p>

答:
I can't remember the name - later I might see if I can dig it out - but there was an ASP.NET book I had that had all the code snippets (and there were a lot) as Visual Studio screenshots.  It seemed cool at first because it showed me exactly where to go in the IDE (I was just learning at that point).  After a while though (Chapter 2, I think), I found I knew where everything was and I was just finding the shots too difficult to read.

Pro C# by Andrew Troelsen was mostly very good, but someone needs to teach the man to use examples properly.  He'd teach one technique for a topic (let's say multithreading), then teach another and compare the two.  The problem is that rather than simply updating the first sample with the new code, he'd write a totally new application that does something totally different, and throw a bunch of extra concepts into the mix as well.


答: The real problem is not that the cowboy coders do not use version control. The real problem is that they've already chosen some way of doing things, and you're trying to change their process. The chosen process do not include version control. All process changes are difficult, unless the programmers themselves notice a problem. If there is a feeling that the existing system is good enough, trying to impose some different system is just futile. We are the borg, you will be assimilated. Of course they're trying to fight becoming borg.</p>


答: Developers who refuse to use source/version control should be fired, simple as that. As you have already pointed out, the inherent risks and costs of NOT using it outweigh any overhead it incurs by many, many orders of magnitude. Anyone trying to argue against this simply should not be involved in software development and I would flat out refuse to work with such people.</p>


问:
How to properly shield a Product Owner from outside?
Update: We are a very small team (3 people) and thus I (Scrum Master) and the Product Owner are also developers doing some coding.

We are aware of this situation and we are actively trying to recruit some new talents. But it's hard!

Meanwhile... we need to adapt... so my question:

The Product Owner complains about having too much outside noise (mainly stakeholders feature requests), and he can't focus on the sprint realisation.

We agree that we should try to educate people on our process implications (sprint durations and product backlog), to reduce the noise.

But as a Scrum Master, how am I supposed to shield a PO from outside? Isn't he supposed to be in contact with the management and business?

Also, if people outside don't want to waste too much time learning agile, what is the best way to educate them?

答: The product owner's responsibility IS to interact with the stakeholders to find out what should be part of the product in development and strictly speaking he IS NOT a part of the development team. Thus he is the requested shield of your development team against requests from the outside.</p>


答:
I feel that assigning the role of PO to a developer is usually the wrong choice. As you noted, the PO is supposed to communicate a lot with external parties, precisely to shield the development team from interruptions, to filter and enhance incoming feature/bug requests (again, via extended discussion with users / stakeholders) and to prioritize stories.

So apart from this role requiring lots of communication, IMHO prioritization should not normally be the task of a developer.

Of course, if your team is very small, someone may need to do it nevertheless, but than (s)he should understand the requirements for this role and not complain too much after accepting it :-)

Title: How to properly shield a Product Owner from outside?

Body:
Update: We are a very small team (3 people) and thus I (Scrum Master) and the Product Owner are also developers doing some coding.

We are aware of this situation and we are actively trying to recruit some new talents. But it's hard!

Meanwhile... we need to adapt... so my question:

The Product Owner complains about having too much outside noise (mainly stakeholders feature requests), and he can't focus on the sprint realisation.

We agree that we should try to educate people on our process implications (sprint durations and product backlog), to reduce the noise.

But as a Scrum Master, how am I supposed to shield a PO from outside? Isn't he supposed to be in contact with the management and business?

Also, if people outside don't want to waste too much time learning agile, what is the best way to educate them?


答:
Either drop his Responsibilities as a Product Owner or as Developer. What he is trying to say is he simply doesn't have time to do Both.

OR

Get him additional development resources.

I simply disagree with the others who say one person can't do both. One person absolutely can.


答:
synthetic keys vs natural keys and single keys vs compound keys are both hotly debated topics that have good positives and negatives on both sides.  They are like the tabs vs spaces and curly brackets on their own line debates.

The most important thing is to pick a side and stick with it for consistency throughout the database. generally synthetic keys are used simply because it's hard to have a good natural key for every table and its much easier to be consistent when every table has a synthetic key.


问:
Dynamically vs Statically typed languages studies
Do there exist studies done on the effectiveness of statically vs dynamically typed languages?

In particular:

Measurements of programmer productivity

Defect Rate

Also including the effects of whether or not unit testing is employed.

I've seen lots of discussion of the merits of either side but I'm wondering whether anyone has done a study on it.

答:
Here's a starting point:

Do Programming Languages Affect Productivity? A Case Study Using Data from Open Source Projects (Delorey, Knutson, Chun, 2007)

The paper is challenging the commonly received wisdom that, all else being equal, programmers write the same number of lines of code per time regardless of language. In other words, the paper should serve as supporting empirical evidence that mechanical productivity (lines of code written) is not a good measure of functional productivity, and must at least be normalized by language.


答:
Although Scrum, as it's defined by Sutherland and Schwaber, doesn't object to the combination of Product Owner and development team member, it sounds like that is problematic in this particular case. The primary responsibility of the person who is designated as Product Owner is to be the voice of the customer, performing tasks such as writing user stories, prioritizing the stories, and generally managing the product backlog.

As a Scrum Master, you should not be shielding the Product Owner from the outside. It is the job of the Product Owner to interface with any clients or users of the system to create and prioritize the requirements. In fact, the point of a Product Owner (and the Scrum Master) is to shield the Development Team from stakeholders so they can focus on designing, developing, and testing the system.

It sounds like, on this particular project, the job of the Product Owner is a full-time responsibility. As such, the Product Owner should be removed from the development team. If, during a sprint, there is sufficient time for the Product Owner to contribute to design, development, or testing, that's good, as long as you track the increase in human resources so you don't skew your velocity. However, the team shouldn't be counting on the Product Owner to be a contributing member of the development team.


问:
Would you use UML if it kept stakeholders from requesting changes frequently?
As much as programmers hate to document their code/system and draw UML (especially, Sequencing, Activity and State machine diagrams) or other diagramming notation, would you agree to do it if it kept managers from requesting a "minor change" every couple of weeks?

IOW, would you put together visual models to document the system if it helped you demonstrate to managers what the effect of changes are and why it takes so long to implement them?

(Edited to help programmers understand what type of answer I'm looking for.)

2nd edit: Restating my question again, "Would you be willing to use some diagramming notation, against your better nature as a programmer, if it helped you manage change requests?"

This question isn't asking if there might be something wrong with the process. It's a given that there's something wrong with the process. Would you be willing to do more work to improve it?

答:
I think the OP is confusing UML (a language for modeling) with requirements management (a process). Modeling your system in UML is not going to stop users from asking requirements. You use UML to capture your architecture and to map requirements to artifacts. A requirement change would invariable represent a change in your model.

These are systemic problems that you just don't "UML it out". There are things to consider here:

Change Scope:
Too large of a change, then either the request is disruptive, or your UML does not relate to the actual system, or your system has an inflexible architecture.

Rate of Requirement Change
Too frequent changes will cause you to 1) update your model and 2) deliver. So without a requirements management process, you are going to UML yourself to death, thus decreasing the rate of at which you produce results.

You could say that your productivity is inversely proportional to the rate of requirement change multiplied by a factor representing the UML "crust" artificially added to a process.

I would suggest you get a book on requirements management, and learn a bit about the way Scrum handles requirements. Say you previously had a requirement R, and the user now wants a change on R, say R'. Then you treat R' as new requirement with its new timeline. You have to communicate users that requirements changes have associated costs.

Also, it would do you well to study a bit of systems engineering and the concept of requirements as being:

Atomic.

Precise.

Unambiguous.

Testable/Verifiable.

Feasible.

A change request on a requirement is
a defect on the requirement. Thus,
it creates a new requirement, and
puts the onus on the originator
(typically the customer.)

There is such a thing as an invalid requirement. A requirement request that does not fill any of the above is an invalid requirement. And in a good process, the development team has the right to reject a requirement.

I mean, you ask an architect to design you a house without windows, he'll walk away. Or you ask repairman to fix your roof with clear tape, he'll give you the finger and walk away. Ask a dentist to remove a tooth from you using a pair of bolt cutters, he'll hit you with them and kick you out.

Only in software you see this notion that all requirements are valid and that they must implemented whatever the cost.

I recently put an answer to a related question, on requirements management and engineering. Maybe you might want to take a look at it. I hope you you find it helpful

How do you deal with changing requirements?


答:
It sounds like your PO has either misunderstood his role or this is his way of trying to say that he's wearing one hat too many. The PO is the person who should be the primary contact with outside stakeholders. If that noise is so loud at your shop that he can't maintain that as well as his programming duties, the role should be split and you need an additional resource. Realizing that your PO might see it as a sign of weakness to admit that he can't handle his load, I still advice you to take the discussion with him.

Document his work-load, how much time he spends on different activities and use this to build a case with your management to hire an additional resource for your team.


问:
What would you do if your client required you not to use object-oriented programming?
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?

答:
Before bothering any further, I'd make sure that you both are talking about the same thing. You could ask him for when software is 'object-oriented' to him. Sine he said that it's not his main expertise himself, it may be that he has some skewed idea.

For instance, many people could consider

```<code>class C {
public:
  C();
  void f( int );
  void g();
};
</code>```

to be a classical object-oriented approach, but

```<code>struct C;
void construct( C ** );
void f( C *obj, int arg);
void g( C *obj );
</code>```

not (even though both are equally object-oriented as far as the classical "data together with the functions which operate on it" definition goes).

Body:
Before bothering any further, I'd make sure that you both are talking about the same thing. You could ask him for when software is 'object-oriented' to him. Sine he said that it's not his main expertise himself, it may be that he has some skewed idea.

For instance, many people could consider

class C {
public:
  C();
  void f( int );
  void g();
};

to be a classical object-oriented approach, but

struct C;
void construct( C ** );
void f( C *obj, int arg);
void g( C *obj );

not (even though both are equally object-oriented as far as the classical "data together with the functions which operate on it" definition goes).


答: While I'm not familiar with all DBMS systems, the smallest "physical" unit of storage in Oracle is a "block" which by default is 2KB in size. The practice of sizing your columns in powers of two is part of a larger practice of sizing your rows to fit properly in storage blocks. Sizing your columns so one row would require one byte more than the block-size would require two blocks to be allocated and your row would also span two blocks, making reading, inserting and scanning more time consuming than if you could fit each row one block (and only have one row in each block). That, at least, is the historic reason for it. Nowadays, most people consider this practice to be sub-optimization.</p>


问:
Should security restrictions cause a service to return null or throw an exception?
I'm in a bit of a disagreement with a more experienced developer on this issue, and wondering what others think about it; our environment is Java, EJB 3, services, etc.

The code I wrote calls a service to get things and to create things. The problem I ran into was that I got null pointer exceptions that didn't make sense. For example, when I ask the service to create an object, I get null back; when I try to look up an object with a known valid ID, I get null back. I spent some time trying to figure out what was wrong in my code; since I'm less experienced I usually assume I've done something wrong, but it turns out the reason for the null returns was security. If the user principal using my service didn't have the right permissions for the target service, then it simply returns null. Most other services here aren't documented very well either, so apparently this is just something you have to know.

This is rather confusing as a developer writing code that interacts with the service. It would make much more sense to me if the service thew an exception that would tell me that the user didn't have the proper permissions to load this thing or to create that thing; I would then immediately know why my service wasn't working as expected.

The more experienced developer who wrote the service argued that asking for the data is not an error condition, and that exceptions should only be thrown in an error condition, not when the user doesn't have access to the data. This data is often looked up in a GUI, and for those users without the right permissions, these things simply "do not exist". So, in short: asking is not wrong, hence no exception. Get methods return null because to those users those things "don't exist". Create methods return null when the user wasn't allowed to create that thing.

Is this normal and/or good practice? I prefer using exceptions because I find it much easier to know what's going on. So I would for example also prefer to throw a NotFoundException if you asked for an object with an invalid ID, rather than returning null.

答:
To play devils advocate I will attempt to take the side of returning null.

In my opinion there is just one situation where this kind of response is nearly acceptable and that is, as in this case, when security is involved.

It is very easy to accidentally give away details of your system that unauthorized people should not know about. This should be avoided.

Take, for example, a user name and password checker. Returning a "User name not found" error and a "Wrong password" error as separate error codes would obviously open you up to serious security issues as someone could first look for a valid user name and then look for a password. Returning a generic "Invalid username/password" would be a better option.

Thus, In this particular case I would say that it is almost ok to return null but I agree, it would be very unpleasant to work with.


问:
How faster is an 'if' construct compared to an immediate 'if' statement (IIF) and when should I use it?
How does the traditional if statement compare with that of the immediate if statement (IIF, the one usually written as condition ? value_if_true : value_if_false) in terms of speed of execution?

Also, in what scenarios should we be ideally using the IIF?

答:
Micro-optimisation is rarely worth worrying about, and whether the ternary operator is executed faster than a full conditional definitely falls under the category of micro-optimisation.

Really, the ternary operator should be used when it makes the code clearer to read and thus easier to maintain and should be avoided where it makes the intent of the code more obscure and thus more difficult to maintain.

If you get to the stage where your application is not performing as well as you need it to perform, then you need to profile your application, benchmarking it with typical and worst case application loads. Only then can you see where you application is running too slowly and thus where to spend your time in optimising.

As it is, you are very unlikely to see any difference between code with uses IIf and code which doesn't, but to be sure you need to benchmark.

Finally, you have to be very careful about using the VB IIf() construct due to issues with side effects. The fact that value_if_true and value_if_false are always evaluated, irrespective of the value of the condition means that the IIf() version could behave very differently to the normal If construct it might be intended to replace.


问:
Schemes to resolve deadlocks
I am interested in research that detects and recover from deadlocks. In other words the system is able to recover from deadlock faults. I'm interested in shared memory multicore processors. Uptill now I have only seen research for distributed systems. Can anyone guide me on this.</p>

答:
The best way to recover from a deadlock condition is to never get into it in the first place.

Techniques such as Tony Hoare's Communicating sequential processes give you the ability to formally reason about your system, detect the potential for deadlock and design it out of your system. I would highly recommend looking into some of the work done on CSP over the years to see if these techniques could be incorporated into your systems.

OwnerDisplayName: MetallicPriest

Title: Schemes to resolve deadlocks


问:
How can I convince cowboy programmers to use source control?
I work on a small team of devs, 4 guys.  They have all used source control.  Most of them can't stand source control and instead choose not to use it. I strongly believe source control is a necessary part of professional development. Several issues make it very difficult to convince them to use source control:

The team is not used to using TFS.  I've had 2 training sessions, but was only allotted 1 hour which is insufficient.

Team members directly modify code on the
server.  This keeps code out of sync.  Requiring comparison just to be sure you are working with the latest code.  And complex merge problems arise

Time estimates offered by developers exclude time required to fix any of these problems.  So, if I say nono it will take 10x longer...I have to constantly explain these issues and risk myself because now management may perceive me as "slow".

The physical files on the server differ in unknown ways over ~100 files.  Merging requires knowledge of the project at hand and, therefore, developer cooperation which I am not able to obtain.

Other projects are falling out of sync.  Developers continue to have a distrust of source control and therefore compound the issue by not using source control.

Developers argue that using source control is wasteful because merging is error prone and difficult.  This is a difficult point to argue, because when source control is being so badly mis-used and source control continually bypassed, it is error prone indeed.  Therefore, the evidence "speaks for itself" in their view.

Developers argue that directly modifying server code, bypassing TFS saves time.  This is also difficult to argue.  Because the merge required to synchronize the code to start with is time consuming.  Multiply this by the 10+ projects we manage.

Permanent files are often stored in the same directory as the web project.  So publishing (full publish) erases these files that are not in source control.  This also drives distrust for source control.  Because "publishing breaks the project".  Fixing this (moving stored files out of the solution subfolders) takes a great deal of time and debugging as these locations are not set in web.config and often exist across multiple code points.

So, the culture persists itself.  Bad practice begets more bad practice.  Bad solutions drive new hacks to "fix" much deeper, much more time consuming problems.  Servers, hard drive space are extremely difficult to come by.  Yet, user expectations are rising.

What can be done in this situation?

答:
Lock down any server other than their development.  Use a configuration manager.  Do regular identifiable builds (against tags).  Tag every change set (ie 1 change set per bug).  We also put a tag on each build. Have a QA type system between dev and production (at a minimum).  Do builds to QA system using correct build tag.  Give them grief for "breaking the build".

I have never run into a situation where I couldn't re-create / fix an issue (that only shows on production).  Yes, I have spent hours getting the issue to recreate on a development system (plus when you figure it out you can add it to your regression test).

We did a project with a bunch of cowboy contractors who did all of those bad things.  I spend 4 weeks cleaning up after then and then put the above practices in place.  The project has had no issues with any of those things since then.


答:
Along with the other answers here, especially Michael Durrant's, I would saw speed is a major reason for me occasionally choosing to use raw JavaScript.

Lately I have been working on a lot of animations or other CPU-intensive tasks and some times raw JavaScript is much, much faster than if I go through jQuery.

One example is where I wanted to change the opacity of a position: fixed element in relation to how far down on a page a user has scrolled. The effect was way too slow when I used jQuery for this, causing scrolling to be jerky and the fade effect was ruined. I switched to using straight JavaScript and everything was silky smooth in all but IE <= 8.

Title: What benefits are there to native JavaScript development?

Body:
Given how much simpler jQuery development is, when compared to native JavaScript, what makes people forgo libraries like jQuery altogether?

Is this because jQuery has limitations or it is slow? I mean, if jQuery is so easy compared to native javascript, what reasons do people have to still use pure javascript?


问:
Should I update blog posts or rewrite them as technology (and me) changes?
I started a programming blog earlier this year, and since I started it some things have changed. Some changes are due to technology changing, some changes are due to my code libraries improving, and some (ok, probably most) are due to me changing as I learn more.

I want to go back and completely re-write certain blog posts. Is it better to rewrite posts to remove old information and update them with new stuff, or to create entirely new posts and possibly take down old ones?

I'm not talking about small changes to the code, or an extra few sentences, but complete rewrites with new code, new information, etc.

Some things to consider are comments on the post, subscribers who receive updates when new posts are created, and user bookmarks.

答:
I think the best approach is to leave the old entries/code samples where they are, and to add new ones with your new ideas/code samples. Then you can include a link on the older posts pointing to the new ones.

This approach allows both you and your visitors to see how your code/ideas evolved over time, which could be valuable. And there's nothing wrong with admitting the stuff you did/wrote a while ago was not as good as it could have been. The very fact that you are recognizing that is a sign of your progress.


答:
No such policy here

I do keep a personal / technical blog (more technical then personal), however it's not related in any way to companies I work for.

Publishing internal protocols, worksheets, code, or other thing would be a serious do not do in my opinion. Other then that I can see for very few reasons where keeping a technical blog would not be allowed. One might be in a case where the contract stipulates any and all material you create is owned by the company. There was an interesting article I read about someone who worked at Microsoft where this was the case. Can't find it again for the life of me though.

Body:
Does your company have a written policy about personal (technical) blogging?

Care to share?

We encourage our developers to keep personal blogs and talk about technical problems they've encountered at work that are not core competency or core IP. We've been doing it "don't ask don't tell" style, but it's time to write something down.

Update: thank you all for your answers, we've implemented a policy for this last week - the full text is here.


答:
I personaly dont like deleting old posts, information even if not up to date is still often usefull. Some people may for example be using the outdated librarys. Also some of the comments may be usefull in ways that are not immediately obvious

In my opinion the best to deal with this situation is to write a new post and clearly mark the new post as superseded with a link to the updated post at the top of the page.

Title: Should I update blog posts or rewrite them as technology (and me) changes?

Body:
I started a programming blog earlier this year, and since I started it some things have changed. Some changes are due to technology changing, some changes are due to my code libraries improving, and some (ok, probably most) are due to me changing as I learn more.

I want to go back and completely re-write certain blog posts. Is it better to rewrite posts to remove old information and update them with new stuff, or to create entirely new posts and possibly take down old ones?

I'm not talking about small changes to the code, or an extra few sentences, but complete rewrites with new code, new information, etc.

Some things to consider are comments on the post, subscribers who receive updates when new posts are created, and user bookmarks.


问:
What is the supposed productivity gain of dynamic typing?
I often heard the claim that dynamically typed languages are more productive than statically typed languages. What are the reasons for this claim? Isn't it just tooling with modern concepts like convention over configuration, the use of functional programming, advanced programming models and use of consistent abstractions - all of which could be used in statically typed languages as well? Admittedly there is less clutter because the (for instance in Java) often redundant type declarations are not needed, but you can also omit most type declarations in statically typed languages that use type inference, without losing the other advantages of static typing. And all of this is available for modern statically typed languages like Scala as well.

So: what is there to say for productivity with dynamic typing that really is an advantage of the type model itself?

Clarification: I'm more interested in big / medium sized projects than in quick hacks. :-)

答: Personally, the only reason dynamic typing would help is if you are a really slow typist or you build giant functions/methods/whatevers that are hard to navigate.  You also have to get into the whole unit testing issue.  Dynamic types require (unless you like writing broken code) vigorous unit tests (To ensure that your dynamic types don't blow up unexpectedly (ie variable is duck mostly, but dcuk accidentally sometimes)).  Statics will try much harder to prevent this (And yes, you can make the argument for vigorous unit tests)</p>


答:
This is very much like the bin packing problem. There are a number of heuristics that will give you an answer that is not optimal but might be good enough for your purposes.

Essentially you are looking to optimize an objective function that gives you the least amount of waste, to solve exactly you may want to look into linear programming and the simplex algorithm.

There's some packages out there already that could help with this. Perhaps have a look at http://www.coin-or.org/

Title: Possibility Program for number of pieces

Body:
I would like to put a program together to calculate the number of 60' pieces would be needed from a list of shorter pieces.  For example, I sell rebar cut to length from our standard length of 60'-0".  Now the length the customer requires are as follows:

```<code>343 pc @ 12.5'
35 pc @ 13'
10 pc @ 15'
63 pc @ 15.5'.......
</code>```

There are 56 total lengths ranging from 12.5' to 30.58'

The idea is to limit the amount of waste from the 60' piece.
The input from the user would be:

number of differnt lengths

Length of piece to cut from

count of different lengths

The result would be the number of prime pieces needed to fulfill the order.

What well-known algorithms exist that could help me solve this problem?


答:
Client says "jump", your answer is: __  _?

For me, I would make an attempt to persuade if it made sense (new project), but I also have a client with a 10 yr old VB6 app that I do upgrades for occasionally... not going to convince them to


答:
With dynamic languages you can write crappy code faster than when using a typed language.

Once you have quickly created your huge pile of dynamic stuff, you can safely move to another project without having to care about long term maintenance.

This is productivity gain :)

I'm joking, but after having being involved in a project using 'dynamic language', I have been frightened by the amount of unnecessary tests, documentations and conventions you have to deal with if you want to have a working product.

And with the joy of lots of runtime errors that could have been caught at compilation.

Oh, I also forgot to rant about all those hacks and voodoos that meta-programming let you introduce in your code !

So the productivity gain might be a myth for medium/big project over its lifetime.

Title: What is the supposed productivity gain of dynamic typing?

Body:
I often heard the claim that dynamically typed languages are more productive than statically typed languages. What are the reasons for this claim? Isn't it just tooling with modern concepts like convention over configuration, the use of functional programming, advanced programming models and use of consistent abstractions - all of which could be used in statically typed languages as well? Admittedly there is less clutter because the (for instance in Java) often redundant type declarations are not needed, but you can also omit most type declarations in statically typed languages that use type inference, without losing the other advantages of static typing. And all of this is available for modern statically typed languages like Scala as well.

So: what is there to say for productivity with dynamic typing that really is an advantage of the type model itself?

Clarification: I'm more interested in big / medium sized projects than in quick hacks. :-)


答:
Most probably those old post are very valuable stuff to those who working on old frameworks/ technologies,  So I suggest you to keep them on your blog. Even they will represent your skills and valuable idea behind them which also let some to use your ideas.

That what you can do is  that create new post by tagging the updated technology version and older version on older post.


答:
It has to be "Wicked Cool PHP"

I bought it because it had a robot with a hammer on the front cover,what could go wrong? I thought.  Turns out everything. Pointless examples, terrible code and incorrect security information throughout.

Title: What's the worst programming book you've ever read?

Body: What's the worst programming-related or technical book you've ever read? This can be any book which one way or another can be connected to programming, as long as it's not fiction.</p>


问:
A good tool for browser automation/client-side Web scripting
I'm interested in adopting a tool/scripting language to automate some daily tasks connected with fighting forum spammers.  A brief overview of these tasks: analyze new registrations and posts on a phpBB forum, and delete or deactivate spammers using a website/community that collects such spam reports.

Typically such automation is integrated into the phpBB installation itself, which certainly has its advantages.  My approach has the advantage of independent operation, etc.

One way to think about this is in terms of browser automation.  I've used iOpus iMacros for Firefox (the free version) in the past to respond to individual spammers, but current attacks are highly distributed.  My "logic" for pigeonholing spammers vs. nonspammers seems beyond the easy reach of the free version of iMacros.

From a more technical perspective one can think about dispensing with the browser altogether and programming GET/POST requests directed to my forum and other Web-based resources.

I'm familiar with some scripting languages like Ruby and Lua, but I could be persuaded that a compiled application is better suited for these tasks.  However in my experience the dynamic flexibility of interpreted environments is very useful in prototyping and debugging the application logic.  So I'm leaning in the direction of scripting languages.

Among browsers I favor Firefox and Chrome. I use both Windows and Linux platforms, and if the tool can adapt to an Android platform, it would make a neat demonstration of skills, yes?

Thanks in advance for your suggestions!

答:
Not entirely sure I understood what you are looking for, but selenium is widely used for web automation.

There are some tools that help with using selenium - capybara is a ruby based tool that simplifies such work.


答: I know in database systems (where all locks are held in one place and can be analyzed), the common practice is to make one thread the "deadlock victim" and kill it, thereby releasing the lock.  This could be complicated in an operating system environment, since a single thread/process could have several locks on disparate parts of the system, so picking a deadlock victim could require some significant introspection and analysis.  Also, retrying a failed transaction due to a deadlock is a pretty standard database idiom, but not so common in application programming.</p>

Title: Schemes to resolve deadlocks

Body: I am interested in research that detects and recover from deadlocks. In other words the system is able to recover from deadlock faults. I'm interested in shared memory multicore processors. Uptill now I have only seen research for distributed systems. Can anyone guide me on this.</p>


问:
OOP private method parameters coding style
After coding for many years as a solo programmer, I have come to feel that most of the time there are many benefits to write private member functions with all of the used member variables included in the parameter list, especially development stage.

This allow me to check at one look what member variables are used and also allow me to supply other values for tests and debugging. Also, a change in code by removing a particular member variable can break many functions. In this case however, the private function remains isolated am I can still call it using other values without fixing the function.

Is this a bad idea afterall, especially in a team environment? Is it like redundant or confusing, or are there better ways?

答: If you want to have the function in class (private or not, does not matter), use members as members, so that it is an operation of the class. Otherwise it does not, in principle, belong in the class. Put it out of the class then and call it with lots of params. If you feel it is a helper that "must work no matter how the class is refactored".</p>


答:
In general, it's not a good idea to give methods (or anything for that matter) access to information it doesn't need. Having a large list of parameters means sifting through more of them when you or someone else needs to find something. If they are definitely related and necessary, maybe you should consider creating an object to pass, or passing the object from which they came.

As far as testing goes, you should try to keep tests separate from your actual logic.

Title: OOP private method parameters coding style

Body:
After coding for many years as a solo programmer, I have come to feel that most of the time there are many benefits to write private member functions with all of the used member variables included in the parameter list, especially development stage.

This allow me to check at one look what member variables are used and also allow me to supply other values for tests and debugging. Also, a change in code by removing a particular member variable can break many functions. In this case however, the private function remains isolated am I can still call it using other values without fixing the function.

Is this a bad idea afterall, especially in a team environment? Is it like redundant or confusing, or are there better ways?


答:
I recommend keeping the info as is. My VB.NET blog hasn't been updated since 2007 and it sees a good amount of traffic from people looking for older stuff, typically 500-700 unique visitors a day. My really old (circa 1999) VB6 static HTML pages even get a bit of traffic.

You can go back and edit posts to add links to newer posts. In some cases, I've added a bold Update header that explains why I don't recommend something anymore.


问:
What benefits are there to native JavaScript development?
Given how much simpler jQuery development is, when compared to native JavaScript, what makes people forgo libraries like jQuery altogether?

Is this because jQuery has limitations or it is slow? I mean, if jQuery is so easy compared to native javascript, what reasons do people have to still use pure javascript?

答:
I need to preface my answer with some open honesty. I love jQuery. It makes my life massively easier, and makes JavaScript code more declarative, which is the way I believe things should work.

jQuery does many things…

Yes you can add plugins

Yes you can extend selectors

Yes it simplifies animation

but jQuery doesn't do everything

Have you ever tried working in multiple window contexts with jQuery? jQuery sucks at dealing with different window contexts because it retains the original window and document context from the window in which it was called.

I've written some code here and there to make popouts*, and jQuery can simply get in the way of what I'm trying to accomplish. Adding a new reference to jQuery in the child window can often make things worse by making it more difficult to tell which jQuery context is being used.

* think of Gmail's popout for composing an email in a new window, not spammy advertising

Use it when it makes code simpler

The time to use jQuery is when you can make your code simpler, shorter, more readable, and faster.

The time to not use jQuery is when it wont make your code simpler, shorter, more readable, or faster. If you need to fine-tune load timings, you may not want to use jQuery because of the event overhead.


答:
allow me to check at one look what member variables are used

Using a method signature solely to identify members of a class is a crude, non-OO style of programming.  OOP is about higher level abstractions and relationships. If you are having trouble tracking a ridiculous # of members, then you should immediately review your classes to ensure they have a single and easily identifiable purpose.  This sounds like you are constructing god objects.

Also, a change in code by removing a particular member variable can break **many** functions.

A great indicator of tight coupling.  Decouple your classes.  Look at dependency injection..

allow me to supply other values for tests and debugging.

Unclear on meaning here. Especially because you go on to say

In this case however, the private function remains isolated am I can still call it using other values without fixing the function.

Generally, private functions make code more difficult to (unit) test not easier.  Are you familiar with Mocking?  Are you testing with unit tests, some kind of home brew or other?


答:
As others have pointed out what you describe seems to go against the idea of objects, for a thorough explanation of this I'd recommend Robert C. Martins book "Clean Code" especially the chapter on methods.

It's relevant because it is a thorough and practical description of how to write clean object oriented code. The referenced chapter in particular discusses method parameter lists regarding:

their length,

the method's responsibility,

the class' responsibility,

and the instance variables.

That chapter contains a long answer to the question. The short answer is to have few parameters, to favor instance variables, and to keep classes very focused - that is in accordance to the Single Responsibility Principle.


答:
Is this a bad idea afterall, especially in a team environment?

I'd say it's at least a questionable practice that could lead to trouble, particularly in a team environment. Having worked this way for some time, you may have developed habits and understanding which avoid the potential trouble, but team members are likely not to understand your unwritten rules.

In particular, it seems like you're essentially practicing procedural programming in an object-oriented environment. The point of objects is that they contain both the data and the operations on that data. If you tell a view to draw(), for example, you don't need to tell it what to draw -- it should draw itself. If you have to tell it what to draw, you're not taking advantage of the power of OOP.

A danger of your approach is that your methods are operating not on the object's members, but on the parameters. If you pass those parameters by value, any changes to them won't be reflected in the corresponding member variables. You can solve that problem by passing by reference, but in that case your code might change member variables if that's what you pass in, but it's not obvious that that's what's happening. Worse, there's the very real possibility that the caller will pass in something other than a member variable, which really changes the meaning of what the method does.

Is it like redundant or confusing

Redundant: definitely.

Confusing: apparently not to you, but surely to others.

are there better ways?

Use member variables or properties instead of parameters in methods that are intended to operate on data stored within the object. Use parameters for information that's external to the object.

If you have trouble discerning which members a given method uses, try any of:

Put a comment near the beginning of the method that explains what the method does, lists the affected members, and perhaps describes any output.

Simplify your methods. I'm all for appropriate comments, but code is much nicer when you can scan the code quickly and get a pretty good idea of what's going on.

Stop worrying about it. A method should use whatever internal data it needs to do its job. Code outside the method should be more concerned with what the method does, not how it does it.