答:
You may like an Agile practice called "The Perfection Game", wich is part of the Core Protocols.

Summarily this is how it works:

the programmer ask to some potential reviewer if he is OK to play a perfection game

if reviewer is OK, the reviewer check the code an give a value of 1 to 10, depending on the value he believe can add to the code (for instance if he says 1 it may mean either this is a piece of shit but I do not understand a bit of it, won't be of any help, or it can mean this is nearly perfect, I couldn't do better. If reviewer says 10 on the other hand it would mean: your code is a piece of crap, but you have luck : I can help you with that because I'm an expert of this kind of crap).

the reviewer explains what he likes (not what he dislikes) in the reviewed code

the programmer then ask what would be needed to make that code perfect and the reviewer explains it.

the programmer then thanks the reviewer and change his code if necessary.

Of course this can be iterated until the programmer stops looking for perfection, or the reviewer can't help any more (he will give a low evaluation and the programmer will stop there).

This is a bit formal as it comes from Core Protocols, but the programmer is always responsible of the code changes and is asking review as a service. He usually won't use this kind of review to reject responsibility, on the contrary the programmer should ask to another reviewer if a given one won't be able to help.


问:
Since Garbage Collection is non-deterministic, why isn't it used for secure random number generation?
I get that /dev/random is a good source of entropy, and is what is usually used-- It's just as I'm reading up on GC, at least in Java, it seems accepted that the garbage collection daemon executes non-deterministically.  If this it true, why don't we use the timing of the garbage collection as a source of entropy instead of the variable /dev/random?</p>

答:
"Unspecified" and "random" are two entirely different concepts.

The exact workings of a garbage collector are not specified and are up to the garbage collector (usually implemented by a VM of sorts, but not necessarily).

Therefore, you have no specified (i.e. deterministic) time at which garbage will be collected.

However any given implementation will follow some rules and there is a high chance that two subsequent runs of the same program will have very similar garbage collection patterns.

Therefore the actual entropy provided by a garbage collector would be very low (and finding out which parts you can actually use as entropy will be tricky).

As a comparison: A HashMap in Java doesn't guarantee any order of retrieval for its members (basically because guaranteeing it would add an overhead that's not worth paying, most of the time). However for a given implementation and a given set of insertions/removals you can definitely calculate the resulting order. Just because there is no guarantee for any given order, doesn't mean that the order is random.

ContentLicense: CC BY-SA 3.0


问:
Should you always pass the bare minimum data needed into a function in cases like this
Let's say I have a function IsAdmin that checks whether a user is an admin. Let's also say that the admin checking is done by matching user id, name and password against some sort of rule (not important).

In my head there are then two possible function signatures for this:

```<code>public bool IsAdmin(User user);
public bool IsAdmin(int id, string name, string password);
</code>```

I most often go for the second type of signature, thinking that:

The function signature gives the reader a lot more info

The logic contained inside the function doesn't have to know about the User class

It usually results in slightly less code inside the function

However I sometimes question this approach, and also realize that at some point it would become unwieldy. If for example a function would map between ten different object fields into a resulting bool I would obviously send in the entire object. But apart from a stark example like that I can't see a reason to pass in the actual object.

I would appreciate any arguments for either style, as well as any general observations you might offer.

I program in both object oriented and functional styles, so the question should be seen as regarding any and all idioms.

答:
I'd go with this approach:

```<code>public bool IsAdmin(this IUser user) { /* ... */ }

public class User: IUser { /* ... */ }

public interface IUser
{
    string Username {get;}
    string Password {get;}
    IID Id {get;}
}
</code>```

Using the interface type as a parameter for this function allows you to pass in User objects, to define mock User objects for testing, and gives you more flexibility around both the use and maintenance of this function.

I also added the keyword this to make the function an extension method of all IUser classes; this way you can write code in a more OO friendly way and use this function in Linq queries.  Simpler still would be to define this function in IUser and User, but I assume there's some reason why you decided to put this method outside of that class?

I use the custom interface IID instead of int as this allows you to redefine properties of your ID; e.g. should you ever need to change from int to long, Guid, or something else.  That's probably overkill, but always good to try to make things flexible such that you're not locked into early decisions.

NB: Your IUser object can be in a different namespace and/or assembly to the User class, so you have the option to keep your User code completely separate from your IsAdmin code, with them only sharing one referenced library.  Exactly what you do there is a call for how you suspect these items to be used.

Body:
I'd go with this approach:

public bool IsAdmin(this IUser user) { /* ... */ }

public class User: IUser { /* ... */ }

public interface IUser
{
    string Username {get;}
    string Password {get;}
    IID Id {get;}
}

Using the interface type as a parameter for this function allows you to pass in User objects, to define mock User objects for testing, and gives you more flexibility around both the use and maintenance of this function.

I also added the keyword this to make the function an extension method of all IUser classes; this way you can write code in a more OO friendly way and use this function in Linq queries.  Simpler still would be to define this function in IUser and User, but I assume there's some reason why you decided to put this method outside of that class?

I use the custom interface IID instead of int as this allows you to redefine properties of your ID; e.g. should you ever need to change from int to long, Guid, or something else.  That's probably overkill, but always good to try to make things flexible such that you're not locked into early decisions.

NB: Your IUser object can be in a different namespace and/or assembly to the User class, so you have the option to keep your User code completely separate from your IsAdmin code, with them only sharing one referenced library.  Exactly what you do there is a call for how you suspect these items to be used.


问:
Why should I use List<T> over IEnumerable<T>?
In my ASP.net MVC4 web application I use IEnumerables, trying to follow the mantra to program to the interface, not the implementation.

```<code>Return IEnumerable(Of Student)
</code>```

vs

```<code>Return New List(Of Student)
</code>```

People are telling me to use List and not IEnumerable, because lists force the query to be executed and IEumerable does not.

Is this really best practice? Is there any alternative? I feel strange using concrete objects where an interface could be used. Is my strange feeling justified?

答:
Another benefit of enumerating the IEnumerable early is exceptions will be thrown at the appropriate location. This assists debugging.

For example, if you got a deadlock exception inside one of your Razor views, it wouldn't really be as clear as if the exception occurred during one of your data access methods.


问:
Why did Apple remove Python support in Mavericks, aka Mac OS X 10.9?
In a rather unceremonious way - Apple has removed Python support (at least from the SDK) in 10.9.

Python IS still installed on the system in...

```<code>/System/Library/Frameworks/Python.framework
</code>```

but trying to link to it under the 10.9 SDK fails. Even with the "CLI Tools" installed, there is no Python in...

```<code>/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks
</code>```

I'm no Pythonista... but I do find it interesting that Apple has removed a part of the Developer Toolchain that has been around for so long, and was once so promising (on the Mac platform).  Apple often tries to steer the focus towards certain "methodologies"; but historically, when the plug has been pulled - it's over - at least in Apple's eye.

Is this a statement by Apple, along the lines "People aren't using Python very much anymore.. we're gonna phase out support"?

Or simply, "Adoption of PyObjC is anemic, maybe we can reduce the size of the SDK by 3.1Mb"?

Whatever the motivation, it's likely a change that is here to stay. Are there suggestions on workarounds to maintain compile and runtime-compatibility, or insights into why the decision was made?

答:
There is an official support page on the subject:

Changes To Embedding Python Using Xcode 5.0

According to that page the rationale is:

Because Python is a framework, it also resides in the SDK, even though Python (or any scripting language) has difficulties being in two places.  Due to both long-term and recent issues, it was decided to remove Python from the SDK.

The subsequent Apple recommendation is to use the standard *nix way of linking to headers instead of linking to Python.framework.


问:
Best way to process a queue in C# (PDF treatment)
First of all let me expose what I would like to do : I already dispose of a long-time running webapp developed in ASP.NET (C#) 2.0. In this app, users can upload standard PDF files (text+pics). The app is running in production on a Windows Server 2003 and has a dedicated database server (SQL server 2008) also running Windows Server 2003. I myself am a quite experienced web developer, but never actually programmed anything non-web (or at least nothing serious).

I plan on adding a functionality to the webapp for which I would need a jpg snapshot of each page of the PDF. Creating these "thumbnails" isn't the big deal as such, I already do it inside my webapp using ghostscript. I've only done it on 1 page documents for now though, and the new functionality will need to process bigger documents.
In order for this process to be transparent aswell for the admins as the final users, I would like to implement some kind of queue to delay the processing of the thumbnails. There again, no problem to create the queue, it will consist of records in a table, with enough info to find the pdf document back.

Then I will need to process this queue, and that's were my interrogations start. Obviously the best solution to process it isn't an ASP script or so, so I will have to get out of my known environment. No problem, but I have no idea which direction to go. Therefore, a few questions :

What should I develop ? I presumably need something that is "standby" on the server, runs when needed, then returns to idle state until further notice.Should I be looking into Windows service ? Is there another more appropriate type of project ?

Depending on the first answer, what will be the approach ? Should I have somehow SQL server "tell" the program/service/... to process the queue, or should I have that program/service/... periodically check the state of the queue and treat new items. In both case, which functionality can I use ?

we're not talking about hundreds of PDF a day (max 50 maybe), I can totally afford to treat the queue 1 item at a time. Can you confirm I don't have to look much further on threads and so ? (I found a lot of answers talking about threads in queue treatment, but it looks quite overkill for my needs)

Maybe linked to the previous question : what about concurrent call to the program, whatever it is ? Let's suppose it is currently running, and a new record comes in the queue, what should be the behaviour ?

I don't need much detailed answers and would already be happy with answers like "You can do the processing with a service, and yes it's possible to have sqlserver on machine A trigger a service start on machine B" or "You have to develop xxx and then use the scheduler to run it every xxx minutes". I don't mind reading articles and so, but I can hardly afford to spend too much time learning stuff to finally realize I went the wrong way for this project, so basically I'm trying to narrow down the scope of matters I need to investigate.

Thanks for reading me, I hope I'll find some helping hands on here :-)

答: Using C# console apps which are run from the Windows Scheduler is a dirt simple way of doing this, and you have severale benefits in easy deployment, reduced problems from any memory leaks, besides you save a lot of energy from not reinventing yet another scheduler.</p>


答:
You've got a few different options -

Kick off a separate process/thread from your ASP.NET code to do the work. I would not recommend this approach, you'll have issues with ghost processes, IIS terminating things for you, user account security problems, etc etc.

A windows console application that you run periodically using the windows scheduler. Nice, simple, easy to maintain and deploy, easy to test. Easy for someone else to figure out what you've done - they can log onto your production box and see the scheduled task. The app checks the DB for what work needs to be done, does it, logs stuff to disk (or even better your DB, or maybe even the event log if you've got a good sysadmin) and then exists. I would go down this path for the moment. You can always stick your code into a DLL and "upgrade" it to the next option...

