问:
Do higher resolution laptop displays matter for programmers?
I'm buying a new laptop that I'll be using mainly for programming.  A couple of options that really intrigue me are the Asus Zenbook UX31A and the new Retina Macbook Pro.  It's obvious that the high-resolution displays on these laptops is useful for entertainment, photo-editing, and other things.  My question is this:  Do these displays provide any benefit for programmers?  Do these displays make code any easier to read?  Are they any easier on the eyes after a whole day of staring at the screen?</p>

答:
tl;dr = yes; code readability decreases sharply with resolution, and I see no reason why making bugs literally harder to see wouldn't result in...making bugs harder to see.

The stats have it. Reading speed is increased by up to 25% on displays of 300dpi (as opposed to the average resolution of PC desktop monitors.) Or so says usability guru Jakob Nielsen, at least. Comprehension is also up sharply, IIRC.

http://www.useit.com/alertbox/web-typography.html is a little OT, but provides excellent context for the somewhat older guidelines at http://www.useit.com/alertbox/9703b.html.

I can already hear gruff geeks trying out some tough-guy line about how real coders have so much screentime behind them that they can read code at any resolution. But of course they can't prove it, because they've never benchmarked their own brains. They just have gut-intuition that they read pretty good on a computer, perhaps better than most, and that it comes with the territory. So file this one under other flights of hypermasculinity and cultural egocentrism. (How do you suppose resolution affects a non-native reader of English? How do you suppose that the industry is affected by restricting the supply of coders to those with unusually precise eyesight?)

Yes, resolution matters -- a lot -- and yes, Apple is slaughtering everyone else as usual, because no one else seems to consider the 'U' in UX. Go buy that Retina MBP. I might bump into you in line.


问:
Is it worth to learn Experimental Languages?
I'm a young programmer who desires to work in the field someday as a programmer.  I know Java, VB.NET and C#.  I want to learn a new language (as I programmer, I know that it is valuable to extend what I know - to learn languages that make you think differently).  I took a look online to see what languages were common.  Everybody knows C and C++ (even those muggles who know so little about computers in general), so I thought, maybe I should push for C.

C and C++ are nice but they are old.  Things like Haskell and Forth (etc. etc. etc.) are old and have lost their popularity.  I'm scared of learning C (or even C++) for this same reason.  Java is pretty old as well and is slow because it's run by the JVM and not compiled to native code.

I've been a Windows developer for quite a while.  I recently started using Java - but only because it was more versatile and spreadable to other places.  The problem is that it doesn't look like a very usable language for these reasons:

It's most used purpose is for web application and cellphone apps (specifically Android)

As far as actual products made with it, the only things that come to mind are Netbeans, Eclipse (hurrah for making and IDE with the language the IDE is for - it's like making a webpage for writing HTML/CSS/Javascript), and Minecraft which happens to be fun but laggy and bipolar as far as computer spec. support.

Other than that it's used for servers but heck - I don't only want to make/configure servers.

The .NET languages are nice, however:

People laugh if I even mention VB.NET or C# in a serious conversation.

It isn't cross-platform unless you use MONO (which is still in development and has some improvements to be made).

Lacks low level stuff because, like Java with the JVM, it is run/managed by the CLR.

My first thought was learning something like C and then using it to springboard into C++ (just to make sure I would have a strong understanding/base), but like I said earlier, it's getting older and older by the minute.

What I've Looked Into

Fantom looks nice.  It's like a nice middleman between my two favorite languages and even lets me publish between the two interchangeably, but, unlike what I want, it compiles to the CLR or JVM (depending on what you publish it to) instead of it being a complete compile.

D also looks nice.  It seems like a very usable language and from multiple sources it appears to actually be better than C/C++.  I would jump right with it, but I'm still unsure of its success because it obviously isn't very mainstream at this point.

There are a couple others that looked pretty nice that focused on other things such as Opa with web development and Go by GOOGLE.

My Question

Is it worth learning these "experimental" languages?  I've read other questions that say that if you aren't constantly learning languages and open to all languages that you aren't in the right mindset for programming.  I understand this and I still might not quite be getting it, but in truth, if a language isn't going to become mainstream, should I spend my time learning something else?  I don't want to learn old (or any going to soon be old) programming languages.  I know that many people see this as something important, *but would any of you ever actually consider (assuming you didn't already know) FORTRAN?  My goal is to stay current to make sure I'm successful in the future.

Disclaimer

Yes, I am a young programmer, so I probably made a lot of naive statements in my question.  Feel free to correct me on ANYTHING!  I have to start learning somewhere so I'm sure a lot of my knowledge is sketchy enough to have caused to incorrect statements or flaws in my thinking.  Please leave any feelings you have in the comments.

The Results...

I'm truly amazed by the amazing responses, most of them so nicely pointing out my misunderstandings and misjudgments.  I've learned quite a lot from this and I'm excited to hopefully utilize everything I've learned!  I'll probably start learning Haskell next (the not so old language, albeit over 20 years old - hahaha) and then start looking at some other options around me.

Thanks

答:
You could say that learning to program in a language like Postscript or APL is arguably a waste of time primarily because the chances of you ever using that knowledge approaches zero. But by the same vein, you could argue that Ruby and Python are a waste of time if you never intend to use them for anything.

But few people would say that learning Lisp is a waste, even though you're about as likely to have to write Lisp as Postscript; but learning Lisp teaches you to think differently about your problem (hopefully), which is why most programmers will tell you that it's worth your time.

Still, I never shy away from learning a new language since the required time investment is really only an hour or four. And uses for a language like Lua pop up in the most unusual places, and you would have never recognized them if you hadn't spent a few hours running through the examples.

When you see a new language, read up a bit on what it's useful for. If it's a niche your favorite languages don't cover too well, then take a day to learn the basics. It's certainly time better spent than watching season 17 of The Bachelor or however else you may waste time. That way, if you have a use for it, it can pop into mind and you know where to find out more.

I'd personally really recommend looking in to Go. I've used it to write single-page programs that perform better than what would take three days and 13 third-party libraries in C or C++, and wouldn't even be possible in Python, C#, Ruby, etc. It was designed by people who really, really, really know their stuff.

ContentLicense: CC BY-SA 3.0


答:
Yes, the screen resulution is extremally important thing for programmer. While the quality of the colours is the most important for web developers (for SQL programmers etc. it's a minor issue), everyone will benefit from high resolution.

I'm actually working on laptop with screen resolution 1366x768 and it's a big mistake to buy something like that for the programmer. It's hard to work with Eclipse, because not much code fits on the screen. I need the console which is 200 characters wide and it hardly fits on the screen, the Android simulator doesn't fit at all. Fortunatelly I have external screen, but it's not very comfortable to type on laptop keyboard and look on the screen that stays on the side.

Almost everyone I know uses 2 displays when it is possible, and some use even 3. Generally, they are using the biggest display available, 24'' with full HD. Such resolution makes sense, because you can fit more things on screen - and one use a lot of them - IDE, a few consoles, web browser, skype etc. - and what is worse, everything should be visible at once.

So, if you want to make your developers more productive, don't buy the laptop with low resolution, please!

Title: Do higher resolution laptop displays matter for programmers?

Body: I'm buying a new laptop that I'll be using mainly for programming.  A couple of options that really intrigue me are the Asus Zenbook UX31A and the new Retina Macbook Pro.  It's obvious that the high-resolution displays on these laptops is useful for entertainment, photo-editing, and other things.  My question is this:  Do these displays provide any benefit for programmers?  Do these displays make code any easier to read?  Are they any easier on the eyes after a whole day of staring at the screen?</p>


问:
Unit and Integration testing: How can it become a reflex
All the programmers in my team are familiar with unit testing and integration testing. We have all worked with it. We have all written tests with it. Some of us even have felt an improved sense of trust in his/her own code.

However, for some reason, writing unit/integration tests has not become a reflex for any of the members of the team. None of us actually feel bad when not writing unit tests at the same time as the actual code. As a result, our codebase is mostly uncovered by unit tests, and projects enter production untested.

The problem with that, of course is that once your projects are in production and are already working well, it is virtually impossible to obtain time and/or budget to add unit/integration testing.

The members of my team and myself are already familiar with the value of unit testing (1, 2) but it doesn't seem to help bringing unit testing into our natural workflow. In my experience making unit tests and/or a target coverage mandatory just results in poor quality tests and slows down team members simply because there is no self-generated motivation to produce these tests. Also as soon as pressure eases, unit tests are not written any more.

My question is the following: Is there any methods that you have experimented with that helps build a dynamic/momentum inside the team, leading to people naturally wanting to create and maintain those tests?

答:
To have a group of programmers in which all naturally want to do something is an utopy (especially when talking about a large group).

Unit and integration testing is a thing of standards. You create a standard for an workflow and each member of the team should respect it. The standards should be made with the aid of QA professionals, because they know it better. An programmers should respect the standards.
What you can do is make the standards clean, easy to understand and follow.

It is not about trust in your own code and desires to use, it is about needing to have coding and testing standards that everyone use in order to make good things, and any programmer should understand this.

When you make people from the start follow the standard, it becomes a reflex and it will be followed. Making it a rule that no code can be put in the codebase without a unit test would convince people that they have to do it.
For project repositories there are even more restrictive rules. For example, companies make unit tests before actually coding the unit (when they make the module specification) and this is a very good method. If a programmer puts code in the project/codebase the code is run throught the test module and if the unit tests don't pass, they go back to work.

If it is hard at the moment to add standards and rules, at least think of adding them in future projects.


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

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

答:
There are only two kinds of languages: the ones people complain about and the ones nobody uses

— Bjarne Stroustrup

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Herding your users to your bugtracker
I have a fully configured mantis bug tracker for tracking issues in apps that I create.  When an user is disciplined and goes straight to mantis to write a issue report, he/she will have fastest response and everything regarding the issue will be very easy to track.

However, not everyone is keen to do so.  They report their problems via phone, e-mail, don't report them at all.

What would be the best way to nudge them towards the using a bugtracker system?  Clearly, they HAVE to see some immediate benefits so they can return and look for more benefits.

EDIT:

I am talking about support for the products that I sell as an ISV.

答:
Internally we have a site template for web applications that includes a feedback link in the corner. This feedback link is provides the user with a jQuery UI dialog that prompts them for a description of the bug, new feature, or other that they encountered and also captures some details about the page and time they are reporting from. All this is pushed directly into JIRA behind the scenes and the user can get updates with the status of the issue.

In sort the best way of doing things is usually by making it as simple as possible for the users, if there is a feedback link in a menu that handles sending the information where it needs to go, they are much more likely to use it.

Title: Herding your users to your bugtracker


问:
Process monitoring in Linux environment?
I'm trying to write a multi threaded/processes application and it need to know how to monitor a process from another process all the time.
So here is what I have, I have a 2 processes, each with multiple threads that handle the network part, then another 2 process also with multiple threads that interact with DB and with the network processes, what I need to do is that if for example one of the network processes goes down the DB process start sending to the live network process until the second one is up again.
I'm using fifo between the DB and the network process.

I was thinking of sending messages with message passing all the time but not sure whether this is a good idea or I need to use some other IPC for this issue, or probably neither is good and I need to use entirely something else?

答:
I would say that you should not depend on this for routing the messages. I'd suggest having a single message queue that all network threads would pick messages from, so if one dies, all unprocessed messages eventually get picked up by the other (instead of some between the thread dying and the watchdog detecting it being send to black hole). The one during processing of which it crashed will still be lost, so you still need some resilience, but the disruption will be smaller.

Than you'd just have a watchdog to make sure there is always required number of threads running. The threads would send a message to the watchdog every n seconds and if no message is received from some thread for 3 or 4 times n, the watchdog would kill it and start new one.


问:
Why is it good to split a program into multiple classes?
I'm still a student in high school (entering 10th grade), and I have yet to take an actual computer course in school. Everything I've done so far is through books. Those books have taught me concepts such as inheritance, but how does splitting a program into multiple classes help? The books never told me.

I'm asking this mainly because of a recent project. It's an arcade video game, sort of like a Flash game as some people have said (although I have no idea what a Flash game is). The thing is, it's only one class. It works perfectly fine (a little occasional lag however) with just one class. So, I'm just asking how splitting it into multiple classes would help it.

This project was in Java and I am the only person working on it, for the record.

答:
It is not about splitting a program into classes but about how you model your application i.e. how you visualize parts of your application. Splitting things is just a mechanism we use to understand complex things better. It is not only with programming. Imagine circuit board with many wires entangled with each other, forming a complex structure with each wire connecting somewhere (spaghetti code). You'll have to follow each wire to its end to figure out the connections. On the contrary imagine wires that are grouped and color coded as per their function. It becomes a lot easier to fix things.

Idea is that you don't start with a long program and then split it into classes. But you model your application in terms of objects/classes first and then connect them to build applications.


问:
What is a user-friendly solution to editing email templates with replacement variables?
I'm working on a system where we rely a lot of "admins / managers" emailing users from the database. One of the key features is being able to email several people at the same time, with specific information relevant to each of them. Another key feature is to be able to hand-craft emails, because it tends to be be necessary to slightly modify them each time, but having a basic template saves a lot of time.

For this, we have the typical "templates" solution, where we have a template that looks kind of like this:

```<code>Hello {{recipient.full_name}},

Your application to {{activity.title}} has been accepted.
You have requested to participate on dates {{application.dates}}, in role {{application.role}}
Blah blah blah
</code>```

The problem we are having is obviously that (as we expected), managers don't get the whole "variables" idea, and they do things like overwriting them, which doesn't let them email more than one person at a time, assuming those are not going to get replaced and that the system is broken, or even inexplicable things like "Hello {{John}}".

The big problem is that this isn't relegated, as usual, to an "admin" section where only a few power users have access to editing the templates that are automatically send out, and they're expected to know what they are doing. Every user of the system gets exposed to this problem.

The obvious solution would be to replace the variables before showing this template for the user to edit, but that doesn't work when emailing several people.

This seems like a reasonably common problem, and we are kind of hoping that someone has already solved it.

Have you seen anywhere/created/can think of good solutions to this problem?

Update

What I ended up doing based on Daniel B's answer was detecting, based on the cursor position, and the position of {{ }} in the code whether the user is currently "inside a variable" or "outside". In inside, I show a little piece of text below the big textarea explaining that this is going to get replaced, and that they can remove it completely if they want, but they can't edit it.

I do this onClick, onChange, onKeyDown, onKeyUp. For the "key" events, if we're inside a variable, I only return TRUE if the keyCode is one of a few "navigational" keys. Otherwise, I return FALSE, which effectively prevents the edition of that variable.

It's not perfect, but it was very cheap, and seems effective.

答:
I'd consider changing how the template is presented to the user so that you can make the parts that will be changed by the code non editable. Something like this:

The bits that you don't want the user to change are now not editable. You could include a close button so that they can remove the items if they don't need them. You can also include explanatory text and/or tooltips to explain what the {{...}} bits mean and why they should be left alone.

Using something like a Silverlight/WPF WrapPanel for each paragraph might give you something that allows each part (editable and not editable) to flow as the user controlled text grows and shrinks.

OwnerDisplayName: Daniel Magliola

OwnerDisplayName: ChrisF


问:
Zero as a constant?
I have come across this programming idiom recently:

```<code>const float Zero = 0.0;
</code>```

which is then used in comparisons:

```<code>if (x > Zero) {..}
</code>```

Can anyone explain if this is really any more efficient or readable or maintainable than:

```<code>if (x > 0.0) {..}
</code>```

NOTE: I can think of other reasons to define this constant, Im just wondering about its use in this context.

答:
First of all, here zero is defined as float, not int. Of course, this doesn't affect anything in the comparison, but in other cases when this constant is used, it might make difference.

I see no other reason why Zero is declared a constant here. It's just some coding style, and it's better to follow the style if it is used everywhere else in that certain program.

Title: Zero as a constant?


答:
It's almost certainly exactly as efficient during execution (unless your compiler is very primitive) and very slightly less efficient during compilation.

As to whether that's more readable than x > 0... remember that there are people who honestly, genuinely, think that COBOL was a great idea and a pleasure to work with - and then there are people who think exactly the same about C. (Rumor has it that there even exist some programmers with the same opinion about C++!) In other words, you are not going to get general agreement on this point, and it's probably not worth fighting over.

Title: Zero as a constant?

Body:
I have come across this programming idiom recently:

```<code>const float Zero = 0.0;
</code>```

which is then used in comparisons:

```<code>if (x > Zero) {..}
</code>```

Can anyone explain if this is really any more efficient or readable or maintainable than:

```<code>if (x > 0.0) {..}
</code>```

NOTE: I can think of other reasons to define this constant, Im just wondering about its use in this context.


答:
Possible reasons are caching, naming or forcing type

Caching (not applicable)

You want to avoid the cost of creating an object during the act of comparison. In Java an example would be

```<code>BigDecimal zero = new BigDecimal ("0.0");
</code>```

this involves a fairly heavy creation process and is better served using the provided static method:

```<code>BigDecimal zero = BigDecimal.ZERO;
</code>```

This allows comparisons without incurring a repeated cost of creation since the BigDecimal is pre-cached by the JVM during initialisation.

In the case of what you have described, a primitive is performing the same job. This is largely redundant in terms of caching and performance.

Naming (unlikely)

The original developer is attempting to provide a uniform naming convention for common values throughout the system. This has some merit, especially with uncommon values but something as basic as zero is only worth it in the case of the caching case earlier.

Forcing type (most likely)

The original developer is attempting to force a particular primitive type to ensure that comparisons are cast to their correct type and possibly to a particular scale (number of decimal places). This is OK, but the simple name "zero" is probably insufficient detail for this use case with ZERO_1DP being a more appropriate expression of the intent.

Title: Zero as a constant?

Body:
Possible reasons are caching, naming or forcing type

Caching (not applicable)

You want to avoid the cost of creating an object during the act of comparison. In Java an example would be

BigDecimal zero = new BigDecimal ("0.0");

this involves a fairly heavy creation process and is better served using the provided static method:

BigDecimal zero = BigDecimal.ZERO;

This allows comparisons without incurring a repeated cost of creation since the BigDecimal is pre-cached by the JVM during initialisation.

In the case of what you have described, a primitive is performing the same job. This is largely redundant in terms of caching and performance.

Naming (unlikely)

The original developer is attempting to provide a uniform naming convention for common values throughout the system. This has some merit, especially with uncommon values but something as basic as zero is only worth it in the case of the caching case earlier.

Forcing type (most likely)

The original developer is attempting to force a particular primitive type to ensure that comparisons are cast to their correct type and possibly to a particular scale (number of decimal places). This is OK, but the simple name "zero" is probably insufficient detail for this use case with ZERO_1DP being a more appropriate expression of the intent.


答:
This might make sense since it explicitly defines Zero to be of type float.

At least in C and C++ the value 0.0 is of type double, while the equivalent float is 0.0f. So assuming the x you compare against is also always a float saying

```<code>x > 0.0
</code>```

while actually promote x to double to match the type of 0.0 which might lead to issues (with equality tests especially). The comparison without conversion would of course be

```<code>x > 0.0f
</code>```

which does the same as

```<code>float Zero = 0.0; // double 0.0 converted to float
x > Zero
</code>```

Nevertheless, I think it would be much more useful to enable warnings of conversions in the compiler instead of having users write awkward code.

Title: Zero as a constant?

Body:
This might make sense since it explicitly defines Zero to be of type float.

At least in C and C++ the value 0.0 is of type double, while the equivalent float is 0.0f. So assuming the x you compare against is also always a float saying

x > 0.0

while actually promote x to double to match the type of 0.0 which might lead to issues (with equality tests especially). The comparison without conversion would of course be

x > 0.0f

which does the same as

float Zero = 0.0; // double 0.0 converted to float
x > Zero

Nevertheless, I think it would be much more useful to enable warnings of conversions in the compiler instead of having users write awkward code.


答:
It's Because of "Tooling Nagging"

A possible reason I don't see listed here is because a lot of quality tools flag the use of magic numbers. It's often a bad practice to have magic numbers thrown into an algorithm without making them clearly visible for change later, especially if they are duplicated in multiple places in the code.

So, while these tools are right about flagging such issues, they often generate false positives for situations where these values are harmless and most likely to be static, or to just be initialization values.

And when that happens, sometimes you face the choice of:

marking them as false positives, if the tool allows it (usually with a specially formatted comment, which is annoying for people NOT using the tool)

or extracting these values to constants, whether it matters or not.

About Performance

It depends on the language I guess, but this is fairly common in Java and has no performance impact, as values are inlined at compile time if they are real constants static final. It wouldn't have an impact in C or C++ if they are declared as constants or even as pre-processor macros either.

Title: Zero as a constant?


问:
UI message passing programming paradigm
I recently (about two months ago) read an article that explained some user interface paradigm that I can't remember the name of and I also can't find the article anymore.

The paradigm allows for decoupling the user interface and backend through message passing (via some queueing implementation). So each user action results in a message being pased to the backend. The user interface is then updated to inform the user that his request is being processed.

The assumption is that a user interface is stale by definition. When you read data from some store into memory, it is stale because another transaction may be updating the same data already. If you assume this, it makes no sense to try to represent the 'current' database state in the user interface (so the delay introduced by passing messages to a backend doesn't matter).

If I remember correctly, the article also mentioned a read-optimized data store for rendering the user interface.

The article assumed a high-traffic web application. A primary reason for using a message queue communicating with the backend is performance: returning control to the user as soon as possible. Updating backend stores is handled by another process and eventually these changes also become visible to the user.

I hope I have explained accurately enough what I'm looking for. If someone can provide some pointers to what I'm looking for, thanks very much in advance.

答:
Sounds like CQRS - Command Query Responsibility Segregation

Here's Martin Fowler on the subject: http://martinfowler.com/bliki/CQRS.html

Title: UI message passing programming paradigm


问:
Should this code/logic be included in Business Objects class or a separate class?
I have created a small application which has a three tier architecture and I have business object classes to represent entities such as User, Orders, UserType etc. In these classes I have methods that are executed when the Constuctor method of, for example, User is called. These methods perform calculations and generate details that setup data for attributes that are part of each User object.

Here is the structure for the project in Visual Studio:

Here is some code from the business object class User.cs:

```<code>Public Class User
{
    public string Name { get; set; }
    public int RandomNumber { get; set; }
    etc

        public User
        {
            Name = GetName();
            RandomNumber = GetRandomNumber();
        }

        public string GetName()
        {
          ....
          return name;
        }

        public int GetRandomNumber()
        {
           ...
           return randomNumber;
        }

    }
</code>```

Should this logic be included in the Business Object classes or should it be included in a Utilities class of some kind? Or in the business rules?

答:
The theory:

A class should be responsible for its data and know what to do with its data.  Any methods that the class needs to enforce that responsibility should be within the class.

In Practice:

So the class will have User.Name and it should also have User.GetName(), User.GetFirstName(), User.GetLastName() as Name belongs to the User and the User should know how to manipulate its Name property.

You should not have a UserUtils.GetFirstNameFromName() for example.

Let's also say that we have User.TaxID and there should be appropriate get / set statements in order to retrieve that property.  However, we should not have User.CreateTaxID as the User class wouldn't / shouldn't have anything to do with getting a foreign identifier to the class.

Instead, this is a great case for UserUtils.CreateTaxID.

So the answer to your question is both "yes" and "no" depending upon what the functions are actually doing.


答:
By request from the comments in ChrisF's answer, here's one solution I've used in the past:

Use a WinForms RichTextBox to allow the user to edit the text of the template.

Allow drag / drop (or other inserting) of variables or placeholders into the RichTextBox.

Disallow editing of the variables themselves by checking around the current place of the cursor for the delimiters of your variables (the {{ and }} symbols, in your example).

My implementation ended up looking something like this:

It has optional highlighting of the variable to differentiate it from the standard text.

The variable delimiters are actually there, they just happen to have the same foreground and background colours.

Obviously, this is quite different to your implementation, which is HTML-based.  I would probably look into how Gmail's editor is implemented; it seems to be similar to a textarea, but is able to have inline images (smilies, etc), which is similar to the behaviour you are looking for.

Title: What is a user-friendly solution to editing email templates with replacement variables?

Body:
I'm working on a system where we rely a lot of "admins / managers" emailing users from the database. One of the key features is being able to email several people at the same time, with specific information relevant to each of them. Another key feature is to be able to hand-craft emails, because it tends to be be necessary to slightly modify them each time, but having a basic template saves a lot of time.

For this, we have the typical "templates" solution, where we have a template that looks kind of like this:

```<code>Hello {{recipient.full_name}},

Your application to {{activity.title}} has been accepted.
You have requested to participate on dates {{application.dates}}, in role {{application.role}}
Blah blah blah
</code>```

The problem we are having is obviously that (as we expected), managers don't get the whole "variables" idea, and they do things like overwriting them, which doesn't let them email more than one person at a time, assuming those are not going to get replaced and that the system is broken, or even inexplicable things like "Hello {{John}}".

The big problem is that this isn't relegated, as usual, to an "admin" section where only a few power users have access to editing the templates that are automatically send out, and they're expected to know what they are doing. Every user of the system gets exposed to this problem.

The obvious solution would be to replace the variables before showing this template for the user to edit, but that doesn't work when emailing several people.

This seems like a reasonably common problem, and we are kind of hoping that someone has already solved it.

Have you seen anywhere/created/can think of good solutions to this problem?

Update

What I ended up doing based on Daniel B's answer was detecting, based on the cursor position, and the position of {{ }} in the code whether the user is currently "inside a variable" or "outside". In inside, I show a little piece of text below the big textarea explaining that this is going to get replaced, and that they can remove it completely if they want, but they can't edit it.

I do this onClick, onChange, onKeyDown, onKeyUp. For the "key" events, if we're inside a variable, I only return TRUE if the keyCode is one of a few "navigational" keys. Otherwise, I return FALSE, which effectively prevents the edition of that variable.

It's not perfect, but it was very cheap, and seems effective.


答:
Your bug tracker is for your convenience, not your customers'. If you can't be bothered to take their phone or email issue and enter it yourself, how do you think they feel?

You need to be able to enter issues and assign them manually to a client. Then when they call in with an issue you can say, "Thanks for reporting that! I'm going to enter it into our issue management system, and you'll start getting email (or whatever) as we deal with it. In the future, if it's easy for you, you can enter that sort of thing right there. Or feel free to just call me, that's fine too."

One of the best such systems I've worked with as a customer is the one at the hosting provider I resell. Email to support@ gets parsed for a domain name in the subject line, assigned to a client account based on the from address, and auto-entered into their ticket system. Pretty slick.

Title: Herding your users to your bugtracker

Body:
I have a fully configured mantis bug tracker for tracking issues in apps that I create.  When an user is disciplined and goes straight to mantis to write a issue report, he/she will have fastest response and everything regarding the issue will be very easy to track.

However, not everyone is keen to do so.  They report their problems via phone, e-mail, don't report them at all.

What would be the best way to nudge them towards the using a bugtracker system?  Clearly, they HAVE to see some immediate benefits so they can return and look for more benefits.

EDIT:

I am talking about support for the products that I sell as an ISV.


答:
If you want follow the OO principles, the answer to this question is yes. An object is responsible to manage its state and behaviour. This means that all the property and methods that describe the object should be implemented in the the base class.

This is a written rule, a theory.

Form the practical side, you can decide to split classes for many reasons:

Personal organization

Readability

Avoid huge classes

This is up to you.

Title: Should this code/logic be included in Business Objects class or a separate class?

Body:
I have created a small application which has a three tier architecture and I have business object classes to represent entities such as User, Orders, UserType etc. In these classes I have methods that are executed when the Constuctor method of, for example, User is called. These methods perform calculations and generate details that setup data for attributes that are part of each User object.

Here is the structure for the project in Visual Studio:

Here is some code from the business object class User.cs:

```<code>Public Class User
{
    public string Name { get; set; }
    public int RandomNumber { get; set; }
    etc

        public User
        {
            Name = GetName();
            RandomNumber = GetRandomNumber();
        }

        public string GetName()
        {
          ....
          return name;
        }

        public int GetRandomNumber()
        {
           ...
           return randomNumber;
        }

    }
</code>```

Should this logic be included in the Business Object classes or should it be included in a Utilities class of some kind? Or in the business rules?


问:
What is the best objective way to measure language popularity trends? (What's better than TIOBE?)
The best way to get data on computer language popularity that I know is the TIOBE index.  But everyone knows that TIOBE is hopelessly flawed.  (If someone provides a link to support this, I'll add it here.)

So is there any data on programming language popularity that is generally considered meaningful?  The only other option I know is to look at the trends at indeed.com, which is inherently flawed, being based on job postings.

It isn't like I would make a future language decision solely based on an index, but it might provide a useful balance to the skewed perspective one obtains by talking to ones friends and colleagues.

To illustrate that bias, I'll point out that based on the experience of those I personally know, the only languages used professionally today (in order of popularity) are Java, C#, Groovy, JavaScript, Ruby, Objective C, and Perl.  (Though it is evident that C, C++ and PHP were used in the past.)

So my question is, everyone bashes TIOBE, but is there anything else?  If so, can anyone explain how we know the alternative has better methodology?  Thanks.

答:
As everyone says "its a bit hit n miss", and besides you don't get to see the future trends from this as even on search term results, you'll get lots of people talking about why "old language" is better then "new trending language" and thus skew the results.

The 'Language Popularity' site did try to aggregate a load of language searches from various sites to give an overview, only they do explain which languages are popular on which sites and let you decide which makes sense, so for example, Google likes C, Yahoo likes C++ whereas Craigslist likes PHP. (site since defunct)

I think the best one is the jobs market - which languages show up most on job adverts is a fair indicator, along with the salary offered for them.

ContentLicense: CC BY-SA 4.0


问:
Can the Clojure set and maps syntax be added to other Lisp dialects?
In addition to create list using parentheses, Clojure allows to create vectors using [ ], maps using { } and sets using #{ }.

Lisp is always said to be a very extensible language in which you can easily create DSLs etc. But is Lisp so extensible that you can take any Lisp dialect and relatively easily add support for Clojure's vectors, maps and sets (which are all functions in Clojure)?

I'm not necessarily asking about cons or similar actually working on these functions: what I'd like to know is if the other could be modified so that the source code would look like Clojure's source code (that is: using matching [ ], { } and #{ } in addition to ( )).

Note that if it cannot be done this is not a criticism of Lisp: what I'd like to know is, technically, what should be done or what cannot be done if one were to add such a thing.

答:
Trivial answer:  yes, you can do this for any Lisp dialect by extending the implementation to provide more features.  (I don't think this is what you mean).

Practical answer:  no, you can't do this in "any Lisp dialect", although you can do it in some.  All Lisp implementations are different -- they have different strengths, weaknesses, and ways in which they can be extended.  Some may be opinionated, and not allow such syntax extensions when normal vector, map, and set functions along with parentheses could be used instead.  Others may not allow it because it's another feature, which needs to be designed, specced, implemented and tested -- all of which increases the workload on the implementors.

If you have a specific Lisp in mind, you should check whether that dialect allows such a thing, but I wouldn't expect any Lisp code more complicated than (+ 1 2) to be portable to all implementations.


问:
Sorting months with pre-defined order?
I want to sort the months of the year starting at any month, but January needs to show up after December if January isn't the starting point. Can I do that in an array or do I need a special data structure or algorithm to do that?</p>

答: you can easily do this with just an array. [Dec,Jan,Feb,...Oct,Nov] then you can iterate through with month mod 12 and it will produce a sorted list that can wrap around from Dec to Jan. You can simply stop iterating at January if you only want that month to wrap.

Title: Sorting months with pre-defined order?


问:
Can't understand example using continuations
I'm reading the r6rs Scheme report and am confused by the explanation of continuations (I find it to be too dense and lacking of examples for a beginner).

What is this code doing and how does it evaluate to 4?  Why does call/cc want an argument that's a function of one argument?  How is call/cc's argument used?

```<code>(+ 1 (call-with-current-continuation
       (lambda (escape)
         (+ 2 (escape 3)))))
          =⇒ 4
</code>```

This example is from section 1.11 - Continuations.

答:
call/cc takes a function with one argument, because that argument will be populated with the "current continuation". The continuation in this case will return to the point "just after" the call/cc, namely where its return value is being set.

Thus, when you call (escape 3), the rest of the expression (the (+ 2 ...)) is abandoned, and 3 is set as the return value of the call/cc. Thus, the (+ 1 (call/cc ...)) is now evaluated as (+ 1 3), hence the result is 4.


问:
Drawing out a document with strategies for coping with "disasters"
Does anyone happen to know of some guidelines for writing up a document for coping with possible disaster scenarios ? By disaster I mean anything that could lead to loss of work, time or eventually a client.

I seem to remember reading an article along these lines but, unfortunately, I can't find it anymore. So I'd appreciate some feedback in this direction.

I think such an approach would be useful in the company I'm in right now as we've had the occasional scare which might have been avoided with some preventative thinking.

答:
The method I'm most familiar with is Failure Mode and Effects Analysis.  It can be generalized to any system.

The point of it is to enumerate all the specific parts that can fail, how they can fail, and in each case what the result would be.  Then classify each item based on likelihood, severity, cost, etc.  Then you go ahead and create mitigation strategies.


答:
One of the things that we did when moving into a new building for our data center was to come up with a disaster recovery plan, and it was as simple as getting everyone together and just "what iffing", and then coming up with solutions for each event.

Things like "What if Larry gets hit by a car coming to work", "What if the primary and slave DB server for the local callouts die at the same time", etc.

Or even "What if the Qwest guy comes in and rewires 9 of our punchdown blocks because he thinks they look messy in the middle of a call cycle?" (Not that that has ever happened...)

Title: Drawing out a document with strategies for coping with "disasters"

Body:
Does anyone happen to know of some guidelines for writing up a document for coping with possible disaster scenarios ? By disaster I mean anything that could lead to loss of work, time or eventually a client.

I seem to remember reading an article along these lines but, unfortunately, I can't find it anymore. So I'd appreciate some feedback in this direction.

I think such an approach would be useful in the company I'm in right now as we've had the occasional scare which might have been avoided with some preventative thinking.


问:
Why #pragmas are not part of the C++ standard?
Usually the problem of having possible multiple inclusions is solved with a series of #ifdef #ifndef but the pragmas just solves this with a single line, apparently they are really useful and can make the code better in terms of readability.

Why they are not part of the C++ and C standards? there is a better way to avoid multiple inclusions?

答: Because it is precisely targeted at specific compiler implementation therefore to support things that would not be part of the standards. Some compilers may elect to support conveniences such as you describe in their own way while others may not support them at all and still be standards compliant.


问:
How to implement an email unsubscribe system for a site with many kinds of emails?
I'm working on a website that features many different types of emails. Users have accounts, and when logged in they have access to a setting page that they can use to customize what types of emails they receive.

However, I'd like to also give users an easy way to unsubscribe directly in the emails they receive.

I've looked into list unsubscribe headers as well as creating some type of one click link that would unsubscribe a user from that type of email without requiring login or further action. The later would probably require me to break convention and make changes to the database in response to a GET on the link.

However, am I incorrect in thinking that either of these would require me to generate and permanently store a unique identifier in my database for every email I ever send, really complicating email delivery? Without that, I'm not sure how I would be able to uniquely identify a user and a type of email in order to change their email preferences, and this identifier would need to be stored forever as a user could have an email sitting in their inbox for a long time before they decide to act on it.

Alternatively, I was considering having a no-login page for managing email preferences. In contrast to above where I would need one of these identifiers for each email, this would only need one identifier per user, with no generation or other action required on sending an email.

All of these raise security issues, and they could potentially be used by people to tamper with others' email preferences. This could be mitigated somewhat by ensuring that the identifier is really difficult to guess.

For the once per user identifier approach, I was considering generating the identifier by passing a user's ID through some type of encryption algorithm, is this a sound approach? For the per-email identifiers, perhaps I could use a user's ID appended to the time.

However, even this would not eliminate the problem entirely, as this would really just be security through obscurity, and anyone with the URL could tamper, and in the end the main defense would have to be that most people aren't so bored as to tamper with other people's email preferences.

Are there any other alternatives I've missed, or issues or solutions with these that anyone can provide insight on? What are best practices in this area?

Edit: Here is the alternative I missed for anyone coming across this later. The smart way to do this is to include in the unsubscribe link a cryptographic signature of the user to be unsubscribed and what they are to be unsubscribed from. Nothing at all needs to be stored in the database, while being on par with security with the solutions I'd been considering.

答:
Why would you need to store a unique identifier for each email you send? You just need a unique identifier for each user, as settings would surely be user-specific.

Typically, email subscription settings wouldn't be considered high-risk or high-security - after all, they can simply resubscribe if they want the email. I would encrypt the user's id (and maybe their email address or some other salt) to give each user a unique unsubscribe key that is added into a link in the footer of each email.

Storing a unique key per user in a database shouldn't concern you. Chances are if you have the resources to send mass mailings on a regular bases, you have the resources to store a 32 character key.


答: The very definition of #pragma is that they are non-Standard. Features which are provided as Standard are provided in some other way. Making #pragma Standard would defeat the purpose of, well, #pragma. They are nothing more than a set of implementation extensions, which happen to coincidentally be the same.

Title: Why #pragmas are not part of the C++ standard?

Body:
Usually the problem of having possible multiple inclusions is solved with a series of #ifdef #ifndef but the pragmas just solves this with a single line, apparently they are really useful and can make the code better in terms of readability.

Why they are not part of the C++ and C standards? there is a better way to avoid multiple inclusions?


答:
Be forewarned if you want to do disaster recover plans the right way they'll be more to it then you might imagine.

Put a budget to the making of that plan, both in man hours and in resources cost. Like are you planning to spend eight man hours writing your plan or 500 man hours. You might say '500 man hours!, no way!.' Powwowing with 10 employees to start and then talking about disaster at meetings add to man hours fast. If you are midsize or large company, then when managers take time to get info ready for you for the plan that you requested then that eats from the time budget also. All just for the writting a disaster recovery plan.

Some things to do for disaster; make an inventory and cost replacement of all your assets you need to make your clients happy. On items with warranties, guarantees, support contracts, licensing, make sure you have all manufacture, distributor, vendor contact info and current status of accounts with them. Think if a server drowns will you be able to replace that 10,000 dollar 10 year old server in a day? Will the vendor be happy to hear you want a replacement item right away (or is your account outstanding). You might say, oh I'll by a NEW machine off the shelf! Oh? will your old software WORK on that machine. Will a custom software app that needs a hardware key allow a new machine to run the custom app?

Have building evacuation plans, usually with walkie talkies assigned to personnel and their backup personnel.

For certain company types, for proper disaster recovery, make sure you've spoken with banks for emergency financing.

Check your medical plan support; ie 50% of staff is out from sickness cause by issue at building, like mold or dangerous fumes. Once I ran across 11% of staff out from getting very sick from DUCK POO (which had a nasty virus).

Have backup site for staff, have travel costs figured and budgeted to have staff go to backup site. Once one company planned their backup site to be just over one hour south of main site. WOW those mileage costs for employees (and sometimes travel time (hourly wage) costs for some staff) can add up in one week! Union people might have contracts for time traveled to offsite. Plan for people just not being able to travel to offsite and account for temps costs to replace them until main site is backup. You might ask "Who would do that?" Well pregnant employees for one as they may need to be near their doctor or hospital.

One odd disaster recovery thing is legal stuff. Like if your board of trustees gets charged for illegal stuff (like having a bunch of computers with illegally installed operating systems). When some company associates are unavailable for what ever reason certain authorities (read as signatures if you like) may become unaccessible.

The way you sell a disaster recovery plan to "those that want it" are:

First and foremost; Staff and client health protection (from disaster), such as evacuation procedures, call-chains/trees (ie who calls who, who is authorized to tell whom what), health issues of people

Second, financial and cash asset protections (ie info like access to your copyrights, patents, contracts (info), client account balances, lines of credit with financiers) without which recover from disaster is really hampered from lack of cash flow.

Certain "Information" assets fall between financial and asset categories.

Details on asset recovery of buildings, electronic equipment, paper assets like all those filing cabinets. (I bet a lot of companies decide to go paperless when they start on a disaster recovery plan)

There's more. But this post is long enough.


答:
Check this Java-ish code:</p>

```<code>public void sortMonths(int START) {
    // Jan = 0, ... , Dez = 11
    int[] myArray = new int[12];
    for (int i = START; i < 12; ++i) {
        myArray[i - START] = i;
    }

    for (int i = 0; i < START; ++i) {
        myArray[i] = i;
    }
}
</code>```

Title: Sorting months with pre-defined order?

Body: I want to sort the months of the year starting at any month, but January needs to show up after December if January isn't the starting point. Can I do that in an array or do I need a special data structure or algorithm to do that?</p>

Body:
Check this Java-ish code:

public void sortMonths(int START) {
    // Jan = 0, ... , Dez = 11
    int[] myArray = new int[12];
    for (int i = START; i < 12; ++i) {
        myArray[i - START] = i;
    }

    for (int i = 0; i < START; ++i) {
        myArray[i] = i;
    }
}


问:
Convention for writing Python without newlines or whitespace?
Is there a convention for writing Python when deprived of newlines and whitespace? For example, stackexchange comments, Twitter, text messages...</p>

答:
Is it possible in Python; mostly, you still need space characters.
Is it practical? not even remotely.

There is a practice similar to a bad form of functional programming that after trying it for a while you'll say "What a waste of time." However with this style, you still need to use indentation for it to work, unless you define your functions in an eval (or some other function) string like this eval('def myfunc(obj):\n\t# do stuff\n\treturn obj\n'). Shoot yourself now.

```<code>myobject = SomeClass()

def compile(obj): # use any function name
    # do stuff
    return obj

def parse(obj): # use any function name
    # do stuff
    return obj

def transpose(obj): # use any function name
    # do stuff
    return obj

# here is the nonwhite space thing you want
myobject=compile(myobject).parse(myobject).tanspose(myobject)
</code>```

You could have put each of those functions in a class as methods. I wanted to show that if you were to go the "I can't use newlines" things that each function call you do will have to return the object you gave it so you can chain your "operations" with a period instead of some other method.

If your functions/methods are small you could use lambdas. Something evil like:
myobject=(lambda obj:obj.add(5))(myobject).(lambda obj:obj.callfunc(func,(args))(myobject)

Know that these things are not Pythonic at the very core. And you might as well do them in another programming language. I've always felt Python's main asset is readability, caused by whitespaces and lack of extraneous non-alphnumeric characters like (){}[]:;# etc.

Body:
Is it possible in Python; mostly, you still need space characters.
Is it practical? not even remotely.

There is a practice similar to a bad form of functional programming that after trying it for a while you'll say "What a waste of time." However with this style, you still need to use indentation for it to work, unless you define your functions in an eval (or some other function) string like this eval('def myfunc(obj):\n\t# do stuff\n\treturn obj\n'). Shoot yourself now.

myobject = SomeClass()

def compile(obj): # use any function name
    # do stuff
    return obj

def parse(obj): # use any function name
    # do stuff
    return obj

def transpose(obj): # use any function name
    # do stuff
    return obj

# here is the nonwhite space thing you want
myobject=compile(myobject).parse(myobject).tanspose(myobject)

You could have put each of those functions in a class as methods. I wanted to show that if you were to go the "I can't use newlines" things that each function call you do will have to return the object you gave it so you can chain your "operations" with a period instead of some other method.

If your functions/methods are small you could use lambdas. Something evil like:
myobject=(lambda obj:obj.add(5))(myobject).(lambda obj:obj.callfunc(func,(args))(myobject)

Know that these things are not Pythonic at the very core. And you might as well do them in another programming language. I've always felt Python's main asset is readability, caused by whitespaces and lack of extraneous non-alphnumeric characters like (){}[]:;# etc.


问:
Best Architecture for ASP.NET WebForms Application
I have written an ASP.NET WebForms portal for a client.  The project has kind of evolved rather than being properly planned and structured from the beginning.  Consequently, all the code is mashed together within the same project and without any layers.  The client is now happy with the functionality, so I would like to refactor the code such that I will be confident about releasing the project.  As there seems to be many differing ways to design the architecture, I would like some opinions about the best approach to take.

FUNCTIONALITY

The portal allows administrators to configure HTML templates.   Other associated "partners" will be able to display these templates by adding IFrame code to their site.  Within these templates, customers can register and purchase products.  An API has been implemented using WCF allowing external companies to interface with the system also.  An Admin section allows Administrators to configure various functionality and view reports for each partner. The system sends out invoices and email notifications to customers.

CURRENT ARCHITECTURE

It is currently using EF4 to read/write to the database.  The EF objects are used directly within the aspx files.  This has facilitated rapid development while I have been writing the site but it is probably unacceptable to keep it like that as it is tightly coupling the db with the UI.  Specific business logic has been added to partial classes of the EF objects.

QUESTIONS

The goal of refactoring will be to make the site scalable, easily maintainable and secure.

What kind of architecture would be best for this?  Please describe what should be in each layer, whether I should use DTO's / POCO / Active Record pattern etc.

Is there a robust way to auto-generate DTO's / BOs so that any future enhancements will be simple to implement despite the extra layers?

Would it be beneficial to convert the project from WebForms to MVC?

答:
As ElYusubov mentioned, the MVP pattern can be great.

The key concept is stripping out most or all of your logic from the code-behind.  Logic should not be bound to a page.  What if you need to re-use the logic from one page in another?  You will be tempted to copy-and-paste.  If you're doing this then your project will become maintainable.

So, for starters begin refactoring your logic out of the code-behind and put it in a business layer.  If you managed to get all the logic out of the code-behind then you could implement the necessary interfaces to be a true MVP.

Also make sure your data access is separate from your business logic.  Create a data layer and begin refactoring on that end as well. Since you're using EF4 this is less of a problem as EF should already have this end separate.  You should be able to easily move all your EF files to another project and simply add a reference to the projects that need it.  The added benefit being, you may need to reference your data model in other projects.

To avoid being overwhelmed, refactor a little at a time.  Whenever you touch a piece of code consider refactoring the code around it.  If you do this, over time your project can become more maintainable.

Edit

You asked about having the code behind inherit a business logic class.  This can't be done because the code behind "is-a" page.  C# does not allow multiple inheritance, so the code-behind class cannot be both a page and a custom object.  You need to conceptually separate out the logic.  Its probably the case that the code in your code-behind is doing many different things.  A class should do one thing and one thing only.  Try and think about how you may conceptually pull out existing functionality. For example, lets say you have a registration page and you're collecting user information.  You probably have a button called register and a click event associated with that button.  In that event you are saving user information and doing whatever processing you need.  You could create a Registration object to handle all that logic.  In the code-behind instead of doing the logic yourself you can pass the information to the Registration object.

This not only a cleaner separation but it can also be a way to self document your code.  When someone reads your code they see you calling a Registration object so you know exactly what's going on.

If you wanted to strictly follow the MVP pattern, instead of passing the parameters to the Registration object the code-behind would implement an interface.  The implementation of the interface would essentially map all the view objects (text field etc) to the interface. e.g. public string FirstName { get{ return txtFirstName.Text; }}

Once that is done you could pass the page to the Regisration object

Registration.RegisterUser(this);

And this RegisterUser method would take the interface as a parameter

public bool RegisterUser(IUser user){ user.FirstName ...}

public interface IUser
{
    public string FirstName;
}

If this MVP sounds confusing, just focus on refactoring and know the point of all this is to maximize code-reuse.  There's no since in repeating yourself.  That's the DRY principal.


答:
Yes, they can be added. It is something you can do using reader macros.
There is already #(…) for vectors, but you can define your own [...] macro:

```<code>(set-macro-character #\] (get-macro-character #\)))
(set-macro-character #\[ (lambda (stream char)
                   (declare (ignore char))
                   `',(apply #'vector (read-delimited-list #\] stream t))))

CL-USER> [1 2 3]
#(1 2 3)
CL-USER> (aref [1 2 3] 0)
1
CL-USER>
</code>```

Look at closer-apl for more&cooler examples.

Title: Can the Clojure set and maps syntax be added to other Lisp dialects?

Body:
In addition to create list using parentheses, Clojure allows to create vectors using [ ], maps using { } and sets using #{ }.

Lisp is always said to be a very extensible language in which you can easily create DSLs etc. But is Lisp so extensible that you can take any Lisp dialect and relatively easily add support for Clojure's vectors, maps and sets (which are all functions in Clojure)?

I'm not necessarily asking about cons or similar actually working on these functions: what I'd like to know is if the other could be modified so that the source code would look like Clojure's source code (that is: using matching [ ], { } and #{ } in addition to ( )).

Note that if it cannot be done this is not a criticism of Lisp: what I'd like to know is, technically, what should be done or what cannot be done if one were to add such a thing.

Body:
Yes, they can be added. It is something you can do using reader macros.
There is already #(…) for vectors, but you can define your own [...] macro:

(set-macro-character #\] (get-macro-character #\)))
(set-macro-character #\[ (lambda (stream char)
                   (declare (ignore char))
                   `',(apply #'vector (read-delimited-list #\] stream t))))

CL-USER> [1 2 3]
#(1 2 3)
CL-USER> (aref [1 2 3] 0)
1
CL-USER>

Look at closer-apl for more&cooler examples.


问:
Selecting a JAX-RS implementation for a new project
I'm starting a new Java project which will require a RESTful API. It will be a SaaS business application serving mobile clients.

I have developed one project with Java EE 6, but I'm not very familiar with the ecosystem, since most of my experience is on the Microsoft platform.

Which would be a sensible choice for a JAX-RS implementation for a new project such as described?

Judging by Wikipedia's list, main contenders seem to be Jersey, Apache CXF, RESTeasy and Restlet. But the Comparison of JAX-RS Implementations cited on Wikipedia is from 2008.

My first impressings from their respective homepages is that:

CXF aims to be a very comprehensive solution (reminds me of WCF in the Microsoft space), which makes me think it can be more complex to understand, setup and debug than what I need;

Jersey is the reference implementation and might be a good choice, but it's legacy from Sun and I'm not sure how Oracle is treating it (announcements page doesn't work and last commit notice is from 4 months ago);

RESTeasy is from JBoss and probably a solid option, though I'm not sure about learning curve;

Restlet seems to be popular but has a lot of history, I'm not sure how up-to-date it is in the Java EE 6 world or if it carries a heavy J2EE mindset (like lots of XML configuration).

What would be the merits of each of these alternatives? What about learning curve? Feature support? Tooling (e.g. NetBeans or Eclipse wizards)? What about ease of debugging and also deployment? Is any of these project more up-to-date than the others? How stable are them?

答:
You can take a look at this question, which discusses some experiences from other developers. </p>

<p>I can personally recommend Jersey. It's very easy to use, and it has a good following because it's the reference implementation. This also means that it'll be maintained and supported for the next little while. </p>

Body:
You can take a look at this question, which discusses some experiences from other developers.

I can personally recommend Jersey. It's very easy to use, and it has a good following because it's the reference implementation. This also means that it'll be maintained and supported for the next little while.


问:
Keep coding the wrong way to remain consistent?

Possible Duplicate:

  Code maintenance: keeping a bad pattern when extending new code for being consistent, or not?

To keep things simple let's say I am responsible for maintaining two applications, AwesomeApp and BadApp (I am responsible for more and no that is not their actual names).

AwesomeApp is a greenfield project I have been working on with other members on my team.  It was coded using all the fancy buzzwords, Multilayer, SOA, SOLID, TDD, and so on.  It represents the direction we want to go as a team.

BadApp is a application that has been around for a long time.  The architecture suffers from many sins, namely everything is tightly coupled together and it is not uncommon to get a circular dependency error from the compiler, it is almost impossible to unit test, large classes, duplicate code, and so on.  We have a plan to rewrite the application following the standards established by AwesomeApp, but that won't happen for a while.

I have to go into BadApp and fix a bug, but after spending months coding what I consider correctly, I really don't want do continue perpetuate bad coding practices.  However, the way AwesomeApp is coded is vastly different from the way BadApp is coded.  I fear implementing the "correct" way would cause confusion for other developers who have to maintain the application.

Question: Is it better to keep coding the wrong way to remain consistent with the rest of the code in the application (knowing it will be replaced) or is it better to code the right way with an understanding it could cause confusion because it is so much different?

To give you an example.  There is a large class (1000+ lines) with several functions.  One of the functions is to calculate a date based on an enumerated value.  Currently the function handles all the various calculations.  The function relies on no other functionality within the class.  It is self contained.  I want to break the function into smaller functions (at the very least) and put them into their own classes and hide those classes behind an interface (at the most) and use the factory pattern to instantiate the date classes.  If I just broke it out into smaller functions within the class it would follow the existing coding standard.  The extra steps are to start following some of the SOLID principles.

答:
Consistency is worth less than quality every time. If your other developers on BadApp don't know how to code well, train them or fire them.

Or, if your boss won't consider those two alternatives, call your headhunter.

Edit: Twas my impression that you were suggesting that the other developers working on BadApp would have a problem with good code. If not, then, well, there's really no reason not to start coding well. Consistency is only valuable if you're consistent with something worth being.


答:
If I was in your place I'd either suggest to the team to concentrate on refactoring the code, or at least have someone only assigned to refactor the code.
It should be pretty obvious that it will pay off in the long run.

Don't ever feel ashamed to fix broken code!

Title: Keep coding the wrong way to remain consistent?

Body:
Possible Duplicate:

  Code maintenance: keeping a bad pattern when extending new code for being consistent, or not?

To keep things simple let's say I am responsible for maintaining two applications, AwesomeApp and BadApp (I am responsible for more and no that is not their actual names).

AwesomeApp is a greenfield project I have been working on with other members on my team.  It was coded using all the fancy buzzwords, Multilayer, SOA, SOLID, TDD, and so on.  It represents the direction we want to go as a team.

BadApp is a application that has been around for a long time.  The architecture suffers from many sins, namely everything is tightly coupled together and it is not uncommon to get a circular dependency error from the compiler, it is almost impossible to unit test, large classes, duplicate code, and so on.  We have a plan to rewrite the application following the standards established by AwesomeApp, but that won't happen for a while.

I have to go into BadApp and fix a bug, but after spending months coding what I consider correctly, I really don't want do continue perpetuate bad coding practices.  However, the way AwesomeApp is coded is vastly different from the way BadApp is coded.  I fear implementing the "correct" way would cause confusion for other developers who have to maintain the application.

Question: Is it better to keep coding the wrong way to remain consistent with the rest of the code in the application (knowing it will be replaced) or is it better to code the right way with an understanding it could cause confusion because it is so much different?

To give you an example.  There is a large class (1000+ lines) with several functions.  One of the functions is to calculate a date based on an enumerated value.  Currently the function handles all the various calculations.  The function relies on no other functionality within the class.  It is self contained.  I want to break the function into smaller functions (at the very least) and put them into their own classes and hide those classes behind an interface (at the most) and use the factory pattern to instantiate the date classes.  If I just broke it out into smaller functions within the class it would follow the existing coding standard.  The extra steps are to start following some of the SOLID principles.


答: Many sorters let you provide your own comparator which dictates the sort order.  Write one that implements your rules and and supply it to the sort function.</p>

Title: Sorting months with pre-defined order?


答:
What it may come down to is a cost analysis on BadApp, to see if it is worth going in and updating the code to better standards, or whether just flat out rewriting the application is better. Or, there may be off the shelf solutions out there to do part of the functions of BadApp, and rewrite/update the rest.

One approach might be to have a developer or two go through the code in BadApp, and outline what needs to be changed/updated (This could be part of or a result of the cost analysis). You keep that list, and then anytime you need to go into BadApp, you also take one of the rewrite functions and complete that. It extends the timeframe for updating BadApp to standard, but it will eventually be at least MediocreApp.


答:
Python allows you to use semicolons to separate statements. As for control structure, that's a bit more difficult. Some projects use the pass keyword (a no-op) to indicate the end of a block:

```<code>if foo==1:foo=2;pass;  if foo==3:foo=4;pass;
</code>```

It's not particularly readable though, and the interpreter will just mock you if you try it for real, so it's not really a general solution.

Title: Convention for writing Python without newlines or whitespace?

Body: Is there a convention for writing Python when deprived of newlines and whitespace? For example, stackexchange comments, Twitter, text messages...</p>

Body:
Python allows you to use semicolons to separate statements. As for control structure, that's a bit more difficult. Some projects use the pass keyword (a no-op) to indicate the end of a block:

if foo==1:foo=2;pass;  if foo==3:foo=4;pass;

It's not particularly readable though, and the interpreter will just mock you if you try it for real, so it's not really a general solution.


答:
I would think your danger in "fixing" BadApp as you maintain is that it will suck up time and effort better spend on GoodApp until it's time for BadApp V2.0.

I would:

Have a team meeting and enumerate the differences between the two.  That helps everyone (including any "old schoolers" to buy into what's good.

Acknowledge that you will leave some of the old stuff (if it's working) as is and leave breadcrumbs for yourself on what needs to be fixed.  You can use your ticket system or even extended "TODO" type comments in the code.  After time these accumulate and the migration is less buggy.

When the rewirte of BadApp does come, management will commit the proper resources based on what you identified above...LOL I just want to type that, could not have said it with a straight face :-)


答:
Refactoring code all the time isn't always good and productive. I had a colleague who is a brilliant programmer but he never managed to finish the app he was working on. With every new bug he saw many faults in the program and tried to change some structure to fix the bug. He was fired eventually.

If there are any changes that will take smth like 30-40 percent more time than you need just to fix the bug, than I'd say you change the code. By the time you and your team find time/person to completely refactor the code, it will be much easier because a lot is already done. If you are adding new piece of code to that app, than add it properly. Don't be afraid that someone won't understand it.

But if with every bug you'll try to rewrite a big piece of code, you'll get nowhere. It's better either to do small changes and wait for the BIG refactoring, or not to touch the old nasty but working code.


问:
Best way to reuse common functions between ASPX pages ?
I have a bunch of functions that are used across multiple ASPX files. I want to condense these down to one file to be used for all the ASPX files. I have a few ideas but I want to know what the accepted method to doing this would be. I have an idea to just create a class to put them in.

However, I was wondering if i could put them in a ascx page, but that does not look like the solution I'm looking for.

Is there a accepted method for this type of situation?

答:
Sure it can be done by creating a library in the project, and referencing the namespace in your aspx files.

```<code><%@ Import Namespace="sharedfunctionlibrarynamespace" %>
</code>```

I also found a similar post - Reusing same functions in different .aspx files/making function library

As you have also mentioned, another approach is to create a base class from which all of your page classes will derive. That will work as well.

Body:
Sure it can be done by creating a library in the project, and referencing the namespace in your aspx files.

<%@ Import Namespace="sharedfunctionlibrarynamespace" %>

I also found a similar post - Reusing same functions in different .aspx files/making function library

As you have also mentioned, another approach is to create a base class from which all of your page classes will derive. That will work as well.


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

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

答: I wish I could make Lust and Gluttony helpful but Sloth, Pride and Envy are certainly great for programmers." ~ Kenneth Clowes</p>


答:
What you're looking for is material about risk management. The general idea of risk management is to first identify the risk, determine what aspects of the project will be affected should it materialize, assess the likelihood of the risk materializing and what impact it would have to different aspects of the project, and identify methods to detect when the risk is beginning to materialize and what action(s) should be taken to counteract the risks.

The methods for dealing with risks is generally captured in a risk management plan. Risk matrices and risk registers capture information pertenent to risk management.

Managing risks is generally considered a project management topic. Hopefully the links to those particular Wikipedia articles might help provide a high level overview, and some links to additional resources. You might also be interested in the Project Management Stack Exchange, especially the questions tagged risk management and risk.


问:
How can I learn to effectively write Pythonic code?
Doing a google search for "pythonic" reveals a wide range of interpretations.  The wikipedia page says:

A common neologism in the Python community is pythonic, which can have a wide range of meanings related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is natural or shows fluency in the language. Likewise, to say of an interface or language feature that it is pythonic is to say that it works well with Python idioms, that its use meshes well with the rest of the language.

It also discusses the term "unpythonic":

In contrast, a mark of unpythonic code is that it attempts to write C++ (or Lisp, Perl, or Java) code in Python—that is, provides a rough transcription rather than an idiomatic translation of forms from another language. The concept of pythonicity is tightly bound to Python's minimalist philosophy of readability and avoiding the "there's more than one way to do it" approach. Unreadable code or incomprehensible idioms are unpythonic.

What does the term "pythonic" mean?  How do I learn to effectively apply it in practice?

答:
Someone said to paraphrase, to learn what is Pythonic, just bash out some code. I disagree with that. If you like writting highly dense code, that doesn't make it more Pythonic.

One way to help you define what is Pythonic as far as yourself is concerned, ask your self "Why would I(meaning you) use the Python language?" What appeals to you about it?

For me it is readability and lack of compiling and open source (pretty much all of it). I can down load tons of libraries and read thier source code with less stress about licensing then many other languages.

To me Python is beautiful visually. Guido (the creator of Python) also keeps proving to me, through his replies in PEPS and discussions) that his choices for how he made the language are superior to my own ideas of how it should have been created.

To me, a great programmer is someone with very informed decision making skills about which way to go when coding. To me, Python aids with making those choices quickly.

By simplifing the source code syntax by allowing duck typing instead of explicid type casting, and the expectation that coders reviewing your code "should be well behaved coders" leads to something I too call "Pythonic"

So there are two sides of what is Pythonic. One is syntactical, the other is the practice of. How to explain the deeper side of what is "Pythonic"..?

In Python it is no big deal to do this:
alist = ['one','two','three\n']
alist.append( (1234, 'Atuple') )

and the tuple will be added to the list without any concern for object types.
The Pythonic part is not that you CAN do this, but that your code should EXPECT this and just work/adapt.

Whatever works on the -alist- object should be written with the idea that some other coder could come in and add a non-string to the list and that the source code adaptation by the new coder should not be difficult to do. That's the benefit of ducktype after all.


问:
How should I write new code when the old codebase and the environment uses lots of globals in PHP
I'm working in the Wordpress environment which itself heavily relies on globals and the codebase I'm maintaining introduces some more. I want this to change and so I'm trying to think how should I handle this.

For the globals our code has introduced I think I will set them as dependencies in the constructor or in getter / setter so that I don't rely on them being globals and then refactor the old codebase little by little so that we have no globals.

With Wordpress globals I was thinking to wrap all WP globals inside a Wrapper class and hide them in there. Like this

```<code>class WpGlobals {
    public static function getDb() {
        global $wpdb;
        return $wpdb;
    }
}
</code>```

Would this be of any help? The idea is that I centralize all globals in one class and do not scatter them through the code, so that if Wordpress kills one of them I need to modify code only in one place.

What would you do?

答:
I recently started working on a Wordpress project. We wrap all calls to Wordpress functions into a wrapper class. This makes it easy to unit test our code. </p>

<p>I have a function that returns the db connection like you do. This way I can mock it. </p>

Body:
I recently started working on a Wordpress project. We wrap all calls to Wordpress functions into a wrapper class. This makes it easy to unit test our code.

I have a function that returns the db connection like you do. This way I can mock it.


问:
Is this a decent use-case for goto in C?
I really hesitate to ask this, because I don't want to "solicit debate, arguments, polling, or extended discussion" but I'm new to C and want to gain more insight into common patterns used in the language.

I recently heard some distaste for the goto command, but I've also recently found a decent use-case for it.

Code like this:

```<code>error = function_that_could_fail_1();
if (!error) {
    error = function_that_could_fail_2();
    if (!error) {
        error = function_that_could_fail_3();
        ...to the n-th tab level!
    } else {
        // deal with error, clean up, and return error code
    }
} else {
    // deal with error, clean up, and return error code
}
</code>```

If the clean-up part is all very similar, could be written a little prettier (my opinion?) like this:

```<code>error = function_that_could_fail_1();
if(error) {
    goto cleanup;
}
error = function_that_could_fail_2();
if(error) {
    goto cleanup;
}
error = function_that_could_fail_3();
if(error) {
    goto cleanup;
}
...
cleanup:
// deal with error if it exists, clean up
// return error code
</code>```

Is this a common or acceptable use-case of goto in C? Is there a different/better way to do this?

答:
There will always be camps that say one way is acceptable and another that is not. Companies I've worked for have frowned or strongly discouraged goto use. Personally, I can't think of any time I've used one, but that doesn't mean they are bad, just another way of doing things.

In C, I typically do the following:

Test for conditions that could prevent processing (bad inputs, etc) and "return"

Do all steps that require resource allocation (e.g. mallocs)

Perform the processing, where multiple steps check for success

Release any resources, if successfully allocated

Return any results

For the processing, using your goto example, I'd do this:

error = function_that_could_fail_1();
if(!error) {
    error = function_that_could_fail_2();
}
if(!error) {
    error = function_that_could_fail_3();
}

There no nesting, and inside the if clauses, you can do any error reporting, if the step generated an error. So, it doesn't have to be "worse" than a method using gotos.

I have yet to run across a case where someone has gotos that can't be done with another method and is just as readable/understandable and that is the key, IMHO.


问:
Can I use publicly mentioned algorithms for writing programs?
I want to write a program that solves sudoku.  </p>

<p>So, I found some sudoku algorithms on Wikipedia.
Can I use them or do I need to develop my own algorithm?
Also, do I need to ask the specific license holder's permission?.. If so, how would I go about obtaining that permission? </p>

答:
You always should honour the licence. It is not probable that someone will find out, but its the ethical way to do things. If there is no license displayed, you should at least try to contact the author using guestbook or email. Big sites like wiki etc. have these issues taken care of in some global portal content licenses.

In case someone is still interested in code available under some permissive licence, I offer mine (currently under MIT license):

Sudoku - Algoritmy.net


答:
The general idea about software, algorithms and implementation details is:

the more you produce something that is abstract and without significant details, like an mathematical algorithm, the less you are likely to have the right to patent that

the more you can produce a detailed implementation the higher the chances are that you can protect your intellectual property with a patent.

For example if you know about JPEG, it's a general file container for bitmap images, its standard says nothing clear about any implementation details, if you just follow the JPEG standard you can't write useful code because it's too generic and does not gives you the implementation details that you need to read or write from an actual JPEG file.

However this kind of things is possible http://www.google.com/patents/US6724939 because it's 1 specific way of implementing this algorithm.

You can find some extra examples here http://en.wikipedia.org/wiki/Patentable_subject_matter

Remember that patenting means that a person registers that intellectual property, it's not about selling and paying for something, in fact you can just choose to patent something and not asking for royalty even if peoples uses that, you can patent something and prohibit the use of that technology without giving licenses, you can patent something and choose to sell licenses to use that technology.

If you find code with an "unknow source" your best chance is to change at least a little piece of code, rearrange the text or something like that.

Title: Can I use publicly mentioned algorithms for writing programs?

Body:
I want to write a program that solves sudoku.  </p>

<p>So, I found some sudoku algorithms on Wikipedia.
Can I use them or do I need to develop my own algorithm?
Also, do I need to ask the specific license holder's permission?.. If so, how would I go about obtaining that permission? </p>


问:
I've inherited 200K lines of spaghetti code -- what now?
I hope this isn't too general of a question; I could really use some seasoned advice.

I am newly employed as the sole "SW Engineer" in a fairly small shop of scientists who have spent the last 10-20 years cobbling together a vast code base. (It was written in a virtually obsolete language: G2 -- think Pascal with graphics). The program itself is a physical model of a complex chemical processing plant; the team that wrote it have incredibly deep domain knowledge but little or no formal training in programming fundamentals. They've recently learned some hard lessons about the consequences of non-existant configuration management. Their maintenance efforts are also greatly hampered by the vast accumulation of undocumented "sludge" in the code itself. I will spare you the "politics" of the situation (there's always politics!), but suffice to say, there is not a consensus of opinion about what is needed for the path ahead.

They have asked me to begin presenting to the team some of the principles of modern software development. They want me to introduce some of the industry-standard practices and strategies regarding coding conventions, lifecycle management, high-level design patterns, and source control. Frankly, it's a fairly daunting task and I'm not sure where to begin.

Initially, I'm inclined to tutor them in some of the central concepts of The Pragmatic Programmer, or Fowler's Refactoring ("Code Smells", etc). I also hope to introduce a number of Agile methodologies. But ultimately, to be effective, I think I'm going to need to hone in on 5-7 core fundamentals; in other words, what are the most important principles or practices that they can realistically start implementing that will give them the most "bang for the buck".

So that's my question: What would you include in your list of the most effective strategies to help straighten out the spaghetti (and prevent it in the future)?

答:
When I have to work with spaghetti code, the first thing I work on is modularization.  Find places where you can draw lines and extract (more or less) independent pieces of the codebase.  They probably won't be very small, due to a high degree of interconnectedness and coupling, but some module lines will emerge if you look for them.

Once you have modules, then you're not faced with the daunting task of cleaning up an entire messy program anymore. Now, instead, you have several smaller independent messy modules to clean up.  Now pick a module and repeat on a smaller scale.  Find places where you can extract big functions into smaller functions or even classes (if G2 supports them).

This is all a lot easier if the language has a sufficiently strong type system, because you can get the compiler to do a lot of the heavy lifting for you.  You make a change somewhere that will (intentionally) break compatibility, then try to compile.  The compile errors will lead you directly to the places that need to be changed, and when you stop getting them, you've found everything.  Then run the program and test everything!  Continuous testing is crucially important when refactoring.


答:
The very first step would be introduction of a Version Control System (SVN, Git, Mercurial, TFS, etc.). This is must to have for a project that will have re-factoring.

Edit: regarding VSC - Every source control package can manage binaries, although with some limitations. Most of the tools in the market has the ability to use a custom difference viewer and editor, use this capability. Binary source files is not an excuse not to use version control.

There is a similar post on how to deal with legacy code, it might be a good reference to follow - Advice on working with legacy code

Title: I've inherited 200K lines of spaghetti code -- what now?

Body:
I hope this isn't too general of a question; I could really use some seasoned advice.

I am newly employed as the sole "SW Engineer" in a fairly small shop of scientists who have spent the last 10-20 years cobbling together a vast code base. (It was written in a virtually obsolete language: G2 -- think Pascal with graphics). The program itself is a physical model of a complex chemical processing plant; the team that wrote it have incredibly deep domain knowledge but little or no formal training in programming fundamentals. They've recently learned some hard lessons about the consequences of non-existant configuration management. Their maintenance efforts are also greatly hampered by the vast accumulation of undocumented "sludge" in the code itself. I will spare you the "politics" of the situation (there's always politics!), but suffice to say, there is not a consensus of opinion about what is needed for the path ahead.

They have asked me to begin presenting to the team some of the principles of modern software development. They want me to introduce some of the industry-standard practices and strategies regarding coding conventions, lifecycle management, high-level design patterns, and source control. Frankly, it's a fairly daunting task and I'm not sure where to begin.

Initially, I'm inclined to tutor them in some of the central concepts of The Pragmatic Programmer, or Fowler's Refactoring ("Code Smells", etc). I also hope to introduce a number of Agile methodologies. But ultimately, to be effective, I think I'm going to need to hone in on 5-7 core fundamentals; in other words, what are the most important principles or practices that they can realistically start implementing that will give them the most "bang for the buck".

So that's my question: What would you include in your list of the most effective strategies to help straighten out the spaghetti (and prevent it in the future)?


答: Yes plus enough filler to make this answer long enough as long as you comply with the declared license. </p>


答:
They say that the first step in solving a problem is admitting that you have one. With that in mind, you might start by generating a dependency graph that illustrates the vast tangle that is your current code base. Good tool to generate dependency diagram? is a few years old but contains some pointers to tools that can help create such graphs. I'd go with one great big, ugly graph that shows as much as possible to drive the point home. Talk about problems that result from too many interdependencies and maybe throw in a line from Buckaroo Banzai:

You can check your anatomy all you want, and even though there may be
  normal variation, when it comes right down to it, this far inside the
  head it all looks the same. No, no, no, don't tug on that. You never
  know what it might be attached to.

From there, introduce a plan to start to straighten out the mess. Break the code into modules that are as self-contained as possible. Be open to suggestions as to how to do that -- the folks you're talking to know the history and the functionality of the code better than you do. The goal, however, is to take one big problem and turn it into some number of smaller problems which you can then prioritize and start to clean up.

Some things to focus on:

Create clean interfaces between modules and start to use them. Old code may, of necessity, continue to not use those nice new interfaces for a while -- that's the problem you're starting to solve. But get everybody to agree to use only the new interfaces going forward. If there's something they need that's not in the interfaces, fix the interfaces, don't go around them.

Look for cases where the same functionality has been repeated. Work toward unification.

Remind everybody from time to time that these changes are meant to make life easier, not more difficult. Transition can be painful, but it's for a good purpose, and the more everybody is on board the faster the benefits will come.


问:
What are the typical applications of Lisp macros?
I am trying to learn some LISP and I have read a lot about the importance of LISP macros so I would like to get some working experience with them.

Can you suggest a practical application area that would allow me to use macros to solve a real-world problem, and to understand the usefulness of this programming construct?

NOTE

This is not a generic what project should I do next question. I am interested to understand which kinds of problems are typically solved by means of LISP macros. E.g., are they good for implementing abstract data types?
Why was this construct added to the language? What kinds of problems does it solve that cannot be solved by means of simple functions?

答:
Lisp macros combine a few distinct properties:

Macros define new syntax ↔ they use source-code as input

Macros usually are run at compile-time

Macros generate source-code

The best applications make use of all of those aspects. Probably the most-well known example is the (loop …) in Common Lisp, it wouldn't be anywhere close to its usefulness without one of those features. Without the source as input it would be awkward to define the actions inside the loop; without compile-time expansion it would be way too slow; and without code-generation it wouldn't be executable.

Another fine example is the binary serialization chapter in Practical Common Lisp,  Practical: Parsing Binary Files.

A query macro that implements something similar to LINQ might be another good application. But it would be missing the auto-completion that makes LINQ as nice as it is. Almost anything that today is solved by special purpose code-generators with XML inputs (e.g. XAML) could also be implemented using Lisp macros.