A windows service application. The nuclear bomb approach. Good if you need it to run more often like every minute or so. If you want to avoid DB polling, you could have it open up a WCF endpoint and talk to it directly. I have done this approach before and it works great, but it's probably overkill.

Title: Best way to process a queue in C# (PDF treatment)

Body:
First of all let me expose what I would like to do : I already dispose of a long-time running webapp developed in ASP.NET (C#) 2.0. In this app, users can upload standard PDF files (text+pics). The app is running in production on a Windows Server 2003 and has a dedicated database server (SQL server 2008) also running Windows Server 2003. I myself am a quite experienced web developer, but never actually programmed anything non-web (or at least nothing serious).

I plan on adding a functionality to the webapp for which I would need a jpg snapshot of each page of the PDF. Creating these "thumbnails" isn't the big deal as such, I already do it inside my webapp using ghostscript. I've only done it on 1 page documents for now though, and the new functionality will need to process bigger documents.
In order for this process to be transparent aswell for the admins as the final users, I would like to implement some kind of queue to delay the processing of the thumbnails. There again, no problem to create the queue, it will consist of records in a table, with enough info to find the pdf document back.

Then I will need to process this queue, and that's were my interrogations start. Obviously the best solution to process it isn't an ASP script or so, so I will have to get out of my known environment. No problem, but I have no idea which direction to go. Therefore, a few questions :

What should I develop ? I presumably need something that is "standby" on the server, runs when needed, then returns to idle state until further notice.Should I be looking into Windows service ? Is there another more appropriate type of project ?

Depending on the first answer, what will be the approach ? Should I have somehow SQL server "tell" the program/service/... to process the queue, or should I have that program/service/... periodically check the state of the queue and treat new items. In both case, which functionality can I use ?

we're not talking about hundreds of PDF a day (max 50 maybe), I can totally afford to treat the queue 1 item at a time. Can you confirm I don't have to look much further on threads and so ? (I found a lot of answers talking about threads in queue treatment, but it looks quite overkill for my needs)

Maybe linked to the previous question : what about concurrent call to the program, whatever it is ? Let's suppose it is currently running, and a new record comes in the queue, what should be the behaviour ?

I don't need much detailed answers and would already be happy with answers like "You can do the processing with a service, and yes it's possible to have sqlserver on machine A trigger a service start on machine B" or "You have to develop xxx and then use the scheduler to run it every xxx minutes". I don't mind reading articles and so, but I can hardly afford to spend too much time learning stuff to finally realize I went the wrong way for this project, so basically I'm trying to narrow down the scope of matters I need to investigate.

Thanks for reading me, I hope I'll find some helping hands on here :-)


问:
Is it reasonable to null guard every single dereferenced pointer?
At a new job, I've been getting flagged in code reviews for code like this:

```<code>PowerManager::PowerManager(IMsgSender* msgSender)
  : msgSender_(msgSender) { }

void PowerManager::SignalShutdown()
{
    msgSender_->sendMsg("shutdown()");
}
</code>```

I'm told that last method should read:

```<code>void PowerManager::SignalShutdown()
{
    if (msgSender_) {
        msgSender_->sendMsg("shutdown()");
    }
}
</code>```

i.e., I must put a NULL guard around the msgSender_ variable, even though it is a private data member. It's difficult for me to restrain myself from using expletives to describe how I feel about this piece of 'wisdom'. When I ask for an explanation, I get a litany of horror stories about how some junior programmer, some-year, got confused about how a class was supposed to work and accidentally deleted a member he shouldn't have (and set it to NULL afterwards, apparently), and things blew up in the field right after a product release, and we've "learned the hard way, trust us" that it's better to just NULL check everything.

To me, this feels like cargo cult programming, plain and simple. A few well-meaning colleagues are earnestly trying to help me 'get it' and see how this will help me write more robust code, but... I can't help feeling like they're the ones who don't get it.

Is it reasonable for a coding standard to require that every single pointer dereferenced in a function be checked for NULL first—even private data members? (Note: To give some context, we make a consumer electronics device, not an air traffic control system or some other 'failure-equals-people-die' product.)

EDIT: In the above example, the msgSender_ collaborator isn't optional. If it's ever NULL, it indicates a bug. The only reason it is passed into the constructor is so PowerManager can be tested with a mock IMsgSender subclass.

SUMMARY: There were some really great answers to this question, thanks everyone. I accepted the one from @aaronps chiefly due to its brevity. There seems to be fairly broad general agreement that:

Mandating NULL guards for every single dereferenced pointer is overkill, but

You can side-step the whole debate by using a reference instead (if possible) or a const pointer, and

assert statements are a more enlightened alternative to NULL guards for verifying that a function's preconditions are met.

答:
Objective-C, for example, treats every method call on a nil object as a no-op that evaluates to a zero-ish value. There are some advantages to that design decision in Objective-C, for the reasons suggested in your question.  The theoretical concept of null-guarding every method call has some merit if it's well publicized and consistently applied.

That said, code lives in an ecosystem, not a vacuum.  The null-guarded behaviour would be non-idiomatic and surprising in C++, and therefore should be considered harmful.  In summary, nobody writes C++ code that way, so don't do it!  As a counter-example, though, note that calling free() or delete on a NULL in C and C++ is guaranteed to be a no-op.

In your example, it would probably be worthwhile to place an assertion in the constructor that msgSender is non-null.  If the constructor called a method on msgSender right away, then no such assertion would be necessary, since it would crash right there anyway.  However, since it is merely storing msgSender for future use, it would not be obvious from looking at a stack trace of SignalShutdown() how the value came to be NULL, so an assertion in the constructor would make debugging significantly easier.

Even better, the constructor should accept a const IMsgSender& reference, which cannot possibly be NULL.


问:
How can robots beat CAPTCHAs?
I have a website e-mail form. I use a custom CAPTCHA to prevent spam from robots. Despite this, I still get spam.

Why? How do robots beat the CAPTCHA? Do they use some kind of advanced OCR or just get the solution from where it is stored?

How can I prevent this? Should I change to another type of CAPTCHA?

I am sure the e-mails are coming from the form, because it is sent from my email-sender that serves the form messages. Also the letter style is the same.

 For the record, I am using PHP + MySQL, but I'm not searching for a solution to this problem. I was interested in the general situation how the robots beat these technologies. I just told this situation as an example, so you can understand better what I'm asking about.

答:
If your site is twitter, and someone has targeted it specifically (rather than a bot finding it) then you can stop reading...

Otherwise, it might be worth not making your form NOT look like a form.
1. Don't have fields with 'e-mail' in the type, name or placeholder, use short or misleading names for all fields.
2. Don't use an actual html form element and submit button. Rather use AJAX to post it on the click of a normal div (styled to look like a button).
3. Don't put the onclick event in the html, add a listener in JavaScript.
4. Use JavaScript to populate any tips 'enter your email address here' as it's possible that bots won't actually be triggering JS when trawling pages (not sure on this one, but I do it anyway).

Title: How can robots beat CAPTCHAs?


问:
How can a website look different in safari Windows and Safari mac?
I have a website. I've been testing crossbrowser on my windows PC, and it looks good in all browsers, but on Mac in Safari it looks like the CSS is not getting interpreted right, or there is a critical javascript error.

When I look in the console cross-browser, the error log shows exactly the same. Chrome on mac interprets the site as intended, so why do I have a problem with safari?

It is the same across different computers, and iphone safari also shows the site wrong.

How is this possible and how do I debug?

答:
The first consideration is that different versions of the same browser may have different rendering backend versions (Webkit in the case of Safari).

A look at wikipedia's Safari version history shows that 5.1.7 is using webkit version 534.57.2.  Meanwhile Mac OSX Safari is running 7.0 for OS 10.9 and 6.1 for the latest version on 10.8.  Realize that Apple does do a reasonable job at pushing updates,  Safari 7.0 is running Webkit 537.71 and 6.1 is running Webkit 537.43.58.  These are all different versions and will likely have some differences in rendering.

The next consideration is that the windowing widgets that the browser uses is different on differing operating systems.  I've recently had an issue where Chrome (latest) on Linux renders <select> list one way and Chrome (latest) on Mac OS X renders it differently.  Different windowing widgets.

You can get an idea of this differing widgets by looking at Styling single selection menu control option groups (optgroup elements) with CSS

This really boils down to You need to test every supported browser and operating system as a separate entity and debug it as such.  The 'same' browser on a different operating system isn't the same.

The thing to do is look at what version of Chrome you are using, what version of webkit (if its one that is using webkit) is in use, and then dig into the change logs for webkit (and trac.webkit.org).  You might what to consider trying to build a consistent version of webkit for both Windows and Mac and then see if you can find the issue in your code, or if not, log an issue with Webkit.  Please note, that you really will need to look into creating an SSCCE version to work from - for yourself and if you hope to have anyone look into it to fix it.


问:
ASP.Net or WPF(C#)?
Our team is divided on this and I wanted to get some third-party opinions.

We are building an application and cannot decide if we want to use .Net WPF Desktop Application with a WCF server, or ASP.Net web app using jQuery. I thought I'd ask the question here, with some specs, and see what the pros/cons of using either side would be. I have my own favorite and feel I am biased.

Ideally we want to build the initial release of the software as fast as we can, then slow down and take time to build in the additional features/components we want later on. Above all we want the software to be fast. Users go through records all day long and delays in loading records or refreshing screens kills their productivity.

Application Details:

I'm estimating around 100 different screens for initial version, with plans for a lot of additional screens being added on later after the initial release.

We are looking to use two-way communication for reminder and event systems

Currently has to support around 100 users, although we've been told to allow for growth up to 500 users

We have multiple locations

Items to consider (maybe not initially in some cases but in future releases):

Room for additional components to be added after initial release (there are a lot of of these... perhaps work here than the initial application)

Keyboard navigation

Performance is a must

Production Speed to initial version

Low maintenance overhead

Future support

Softphone/Scanner integration

Our Developers:

We have 1 programmer who has been learning WPF the past few months and was the one who suggested we use WPF for this.

We have a 2nd programmer who is familiar with ASP.Net and who may help with the project in the future, although he will not be working on it much up until the initial release since his time is spent maintaining our current software.

There is me, who has worked with both and am comfortable in either

We have an outside company doing the project management, and they are an ASP.Net company.

We plan on hiring 1-2 others, however we need to know what direction we are going in first

Environment:

General users are on Windows 2003 server with Terminal Services. They connect using WYSE thin-clients over an RDP connection. Admin staff has their own PCs with XP or higher. Users are allowed to specify their own resolution although they are limited to using IE as the web browser.

Other locations connects to our network over a MPLS connection

Based on that, what would you choose and why?

答:
This part is quite concerning:

General users are on Windows 2003 server with Terminal Services. They connect using WYSE thin-clients over an RDP connection. Admin staff has their own PCs with XP or higher. Users are allowed to specify their own resolution although they are limited to using IE as the web browser.

WPF is not great over Remote Desktop/Thin client connections. Animations will not be smooth and any complex images (even gradients) will slow the UI response down to a crawl. Admin staff with typical retro XP machines will also most likely have performance problems with complex WPF applications (because of tiny amounts of RAM and bad GPUs).

If you go the WPF route for rich graphics, be prepared for last minute performance hacks when you find out that the target machines are ten years old. Stick to static screens and use .NET 4.0 as the WPF performance has improved dramatically since 3.5.

Title: ASP.Net or WPF(C#)?

ContentLicense: CC BY-SA 2.5


答:
Firstly, we have to be careful not to fall into the trap of reasoning by manipulation of mere words. For instance, we could ask, since a NFA is a "non-deterministic finite automaton", why don't we use it to obtain random numbers? In that case, it would be because that's not what "non-deterministic" means in an NFA; in fact, when we simulate an NFA, on a given input, the behavior of the simulation is perfectly deterministic.

"Deterministic" is a loaded phrase. To a computer programmer or computer scientist, non-deterministic behavior just means "determining the exact behavior is complicated to think about", and depends on too many factors, including the program input.

However, that doesn't mean it's not deterministic to someone motivated to attack a cryptosystem.  Sometimes environmental factors and inputs can be pinned down, and repeatable patterns emerge from "non-deterministic" behavior.

Title: Since Garbage Collection is non-deterministic, why isn't it used for secure random number generation?

Body: I get that /dev/random is a good source of entropy, and is what is usually used-- It's just as I'm reading up on GC, at least in Java, it seems accepted that the garbage collection daemon executes non-deterministically.  If this it true, why don't we use the timing of the garbage collection as a source of entropy instead of the variable /dev/random?</p>


问:
Advice on designing a robust program to handle a large library of meta-information & programs
So this might be overly vague, but here it is anyway
I'm not really looking for a specific answer, but rather general design principles or direction towards resources that deal with problems like this. It's one of my first large-scale applications, and I would like to do it right.

Brief Explanation

My basic problem is that I have to write an application that handles a large library of meta-data, can easily modify the meta-data on-the-fly, is robust with respect to crashing, and is very efficient. (Sorta like the design parameters of iTunes, although sometimes iTunes performs more poorly than I would like).

If you don't want to read the details, you can skip the rest

Long Explanation

Specifically I am writing a program that creates a library of image files and meta-data about these files. There is a list of tags that may or may not apply to each image.

The program needs to be able to add new images, new tags, assign tags to images, and detect duplicate images, all while operating.

The program contains an image Viewer which has tagging operations. The idea is that if a given image A is viewed while the library has tags T1, T2, and T3, then that image will have boolean flags for each of those tags (depending on whether the user tagged that image while it was open in the Viewer). However, prior to being viewed in the Viewer, image A would have no value for tags T1, T2, and T3. Instead it would have a "dirty" flag indicating that it is unknown whether or not A has these tags or not. The program can introduce new tags at any time (which would automatically set all images to "dirty" with respect to this new tag)

This program must be fast. It must be easily able to pull up a list of images with or without a certain tag as well as images which are "dirty" with respect to a tag.

It has to be crash-safe, in that if it suddenly crashes, all of the tagging information done in that session is not lost (though perhaps it's okay to loose some of it)

Finally, it has to work with a lot of images (>10,000)

I am a fairly experienced programmer, but I have never tried to write a program with such demanding needs and I have never worked with databases.

With respect to the meta-data storage, there seem to be a few design choices:

Choice 1: Invidual meta-data vs centralized meta-data

Individual Meta-Data: have a separate meta-data file for each image. This way, as soon as you change the meta-data for an image, it can be written to the hard disk, without having to rewrite the information for all of the other images.

Centralized Meta-Data: Have a single file to hold the meta-data for every file. This would probably require meta-data writes in intervals as opposed to after every change. The benefit here is that you could keep a centralized list of all images with a given tag, ect, making the task of pulling up all images with a given tag very efficient

答:
There are several possible ways to tackle your needs. As sqlvogel mentioned, some content management system might work out-of-the-box for you. If you need more control in your own program, using a standard database should be the proper way, which will cover most topics you mentioned (speed, good scalability, crash-safety (if done properly). So I advice to read some stuff about databases and their properties - free versus commercial, speed etc..

Don't forget to hide all your database access behind a proxy or facade, so you can easily switch to another db system if needed later.

If this is your first real big thing, I also recommend you to draw a lot of sketches of your software and its modules and talk continuously to a lot of persons about them. Will do wonders to your understanding your own software and not getting lost! :-)

OwnerDisplayName: Sam Bryant

OwnerDisplayName: LastFreeNickname


问:
How do you cope with ugly code that you wrote?
So your client asks you to write some code, so you do. He then changes the specs on you, as expected, and you diligently implement his new features like a good little lad. Except... the new features kind of conflict with the old features, so now your code is a mess. You really want to go back and fix it, but he keeps requesting new things and every time you finish cleaning something, it winds up a mess again.

What do you do? Stop being an OCD maniac and just accept that your code is going to wind up a mess no matter what you do, and just keep tacking on features to this monstrosity? Save the cleaning for version 2?

答:
I have the following comment in a code base that I'm currently working on:

```<code>/*
 * Every time I see this function, I want to take a shower.
 */
</code>```

I know, very well the situation you are describing. What I do is try (my best) to wait until things settle down and any kind of 'creep' has 'crept' all that it's going to do. By that time, you probably have something usable released, and you can take some time to clean things up and implement stuff a bit differently.

You can't run around cleaning up lots of little messes repeatedly. That just triples your work, and frustration. Wait for it to become one bigger, but hardly moving mess and then you can do something about it.

Body:
I have the following comment in a code base that I'm currently working on:

/*
 * Every time I see this function, I want to take a shower.
 */

I know, very well the situation you are describing. What I do is try (my best) to wait until things settle down and any kind of 'creep' has 'crept' all that it's going to do. By that time, you probably have something usable released, and you can take some time to clean things up and implement stuff a bit differently.

You can't run around cleaning up lots of little messes repeatedly. That just triples your work, and frustration. Wait for it to become one bigger, but hardly moving mess and then you can do something about it.


问:
Is it better to have constructors with or without parameters?
Is it better to have constructors with or without parameters and why?

```<code>public NewClass( String a,  String b, int c) throws IOException
{
    //something
}
</code>```

OR

```<code>public NewClass()
{
    //something
}
</code>```

答:
A constructor should establish the initial invariant of your object, that is, put it in a valid and usable state.

If your object is not really usable as an instance of the type it is after construction, it's a sign that you've got a bit of a smear between initialization of the object and use of the object.

If it's impossible to provide all the information needed up-front to construct your object properly, you may want to consider some sort of builder to gather state incrementally before  instantiating the object.

In general, zombie-type objects which have initialization after construction and invalidation before disposal tend to be error-prone, particularly if there is no language support for it, leaving you to enforce the concepts in documentation and assertions.


问:
Is creating a separate pool for each individual png image in the same class appropriate?
I'm still possibly a little green about object-pooling, and I want to make sure something like this is a sound design pattern before really embarking upon it.  Take the following code (which uses the Starling framework in ActionScript 3):

```<code>[Embed(source = "/../assets/images/game/misc/red_door.png")]
private const RED_DOOR:Class;

private const RED_DOOR_TEXTURE:Texture = Texture.fromBitmap(new RED_DOOR());

private const m_vRedDoorPool:Vector.<Image> = new Vector.<Image>(50, true);
.
.
.
public function produceRedDoor():Image
{
    // get a Red Door image
}

public function retireRedDoor(pImage:Image):void
{
    // retire a Red Door Image
}
</code>```

Except that there are four colors: red, green, blue, and yellow.  So now we have a separate pool for each color, a separate produce function for each color, and a separate retire function for each color.  Additionally there are several items in the game that follow this 4-color pattern, so for each of them, we have four pools, four produce functions, and four retire functions.

There are more colors involved in the images themselves than just their predominant one, so trying to throw all the doors, for instance, in a single pool, and then changing their color properties around isn't going to work.  Also the nonexistence of the static keyword is due to its slowness in AS3.

Is this the right way to do things?

EDIT:

One individual piece of the puzzle is whether I should be trying to throw all of these pools into the same class, with brand new functions and everything for each and every pool.  That is somewhat related to another question I asked recently.  Even though the accepted answer of that question didn't necessarily address this particular scenario, getting more classes, variables, abstractions, etc. is going to create more overhead, and when you're trying to do something like object pooling, I'm not sure whether neatening up the class design like that is going to introduce "too much" overhead.  This is only one individual part of what I'm asking though, as the question is ultimately much more general.

答:
If you have a {Red,Green,Blue,Yellow} Door pool and a {Red,Green,Blue,Yellow} Window pool, it would be worth choosing an appropriate abstraction: The variable things are the item type (door or window), and the color.

A Pool has a color, an item class, and a collection of images. It also has produce and retire methods. For example (switching to Java, because generics):

```<code>Pool<Door> redDoorPool = new Pool<Door>(Color.RED);
Image redDoor = redDoorPool.produce();
</code>```

You could then create a ColorPool class which groups four Pools together:

```<code>class ColorPool<T> {
  public final red    = new Pool<T>(Color.RED);
  public final green  = new Pool<T>(Color.GREEN);
  public final blue   = new Pool<T>(Color.BLUE);
  public final yellow = new Pool<T>(Color.YELLOW);
}
</code>```

Consider using the Composite Pattern here. Also, use accessors instead of public fields in actual code…

Then:

```<code>ColorPool<Door> doorPool = new ColorPool<Door>();
Image redDoor = doorPool.red.produce();
</code>```

We have now successfully abstracted over all variable pieces in your pools, and neither type information, nor color information is part of the method name.

Note that generics are not strictly necessary for this design to work – I just used it here to make the relationships clear.

Body:
If you have a {Red,Green,Blue,Yellow} Door pool and a {Red,Green,Blue,Yellow} Window pool, it would be worth choosing an appropriate abstraction: The variable things are the item type (door or window), and the color.

A Pool has a color, an item class, and a collection of images. It also has produce and retire methods. For example (switching to Java, because generics):

Pool<Door> redDoorPool = new Pool<Door>(Color.RED);
Image redDoor = redDoorPool.produce();

You could then create a ColorPool class which groups four Pools together:

class ColorPool<T> {
  public final red    = new Pool<T>(Color.RED);
  public final green  = new Pool<T>(Color.GREEN);
  public final blue   = new Pool<T>(Color.BLUE);
  public final yellow = new Pool<T>(Color.YELLOW);
}

Consider using the Composite Pattern here. Also, use accessors instead of public fields in actual code…

Then:

ColorPool<Door> doorPool = new ColorPool<Door>();
Image redDoor = doorPool.red.produce();

We have now successfully abstracted over all variable pieces in your pools, and neither type information, nor color information is part of the method name.

Note that generics are not strictly necessary for this design to work – I just used it here to make the relationships clear.


问:
Tell a user whether they have already viewed an item in a list. How?
It is pretty common for a web application to display a list of items and for each item in the list to indicate to the current user whether they have already viewed the associated item.

An approach that I have taken in the past is to store HasViewed objects that contain the Id of a viewed item/object and the Id of the User who has viewed that item/object.

When it comes time to display a list of items this requires querying the database for the items, and separately querying the database for the HasViewed objects, and then combining the results of these queries into a set of objects constructed solely for the purpose of displaying them in the view.

Each e.g li then uses the e.g. has_viewed property of the objects constructed above.

I think it is time to find a better approach and would like to know what approaches you would recommend.

答:
Although this could be answered with a number of database design ideas, there is a problem with the premise of the question as posed. The question as you've written it makes it apparent that you are looking to solve this problem on your own, but why reinvent the wheel, and especially, why reinvent it on the server?

Your first sentence says "It is pretty common for a web application ... to indicate to the current user whether they have already viewed the associated item."

This is true — it is common — but I've rarely (maybe never) seen simple click-visiting-status achieved through server-side databases.  Almost universally it is accomplished using the native browser history, through the use of :visited CSS pseudo-selectors.

How to do it, and how REST helps

The user visits a page

The browser records that page (URL) visit in history

Any time a link's href matches a visit in history, the :visited pseudo-selector will apply to that element.

For example:

```<code>:visited {
  color:red;
}
</code>```

will apply a red color to any visited link on a page (unless a conflicting style rule is more specific).

How REST helps

When you use REST URIs appropriately, you are more fully able to utilize the web browser's native features, including visited status, and other features such as caching.

For example, if your web application uses consistent URIs, then the browser is easily able to recognize whether you've viewed an item no matter where its URI appears throughout your application:

/user/13

/user/13/friends

/post/welcome-page

But, if you have poor, inconsistent URI creation, this is problematic.  Here are some example URIs that break caching and visited links (based on common real-world patterns):

/user?id=13

/user?id=13&nav=profilepic

/user?id=13&tab=details

/user?tab=details&id=13

To the viewer, these links may all appear to point to the same page but the browser will have no knowledge of that.

If your application has this problem, it's probably because the URI has been overloaded in purpose to track things that it's really not meant to.  But, it is probably still easier to fix this than to track "visited" state for every viewer in your database.

Why use REST and native browser features?

This pattern has many advantages.

Don't reinvent the wheel.  Visited status already exists in browsers.

Using appropriate URIs is a server problem.  Solve server problems on the server.

I can't bold this enough: Scalability (!!!) Viewing those URIs is a distributed problem.  Always  prefer to solve distributed problems on the client.

The complexity of this feature could absolutely explode if you attempt to solve it on the server.  Think about it.  If you have N visitors and M distinct resources, then you have a problem magnitude of N × M.  You have to resolve the problem every time N or M (or both) outgrow your previous solution.  Any time you have a new type of resource that you didn't account for you will need to do more fixing.  Your ongoing resource costs will be higher as well.

If you use browser native features you don't have to do any of this.  The problem is already distributed.

You are using the features of HTTP for the purposes they were designed for.  URIs were designed to identify resources.  Browsers are good at using URIs to get them, and servers are good at delivering them.

When does a server solution make sense?

Finally, there are a few cases where a server solution might make sense:

:visited support insufficient:

If you need to change content more significantly than just colors, since the capability of :visited has been reduced for the privacy of the user.

Your users frequently have more complicated browsing behavior than can be served by the browser history, such as frequently changing devices

Other features:

"Recently viewed/edited items" or similar — display lists of only visited items.

"Not viewed yet" or similar — display lists of only unvisited items, such as marking inbox items as read

"Who has viewed this" — Tracking popularity or alerting other users to who has viewed a particular item, like LinkedIn's profile views feature.

Body:
Although this could be answered with a number of database design ideas, there is a problem with the premise of the question as posed. The question as you've written it makes it apparent that you are looking to solve this problem on your own, but why reinvent the wheel, and especially, why reinvent it on the server?

Your first sentence says "It is pretty common for a web application ... to indicate to the current user whether they have already viewed the associated item."

This is true — it is common — but I've rarely (maybe never) seen simple click-visiting-status achieved through server-side databases.  Almost universally it is accomplished using the native browser history, through the use of :visited CSS pseudo-selectors.

How to do it, and how REST helps

The user visits a page

The browser records that page (URL) visit in history

Any time a link's href matches a visit in history, the :visited pseudo-selector will apply to that element.

For example:

:visited {
  color:red;
}

will apply a red color to any visited link on a page (unless a conflicting style rule is more specific).

How REST helps

When you use REST URIs appropriately, you are more fully able to utilize the web browser's native features, including visited status, and other features such as caching.

For example, if your web application uses consistent URIs, then the browser is easily able to recognize whether you've viewed an item no matter where its URI appears throughout your application:

/user/13

/user/13/friends

/post/welcome-page

But, if you have poor, inconsistent URI creation, this is problematic.  Here are some example URIs that break caching and visited links (based on common real-world patterns):

/user?id=13

/user?id=13&nav=profilepic

/user?id=13&tab=details

/user?tab=details&id=13

To the viewer, these links may all appear to point to the same page but the browser will have no knowledge of that.

If your application has this problem, it's probably because the URI has been overloaded in purpose to track things that it's really not meant to.  But, it is probably still easier to fix this than to track "visited" state for every viewer in your database.

Why use REST and native browser features?

This pattern has many advantages.

Don't reinvent the wheel.  Visited status already exists in browsers.

Using appropriate URIs is a server problem.  Solve server problems on the server.

I can't bold this enough: Scalability (!!!) Viewing those URIs is a distributed problem.  Always  prefer to solve distributed problems on the client.

The complexity of this feature could absolutely explode if you attempt to solve it on the server.  Think about it.  If you have N visitors and M distinct resources, then you have a problem magnitude of N × M.  You have to resolve the problem every time N or M (or both) outgrow your previous solution.  Any time you have a new type of resource that you didn't account for you will need to do more fixing.  Your ongoing resource costs will be higher as well.

If you use browser native features you don't have to do any of this.  The problem is already distributed.

You are using the features of HTTP for the purposes they were designed for.  URIs were designed to identify resources.  Browsers are good at using URIs to get them, and servers are good at delivering them.

When does a server solution make sense?

Finally, there are a few cases where a server solution might make sense:

:visited support insufficient:

If you need to change content more significantly than just colors, since the capability of :visited has been reduced for the privacy of the user.

Your users frequently have more complicated browsing behavior than can be served by the browser history, such as frequently changing devices

Other features:

"Recently viewed/edited items" or similar — display lists of only visited items.

"Not viewed yet" or similar — display lists of only unvisited items, such as marking inbox items as read

"Who has viewed this" — Tracking popularity or alerting other users to who has viewed a particular item, like LinkedIn's profile views feature.


问:
How do you make people accept code review?
All programmers have their style of programming. But some of the styles are let’s say... let’s not say. So you have code review to try to impose certain rules for good design and good programming techniques.

But most of the programmers don’t like code review. They don’t like other people criticizing their work.

Who do they think they are to consider themselves better than me and tell me that this is bad design, this could be done in another way. It works right? What is the problem? This is something  they might say (or think but not say which is just as bad if not worse).

So how do you make people accept code review without starting a war?

How can you convince them this is a good thing; that will only improve their programming skills and avoid a lot of work later to fix and patch a zillion times a thing that hey... "it works"?

People will tell you how to make code review (peer-programming, formal inspections etc) what to look for in a code review, studies have been made to show the number of defects that can be discovered before the software hits production etc. But how do you convince programmers to accept a code review?

答:
I was astonished nobody mentioned yet the Agile practice called "The Perfection Game", wich is part of the Core Protocols. Core Protocols suggests a kind of code review easier to accept for programmers.

Summarily this is how it works:

the programmer ask to some potential reviewer if he is OK to play a perfection game

if reviewer is OK, the reviewer check the code an give a value of 1 to 10, depending on the value he believe can add to the code (for instance if he says 1 it may mean either this is a piece of shit but I do not understand a bit of it, won't be of any help, or it can mean this is nearly perfect, I couldn't do better. If reviewer says 10 on the other hand it would mean: your code is a piece of crap, but you have luck : I can help you with that because I'm an expert of this kind of crap).

the reviewer explains what he likes (not what he dislikes) in the reviewed code

the programmer then ask what would be needed to make that code perfect and the reviewer explains it.

the programmer then thanks the reviewer and change his code if necessary.

Of course this can be iterated until the programmer stops looking for perfection, or the reviewer can't help any more (he will give a low evaluation and the programmer will stop there).

This is a bit formal as it comes from Core Protocols, but the programmer is always responsible of the code changes and is asking review as a service. He usually won't use this kind of review to reject responsibility, on the contrary the programmer should ask to another reviewer if a given one won't be able to help.

Perfection Game may not applies to every case as it works on a voluntary basis (I understand the question as asking about mandatory code reviews). It also put to light that the label "code review" covers many underlying different practices (in the agile World only Perfection Game and Pair Programming are for instance two totally different kind of code reviews).

Some practice are easier to accept than others and it may also depends on the team and the individual programmer. As an afterword I would also answer to the original question by saying that code reviews are easier when there is trust between the members of a team.

Whichever the practices chosen, Trust toward fellow teamworkers  is certainly at the core of code review acceptation by programmers..


答:
If you do not want to store the visited state information on the server, and in case the user does not have an account with your application, but still you must know if s/he has already been on a page or has reviewed an item, then what comes to my mind is a cookie. You can store a list of the item ids that the user has visited in a cookie, and check with it each time you load an item to see if it has already been visited.

Keep in mind that of you have many items that a user can visit, the cookie may grow too big. Also, the user may delete it at any time without you to notice or take any measure.

A plus with this solution is, if you particularly aim at visual effects or other front-end related functionality, that you can do this on the client with javascript, with no need to modify your server-side code

Title: Tell a user whether they have already viewed an item in a list. How?

Body:
It is pretty common for a web application to display a list of items and for each item in the list to indicate to the current user whether they have already viewed the associated item.

An approach that I have taken in the past is to store HasViewed objects that contain the Id of a viewed item/object and the Id of the User who has viewed that item/object.

When it comes time to display a list of items this requires querying the database for the items, and separately querying the database for the HasViewed objects, and then combining the results of these queries into a set of objects constructed solely for the purpose of displaying them in the view.

Each e.g li then uses the e.g. has_viewed property of the objects constructed above.

I think it is time to find a better approach and would like to know what approaches you would recommend.


问:
Implementing separation of concerns via MVC
I'm creating a question to see if my understanding of MVC separation is correct, I haven't been able to find a clear answer anywhere online. So is this the right way to implement it (in Java):

I would have 3 .java files, one each for Model, Controller, View.
I would put all the classes related to Model in the Model.java like so:

```<code>//Model.java {
    public class Model

    //class fields

    public Model();

    public ModelClassA();

    public ModelClassB();

    public ModelClassC();
    }
</code>```

With the ModelClasses being any class that I consider belonging to the Model. Is it correct to have the classes within the Model Class, as I have read that nested classes should be avoided where possible.

答:
I think you are mixing some terminology here. Java nested classes is not the same as a model having a property which is also a model.

If your concern is whether to have a model whose properties are other models- then this is OK (as long as the models are not nested classes in terms of a Java nested class). It is a good way to encapsulate logic and reduce code repetition.

Consider for instance an Order model (as an e-commerce order) and a Customer model. They both may need to use address information, so the order will have a ShippingAddress property, and the Customer would have an Address property. Both can be of the same type (same java class) and be represented by an additional model, say an Address model.

A nested Java class is a different thing. This is a class that is defined within another Java class, and in some cases a nested class may have special interactions allowed with the "hosting" class. You'd better check the Java documentation which describes the Java nested classes, and the difference between static and non-static nested classes.


答:
I'd attempt to enlist the basic clues over browsers which provide the visual differences, based on my own experience (and efforts) in that direction:

The fonts. The browser uses fonts (via the font-family css property) to display text on the page. Most of these fonts are coming from the operating system, so here is a short list of what can go wrong with that:

The different operating systems have different font families pre-installed, and when a certain font is missing, it is silently substituted with another. Moreover, the font that is used for substitution may be a native to the OS and specific to that particular OS only.

A particular font with size of 10px for instance, can look larger or smaller as the same 10px-sized font on another operating system.

The font appearance is determined also by the clear type effect, which is supported in different manner under the different operating systems. This feature may be disabled by default or not available at all on some OS-es. For example, Windows XP has it disabled, and below Windows versions do not support it at all, as far as I know. Under XP, you can also enable the clear-type only for the browser, not the entire OS, if you use IE7 or above. The lack of clear type will make a font look pixelated, and thus quite different from their clear-type-enabled version. Furthermore, the clear-type itself can be fine-tunned for best appearance, so one's personal settings may also cause slight difference in the look-and-feel of the text.

The rendering engine. The browsers use engines of their own to display the website and execute scripts, called rendering engines. The most popular browsers today come with rendering engines each of their own:

Trident is used by IE

Gecko is used by Firefox

WebKit is used by Safari and Chrome and yet they render pages differently.

Presto is the engine that Opera used to ship with, now it has switched to WebKit.

Each rendering engine may behave differently under different devices/operating systems. Chrome for instance, being a cross-platform browser, may show slightly observable differences under different OS-es, like Windows and Linux, even if both OS-es use the same browser version (also true terms of script behavior).

The browser version. The browser version is another important thing to look at. Why, you may ask. Here it is:

As browsers evolve, they are independently introducing new versions with individual patches for their rendering engine. Therefore, the latest patch for Safari's WebKit will likely be different than Chrome's most-current WebKit version.

One particular browser could come up changes that affect page display between its former and its current version. For instance Microsoft are deprecating many features from its Trident engine, so some IE7 display tricks and scripts will no longer work on the new IE11.

It is possible for an update to introduce a change that replaces the entire rendering engine, like is the case with Opera.

The client operating system. Besides the fonts and clear type effects, the basic styles of some HTML elements are provided by the appearance and the theme of the operating system - as pointed in the MichaelT's answer. Usually, this will affect the appearance of: buttons, combo boxes, scroll-bars, radio buttons and check-boxes, if not overridden by the page's styles. Older browsers, like IE6, may not support re-styling of these UI components, and they will appear as whatever the OS theme looks like.

Browser-specific code, hacks or spoofing. Last, but not least are the browser-specific hacks, which are practices that can be seen in css, javascript and html. These are done by web developers and designers to overcome some browser-specific issues and may cause display differences either accidentally, or on purpose. As mentioned by the first comment under the question, a developer or user might deliberately cause his browser to identify itself as another browser. Usually, it is a practice for developers to test how a website would look if viewed by a mobile browser while still working on a desktop PC, and some browsers have plug-ins that allow them to re-identify themselves as other known browsers.

Combine all the above and you will get a very comprehensive and wide range of factors that may cause a page to look (and even behave!) differently depending on the device, OS, browser, browser version and the page's own source code. And, I do not pretend to be exhausting all the possibilities.

Title: How can a website look different in safari Windows and Safari mac?

Body:
I have a website. I've been testing crossbrowser on my windows PC, and it looks good in all browsers, but on Mac in Safari it looks like the CSS is not getting interpreted right, or there is a critical javascript error.

When I look in the console cross-browser, the error log shows exactly the same. Chrome on mac interprets the site as intended, so why do I have a problem with safari?

It is the same across different computers, and iphone safari also shows the site wrong.

How is this possible and how do I debug?


问:
Testing a codebase with sequential cohesion
I've this really simple program written in C with ncurses that's basically a front-end to sqlite3. I would like to implement TDD to continue the development and have found a nice C unit framework for this.

However I'm totally stuck on how to implement it.

Take this case for example:
A user types a letter 'l' that is captured by ncurses getch(), and then an sqlite3 query is run that for every row calls a callback function. This callback function prints stuff to the screen via ncurses.

So the obvious way to fully test this is to simulate a keyboard and a terminal and make sure that the output is the expected. However this sounds too complicated.

I was thinking about adding an abstraction layer between the database and the UI so that the callback function will populate a list of entries and that list will later be printed. In that case I would be able to check if that list contains the expected values. However, why would I struggle with a data structure and lists in my program when sqlite3 already does this?

For example, if the user wants to see the list sorted in some other way, it would be expensive to throw away the list and repopulate it. I would need to sort the list, but why should I implement sorting when sqlite3 already has that? Using my orginal design I could just do an other query sorted differently.

Previously I've only done TDD with command line applications, and there it's really easy to just compare the output with what I'm expected. An other way would be to add CLI interface to the program and wrap a test program around the CLI to test everything. (The way git.git does with it's test-framework).

So the question is, how to add testing to a tightly integrated database/UI.

答:
Let's try an answer then. From what I understand we actually have two questions here:

How can you apply TDD when adding new features to a codebase that has not been developed with TDD itself?

How can you add tests for tightly coupled code?

Answer to question 1:

First of all, test-driven development is used for new code. By the very name of it TDD cannot be used to add tests to already existing code, because obviously, the development would not be driven by tests in that way. So TDD is out for question 2.

For question 1, however, you run into problems as soon, as your code interacts with the existing codebase in some way. Any completely new modules/classes can easily be developed with a TDD approach of course. When you have an interface to the existing code, you can still develop with a TDD approach, but that requires you to provide a mock or stub for the interface. This does not necessarily mean that you re-implement behavior.

A mock/stub need not have the full behavior of your original object. For example, it is perfectly fine to have a database stub that returns a constant list of thingies for every query you give it. It is sufficient to test whatever behavior you want to test that needs to work with that return list. You are after all not testing the database layer itself at that moment.

The problem gets more difficult, when you have to add code to existing classes/modules within a method, or maybe add calls to a new method. In those cases you suffer from the lack of tests of the original codebase and it can become troublesome to write tests. Mostly, this should be dealt with by improving the original codebase - see answer to question 2.

Answer to question 2:

When you have an existing codebase with high coupling and you want to test it, then first of all you should have a good reason to do so. It's a nice exercise, but does not per se add any value to your product, so you need some reason, where the existence of these tests gives you a future benefit.

Here's a bunch of typical reasons, why you want to do this:

The codebase is legacy and you are assigned to its maintenance. The tests will give you a better understand of what the code does, and provides a safety net against introducing errors when you make changes in the future.

The codebase will be significantly changed to adapt the product for new features. In that case you will be working with the code for a while, which means you will reap the benefits of the created tests during your ongoing development.

The codebase is subject to be replaced. For example, your database layer may be exchanged for another one. In that case, the tests will be used as a safety net to detect if the new database layer behaves differently.

Once you know why you want to write the tests, you can also focus your tests more thoroughly. If you want to continue development on the source, you will need fine-grained unit tests. If instead you just want to have tests against the whole module, any kind of integration test will suffice.

From what I can guess about your intentions, I'd say that your most likely reason seems to be that you have a legacy codebase that you want to continue working upon. In that case, the tests are step one and provide you a foundation upon which you can perform refactoring operations. Given the tests, you can rather quickly work on the coupling problems and improve the code design to make it more robust for future development.

Finally, to address your example about sorting lists: You need to think about which module is responsible for the sort operation, and whether or not it makes sense for you to test it. If you delegate sorting to the database layer (via sqlite queries), then you only need to test it if you plan to use the test against a new database layer implementation, in which you suspect sorting to behave differently. However, you need not re-implement any sorting to test your UI-side, because the UI itself has no sorting behavior whatsoever that could be tested. All you can test is that the UI respects the order of the elements it is given. In other words, there is no coupling between the database and the UI with respect to sorting. The database is responsible for sorting and just gives an ordered list to the UI. And the UI is only responsible for representing an ordered list of elements - no matter which order that is. Of course, you can also test your controller such that it does in fact call the correct query to create the requested sorting order.

It all comes down to the point that you want loose coupling: it forces you to define proper interfaces between your components, it allows you to test each individual component thoroughly and without needing any of the other component implementations.


问:
What is meant by, "A user shouldn't decide whether it is an Admin or not. The Privileges or Security system should."
The example used in the question pass bare minimum data to a function touches on the best way to determine whether the user is an administrator or not.  One common answer was:

```<code>user.isAdmin()
</code>```

This prompted a comment which was repeated several times and up-voted many times:

A user shouldn't decide whether it is an Admin or not. The Privileges
  or Security system should. Something being tightly coupled to a class
  doesn't mean it is a good idea to make it part of that class.

I replied,

The user isn't deciding anything. The User object/table stores data
  about each user. Actual users don't get to change everything about
  themselves.

But this was not productive.  Clearly there is an underlying difference of perspective which is making communication difficult.  Can someone explain to me why user.isAdmin() is bad, and paint a brief sketch of what it looks like done "right"?

Really, I fail to see the advantage of separating security from the system that it protects.  Any security text will say that security needs to be designed into a system from the beginning and considered at every stage of development, deployment, maintenance, and even end-of-life.  It is not something that can be bolted on the side.  But 17 up-votes so far on this comment says that I'm missing something important.

答:
Well, at the very least it violates single responsibility principle. Should there be changes(multiple admin levels, even more different roles?) this kind of design would be fairly messy and awful to maintain.

Consider the advantage of separating the security system from the user class, so that both can have single, well defined role. You end up with cleaner, easier to maintain design overall.


答:
I think that the issue, perhaps phrased poorly, is that it puts too much weight on the User class. No, there is no security issue with having a method User.isAdmin(), as was suggested in those comments. After all, if someone is deep enough in your code to inject malicious code for one of your core classes, you have serious problems. On the other hand, it doesn't make sense for the User to decide if it is an administrator for every context. Imagine that you add different roles: moderators for your forum, editors who can publish posts to the front page, writers who can write content for the editors to publish, and so on. With the approach of putting it on the User object, you'll end up with too many methods and too much logic living on the User that isn't directly related to the class.

Instead, you could use an enum of different types of permissions, and a PermissionsManager class.  Perhaps you could have a method like PermissionsManager.userHasPermission(User, Permission), returning a boolean value.  In practice, it might look like (in java):

```<code>if (!PermissionsManager.userHasPermission(user, Permissions.EDITOR)) {
  Site.renderSecurityRejectionPage();
}
</code>```

It's essentially equivalent to the Rails method before_filter method, which provides an example of this type of permissions check in the real world.

Title: What is meant by, "A user shouldn't decide whether it is an Admin or not. The Privileges or Security system should."

Body:
The example used in the question pass bare minimum data to a function touches on the best way to determine whether the user is an administrator or not.  One common answer was:

```<code>user.isAdmin()
</code>```

This prompted a comment which was repeated several times and up-voted many times:

A user shouldn't decide whether it is an Admin or not. The Privileges
  or Security system should. Something being tightly coupled to a class
  doesn't mean it is a good idea to make it part of that class.

I replied,

The user isn't deciding anything. The User object/table stores data
  about each user. Actual users don't get to change everything about
  themselves.

But this was not productive.  Clearly there is an underlying difference of perspective which is making communication difficult.  Can someone explain to me why user.isAdmin() is bad, and paint a brief sketch of what it looks like done "right"?

Really, I fail to see the advantage of separating security from the system that it protects.  Any security text will say that security needs to be designed into a system from the beginning and considered at every stage of development, deployment, maintenance, and even end-of-life.  It is not something that can be bolted on the side.  But 17 up-votes so far on this comment says that I'm missing something important.

Body:
I think that the issue, perhaps phrased poorly, is that it puts too much weight on the User class. No, there is no security issue with having a method User.isAdmin(), as was suggested in those comments. After all, if someone is deep enough in your code to inject malicious code for one of your core classes, you have serious problems. On the other hand, it doesn't make sense for the User to decide if it is an administrator for every context. Imagine that you add different roles: moderators for your forum, editors who can publish posts to the front page, writers who can write content for the editors to publish, and so on. With the approach of putting it on the User object, you'll end up with too many methods and too much logic living on the User that isn't directly related to the class.

Instead, you could use an enum of different types of permissions, and a PermissionsManager class.  Perhaps you could have a method like PermissionsManager.userHasPermission(User, Permission), returning a boolean value.  In practice, it might look like (in java):

if (!PermissionsManager.userHasPermission(user, Permissions.EDITOR)) {
  Site.renderSecurityRejectionPage();
}

It's essentially equivalent to the Rails method before_filter method, which provides an example of this type of permissions check in the real world.


答:
That comment was badly worded.

The point isn't whether the user object "decides" whether it is an admin, a trial user, a superuser or anything in or out of the ordinary. Obviously it doesn't decide any of those things, the software system at large, as implemented by you, does. The point is whether the "user" class should represent the roles of the principal that its objects represent, or whether this is a responsibility of another class.


问:
Naming methods that perform HTTP GET/POST calls?
In the application I am currently working on, there are generally 3 types of HTTP calls:

pure GETs

pure POSTs (updating the model with new data)

"GET" POSTs (posting down an object to get some data back, no updates to the model)

In the integration service, generally we name methods that post "postSomething()", and methods that get, "getSomething()".

So my question is, if we have a "GET" POST, should the method be called:

getSomething - seeing as the purpose is to obtain data

postSomething - since we are technically using POST

performSomeAction - arbitrary name that's more relevant to the action

What are everyone's thoughts?

答: I would use requestSomething. It is different than get and post, and is what you actually want to do.


问:
Why do large IT projects tend to fail or have big cost/schedule overruns?
I always read about large scale transformation or integration project that are total or almost total disaster. Even if they somehow manage to succeed  the cost and schedule blow out is enormous. What is the real reason behind large projects being more prone to failure. Can agile be used in these sort of projects or traditional approach is still the best.

One example from Australia is the Queensland Payroll project where they changed test success criteria to deliver the project.

See some more failed projects in this SO question (on Wayback Machine)

Have you got any personal experience to share?

答:
Steve McConnell (of "Code Complete" fame) has a list of the classic mistakes.

Some ineffective development practices have been chosen so often, by so many people, with such predictable, bad results that they deserve to be called "classic mistakes"...

This section enumerates three dozen classic mistakes. I have personally seen each of these mistakes made at least once, and I've made many of them myself...

The common denominator in this list is that you won't necessarily get rapid development if you avoid the mistake, but you will definitely get slow development if you don't avoid it...

For ease of reference, the list has been divided along the development-speed dimensions of people, process, product, and technology.

People

#1: Undermined motivation...

#2: Weak personnel...

#3: Uncontrolled problem employees...

#4: Heroics...

#5: Adding people to a late project...

#6: Noisy, crowded offices...

#7: Friction between developers and customers...

#8: Unrealistic expectations...

#9: Lack of effective project sponsorship...

#10: Lack of stakeholder buy-in...

#11: Lack of user input...

#12: Politics placed over substance...

#13: Wishful thinking...

Process

#14: Overly optimistic schedules...

#15: Insufficient risk management...

#16: Contractor failure...

#17: Insufficient planning...

#18: Abandonment of planning under pressure...

#19: Wasted time during the fuzzy front end. The "fuzzy front end" is the time before the project starts, the time normally spent in the approval and budgeting process...

#20: Shortchanged upstream activities... Also known as "jumping into coding"...

#21: Inadequate design...

#22: Shortchanged quality assurance...

#23: Insufficient management controls...

#24: Premature or too frequent convergence. Shortly before a product is scheduled to be released there is a push to prepare the product for release--improve the product's performance, print final documentation, incorporate final help-system hooks, polish the installation program, stub out functionality that's not going to be ready on time, and so on...

#25: Omitting necessary tasks from estimates...

#26: Planning to catch up later...

#27: Code-like-hell programming. Some organizations think that fast, loose, all-as-you-go coding is a route to rapid development...

Product

#28: Requirements gold-plating. Some projects have more requirements than they need right from the beginning...

#29: Feature creep...

#30: Developer gold-plating. Developers are fascinated by new technology and are sometimes anxious to try out new features... -- whether or not it's required in their product...

#31: Push me, pull me negotiation...

#32: Research-oriented development. Seymour Cray, the designer of the Cray supercomputers, says that he does not attempt to exceed engineering limits in more than two areas at a time because the risk of failure is too high (Gilb 1988). Many software projects could learn a lesson from Cray...

Technology

#33: Silver-bullet syndrome...

#34: Overestimated savings from new tools or methods... A special case of overestimated savings arises when projects reuse code from previous projects...

#35: Switching tools in the middle of a project...

#36: Lack of automated source-code control...


答:
I would not tie my method names to the HTTP operation they perform at all but with the semantics/business logic they offer.

Consider that the HTTP API you are using may change, which would impose that you go through your client code-base and update everything from "getXyzEntity" to "postXyzEntity" or "updateXyzEntity" or whatever.

If you implement these functions in a class hierarchy that is used all over your code base, you will end up having to update lots of client code for what is essentially an implementation detail.

I would call all my methods depending on what I wanted the client of the code to see (i.e. "client code wants to update Xyz Entity and should not care if that is implemented in terms of a HTTP GET, POST or that it even performs a HTTP call for that).

'getSomething` is OK for getting data from the server, but it should have nothing to do with it being implemented through a HTTP get, and everything with the it "getting data" and returning it to the client.

Title: Naming methods that perform HTTP GET/POST calls?

Body:
In the application I am currently working on, there are generally 3 types of HTTP calls:

pure GETs

pure POSTs (updating the model with new data)

"GET" POSTs (posting down an object to get some data back, no updates to the model)

In the integration service, generally we name methods that post "postSomething()", and methods that get, "getSomething()".

So my question is, if we have a "GET" POST, should the method be called:

getSomething - seeing as the purpose is to obtain data

postSomething - since we are technically using POST

performSomeAction - arbitrary name that's more relevant to the action

What are everyone's thoughts?


问:
How to practice object oriented programming?
I've always programmed in procedural languages and currently I'm moving towards object orientation. The main problem I've faced is that I can't see a way to practice object orientation in an effective way. I'll explain my point. When I've learned PHP and C it was pretty easy to practice: it was just matter of choosing something and thinking about an algorithm for that thing.

In PHP for example, it was matter os sitting down and thinking: "well, just to practice, let me build one application with an administration area where people can add products". This was pretty easy, it was matter of thinking of an algorithm to register some user, to login the user, and to add the products. Combining these with PHP features, it was a good way to practice.

Now, in object orientation we have lots of additional things. It's not just a matter of thinking about an algorithm, but analysing requirements deeper, writing use cases, figuring out class diagrams, properties and methods, setting up dependency injection and lots of things.

The main point is that in the way I've been learning object orientation it seems that a good design is crucial, while in procedural languages one vague idea was enough. I'm not saying that in procedural languages we can write good software without design, just that for sake of practicing it is feasible, while in object orientation it seems not feasible to go without a good design, even for practicing.

This seems to be a problem, because if each time I'm going to practice I need to figure out tons of requirements, use cases and so on, it seems to become not a good way to become better at object orientation, because this requires me to have one whole idea for an app everytime I'm going to practice.

Because of that, what's a good way to practice object orientation?

答:
Good question. Of course, what you are saying is that practicing OOP actually means practicing all of these things (requirements analysis, use cases, design patterns, etc.), which is true and may seem daunting at first.

My advice would be start your practice sessions by keeping two things in mind: test-driven development and the single responsibility principle.

Then just start off like you did with PHP/C: come up with an idea, think about what you need for that and implement these things one after the other. However, keep in mind, that you need to start from the tests (which forces you to define proper interfaces, as otherwise testability immediately suffers) and that TDD implies a red-green-refactor cycle. In other words, you have a tiny little bit of functionality, and once it's working you refactor to get a proper OO-design if you didn't make it from the start (which you won't).

When doing this refactoring step always remind yourself of the SRP. If you added a second responsibility to your object it's time to create something new.

When you develop like this, you need to be aware that your final solution will be far different from what you start with. Your learning curve will also be rather steep. For example, you will not learn what a Factory pattern is, but instead you will recognize the need for something that creates instances of your class in different ways. So if you haven't heard of object-oriented design patterns at all, it's good to read up a bit on those in parallel.


答:
Now, in object orientation we have lots of additional things.

No you don't...

It's not just a matter of thinking about an algorithm, but analysing requirements deeper, writing use cases, figuring out class diagrams, properties and methods, setting up dependency injection and lots of things.

None of those things are necessary for practicing object oriented programming.

This was pretty easy, it was matter of thinking of an algorithm to register some user, to login the user, and to add the products.

All object oriented programming is instead of thinking of the algorithms to do these steps, you think about what objects are needed to do these steps - what functionality you want, what state is needed to do that, and what sort of interface you want to expose to the user. Just like you have to do in procedural programming.

The only difference is that instead of focusing on the functions you need and how they work, you focus on how the functionality and state is grouped into responsibilities, and how those responsibilities interact.

How to practice? The same way you practice procedural programming: pick a problem and solve the problem using bundles of classes. Figure out how that sucked, repeat with lessons learned.

Title: How to practice object oriented programming?

Body:
I've always programmed in procedural languages and currently I'm moving towards object orientation. The main problem I've faced is that I can't see a way to practice object orientation in an effective way. I'll explain my point. When I've learned PHP and C it was pretty easy to practice: it was just matter of choosing something and thinking about an algorithm for that thing.

In PHP for example, it was matter os sitting down and thinking: "well, just to practice, let me build one application with an administration area where people can add products". This was pretty easy, it was matter of thinking of an algorithm to register some user, to login the user, and to add the products. Combining these with PHP features, it was a good way to practice.

Now, in object orientation we have lots of additional things. It's not just a matter of thinking about an algorithm, but analysing requirements deeper, writing use cases, figuring out class diagrams, properties and methods, setting up dependency injection and lots of things.

The main point is that in the way I've been learning object orientation it seems that a good design is crucial, while in procedural languages one vague idea was enough. I'm not saying that in procedural languages we can write good software without design, just that for sake of practicing it is feasible, while in object orientation it seems not feasible to go without a good design, even for practicing.

This seems to be a problem, because if each time I'm going to practice I need to figure out tons of requirements, use cases and so on, it seems to become not a good way to become better at object orientation, because this requires me to have one whole idea for an app everytime I'm going to practice.

Because of that, what's a good way to practice object orientation?


答:
You should favor parameterless constructors.

There's two main reasons for this, the first being that constructors have no good way to report errors. Sure, you can toss exceptions but that's a fairly high impact response to simple bad data - it forces the users of your object to treat it with undue care since any creation can throw.

The second is that it can sometimes (in some languages especially) cause disconnects (or duplicated code) between the validation for constructor setting and property setting to enforce your invariance. Since the class invariants are the same, the validation should be the same. By allowing two effective ways to set values, it complicates the class' validation.

To be clear, I'm not saying to never have parameterized constructors. And I'm definitely not saying to have some Initialization method. What I'm saying is that objects should have a clear, well-defined initial state with sane defaults.

Sometimes objects can't have sane defaults and instead need their initial state passed to them. It happens. But in general, you should look to avoid it.

Title: Is it better to have constructors with or without parameters?

Body:
Is it better to have constructors with or without parameters and why?

```<code>public NewClass( String a,  String b, int c) throws IOException
{
    //something
}
</code>```

OR

```<code>public NewClass()
{
    //something
}
</code>```


答:
Let's add some terminology, object-oriented analysis and object-oriented design, as Peter Coad did in the 1990's.

Together these form a software engineering discipline OOAD that can (done right) support the programmer at the point of writing and testing code.  Object-oriented programming can then have its proper level of granularity, skillful use of programming language features to meet the functional objectives and design requirements specified at a project level.

Sometimes it's a one-person project, and then you must wear all the hats (but not necessarily all at the same time).  I'm a huge fan of test-driven development for my own personal projects (see Frank's recommendation), but it doesn't pertain only to object-oriented software development.

In a team project having a good division of responsibilities is a key to successful implementation.  Skillful use of object-oriented design patterns helps team understanding by limiting the visible interfaces needed for analysis, data-feeds, and business logic to share a usable framework.


问:
Advice on designing web application with a 40+ year lifetime
Scenario

Currently, I am apart of a health care project whose main requirement is to capture data with unknown attributes using user generated forms by health care providers. The second requirement is that data integrity is key and that the application will be used for 40+ years. We are currently migrating the client's data from the past 40 years from various sources (Paper, Excel, Access, etc...) to the database. Future requirements are:

Workflow management of forms

Schedule management of forms

Security/Role based management

Reporting engine

Mobile/Tablet support

Situation

Only 6 months in, the current (contracted) architect/senior programmer has taken the "fast" approach and has designed a poor system. The database is not normalized, the code is coupled, the tiers have no dedicated purpose and data is starting to go missing since he has designed some beans to perform  "deletes" on the database. The code base is extremely bloated and there are jobs just to synchronize data since the database is not normalized. His approach has been to rely on backup jobs to restore missing data and doesn't seem to believe in re-factoring.

Having presented my findings to the PM, the architect will be removed when his contract ends. I have been given the task to re-architect this application. My team consists of me and one junior programmer. We have no other resources. We have been granted a 6-month requirement freeze in which we can focus on re-building this system.

I suggested using a CMS system like Drupal, but for policy reasons at the client's organization, the system must be built from scratch.

This is the first time that I will be designing a system with a 40+ lifespan. I have only worked on projects with 3-5 year lifespans, so this situation is very new, yet exciting.

Questions

What design considerations will make the system more "future proof"?

What questions should be asked to the client/PM to make the system more "future proof"?

答:
After I've read the question and the other (very well thought out) answers, I've thought that I'll leave my two cents as well. Note: I don't have to maintain any really old application/software at all. What I use as reference is my own work-in-progress hobby web app that grabs some open government data, parses and displays it in different formats. The app started as a project where I wasn't alone and where the gov just announced that it will offer this data somewhen, somehow. So it was clear that lots of things will change over time. And they did. What I learned from it:

Split things up in mini-applications. Each fully able to fulfill its task on its own. This makes switching out a single piece very fast, very secure and very easy. And when you have to go back in, it's not really hard to get around why things happen and how you they happen. If you or someone else will have to change something later on, it's easier to replace a single part than a whole set of things.

Get a solid constant middleware/-layer that is used for communication between the different parts. In this case I used JSON, but XML, ini or similar standards would be fine as well. It's easy to repeat and can be transformed into nearly anything. All are proven standards that will survive quite some time. Even if the underlying data and/or storage model will change. Each of the apps can use their own data storage for its specific task. This makes the amount of scanned data for a task smaller, therefore easier to handle and maintain and is easier exchangeable.

Don't worry about programming language decisions. Those will change over time. Just make sure that you use the language that you're comfortable with or that fits a task best.

Make sure that your data storage is "horizontally scaleable" and that it's easy to plug in additional storage modules.

Get a common point (in my case it's URIs) where the mini-apps are called and/or exchange data.

Summed up: The thing I'd care most about is the separation of concerns and exchange-ability of parts that are assigned for tasks. You simply know that in 40 years (even in 5 or 10) hardware, interfaces, storage, etc. will change a lot. And later developers will have to react on those changes and exchange parts of your application, be it the data container or parts of the User Interface.


答:
I would suggest using event sourcing and command and query responsibility segregation. This is mainly because the only thing that you can be sure about is the events that already appeared. New types of events might come. So even if you put heavy thoughts on a model, it is sure that this will get outdated. Migrating all data with every release might not be feasible. So the best is to have a model that fits your current needs and which is calculated from already recorded events every time you need it and then to pass out events that are computed from the current state of that model.

Also have testing in mind. If the application is in use in ten years from now, testers have to make sure that it is still doing what its supposed to do. So make integration testing your application as easy as possible.

Title: Advice on designing web application with a 40+ year lifetime

Body:
Scenario

Currently, I am apart of a health care project whose main requirement is to capture data with unknown attributes using user generated forms by health care providers. The second requirement is that data integrity is key and that the application will be used for 40+ years. We are currently migrating the client's data from the past 40 years from various sources (Paper, Excel, Access, etc...) to the database. Future requirements are:

Workflow management of forms

Schedule management of forms

Security/Role based management

Reporting engine

Mobile/Tablet support

Situation

Only 6 months in, the current (contracted) architect/senior programmer has taken the "fast" approach and has designed a poor system. The database is not normalized, the code is coupled, the tiers have no dedicated purpose and data is starting to go missing since he has designed some beans to perform  "deletes" on the database. The code base is extremely bloated and there are jobs just to synchronize data since the database is not normalized. His approach has been to rely on backup jobs to restore missing data and doesn't seem to believe in re-factoring.

Having presented my findings to the PM, the architect will be removed when his contract ends. I have been given the task to re-architect this application. My team consists of me and one junior programmer. We have no other resources. We have been granted a 6-month requirement freeze in which we can focus on re-building this system.

I suggested using a CMS system like Drupal, but for policy reasons at the client's organization, the system must be built from scratch.

This is the first time that I will be designing a system with a 40+ lifespan. I have only worked on projects with 3-5 year lifespans, so this situation is very new, yet exciting.

Questions

What design considerations will make the system more "future proof"?

What questions should be asked to the client/PM to make the system more "future proof"?


问:
The Agile process: how and what should be documented?
A while ago the company I work for had outsourced a development project to a third party. They employed agile practices in developing the solution. However when asked for documentation they would just say it was required as it was incorporated in a wiki or as part of their sprints.

They did leave at the completion of the project, with all but one of the project team. The project wiki site has now been closed down once the yearly subscription was due.

When they left they took most of the knowledge and understanding of what was developed with them.

So I do have 2 main questions;

Is this normal for agile or just an excuse for not wanting to write it?

What are the industry norm for documentation in agile projects to record development
requirements, designs, key decisions and context?

答: Your problem has nothing to do with Agile. They should have produced the documentation that you asked for. The project was poorly managed. </p>