问:
Is obscuring/obfuscating public-facing database ids really a "best practice"?
I've heard people lecture here and there on the internet that it's best practice to obscure public facing database ids in web applications. I suppose they mainly mean in forms and in urls, but I've never read anything more than a mouthful on the subject.

EDIT: Of course, now that I ask this, I find some resources on the subject:

https://stackoverflow.com/questions/2374538/obscuring-database-ids

https://stackoverflow.com/questions/1895685/should-i-obscure-primary-key-values

http://joshua.schachter.org/2007/01/autoincrement.html

These links satisfied some of my curiosity, but the SO posts don't have many votes and aren't necessarily centered around the topic in this context so I'm not sure what to make of it, and some of them claim that the third link is bogus. I'll leave the rest of my post intact:

I understand the differences between obscurity and security, as well as how the two can work together, but I can't imagine why this would be necessary.

Is there any truth to this, is it just paranoia, or is it just totally bogus altogether?

I can think of ways to do it, but of course it adds a lot of complexity to the application code. Under what circumstances would this be useful? If this is something people frequently do, how is it usually deployed? Hashing the identifiers? Something else? It seems like a lot of work for not much extra security. I'm not looking for real solutions, I just want to get an idea of how/why people would do this in the real world.

Is this really considered a "best practice" or is it merely a micro-optimization of little value?

NOTE: I think a few folks might have gotten the wrong idea: I'm not suggesting that difficult-to-guess ids would be the only security mechanism, obviously there would have be the usual access checks. Let's assume those are in place, and that simply knowing the id or hashed id of a record is not enough to grant access.

答:
I don't think it's that important, but there are some scenarios when it could matter depending on other decisions you make.

For example, if you were to expose an order ID that's generated sequentially, and you had a social engineering attack with someone calling customer support and saying "hey, I just spent $2000 on a new computer and you guys sent me some other guy's order for a $15 cable, now I'm out $2000" you could spend a lot of time trying to vet the issue before you either conclude it's bogus or you send the faker a new computer.

There are similar, less sophisticated, but embarrassing variations on the theme; if a bad guy increments an order ID an emailed link to a receipt, and if no additional validations are made to verify that the person who clicked on the link has the right to view the order ID, suddenly you're unwittingly exposing private customer information to the wrong person.

In such cases, if the numbers are non-sequential the exposure is slightly mitigated because guessing is less likely to yield interesting results. On the other hand, now you need a convenient way to reference an order ID in customer support interactions that won't result in long back-and-forth conversations with telephone-based customer interactions while your rep tries to distinguish between B, P D and T in order number BPT2015D.

I'd say it's a stretch to call this obfuscation a "best practice", but in certain scenarios, it can reduce the ease of exploiting another weakness in your validation or authorization code. On the other hand, it doesn't really matter whether someone knows you wrote blog post #1 or #2559. If the ID isn't valuable information, even with additional knowledge, then the argument that obfuscating it is a best practice holds less weight.

There's a second potential argument, which is that your database identifier may wed you to a particular database implementation (or instance), and when your company gets bought out or picks up a competitor and now you have to merge two legacy systems, or the CEO goes out drinking with the rep from DynoCoreBase and they decide that you will now move all your data to DynoCoreBase version 13h and it wants all the primary keys to be guids, and you have to create some sort of mapping layer to translate old IDs to new IDs so that old URLs don't break, but whether these scenarios matter to you depend far more on the nature of your business (and the customer involvement with those IDs) than on any general best practice.


问:
Changing from VB.NET to C#?
I am working on co-op at a company as a test engineering specialist.  This is not technically a software job, however at the end of the day, I spend most of my time programming.

I am not a programming wiz by any means, but I am very comfortable using VB.NET since that is what projects started at my company previous to my time were written in, and so it is what I have learned and used in the position.

I have gotten the feeling from my time searching for help online when I need it that there is generally more and better support for C# than there is for VB.NET.  This has led me to thinking that it may be beneficial for the company going forward to start programming less in VB.NET and more in C#.

However, almost all projects in my department (since several other people work on small programming projects) are currently written in VB.NET.  Additionally, most of the software design done in our department is relatively simple I would imagine relative to a software focused area of any company. Probably half of it is generating html pages with graphs to visually illustrate certain data.  Taking these two facts into account, there are obvious disadvantages to trying to switch the main programming language used.  Also, the vb.net language is very similar to VBA (for excel) and VBScript, which are also used quite a bit in my area of the company.

I am basically not sure if it would be worth the work to change the main language used since there is not a lot of complicated programming done, and similar languages are necessary anyways it seems.

I was curious what additional insight experienced programmers may be able to offer me regarding changing the main language used in my area from VB.NET to C#?  What benefits or disadvantages are there that I may not have thought of?  How big a role do each advantage and disadvantage play?

What is your overall opinion on the idea of changing from VB.NET to C#?

答:
I was curious what additional insight experienced programmers may be
  able to offer me regarding changing the main language used in my area
  from VB.NET to C#?

In the company I worked for, we used to work on projects having VB and C# code bases simultaneously. But then there was a gradual shift to C# due to the comfort my team mates felt using C# syntax structure. This was because we had more exposure to C# syntax by learning C, C++ and Java during graduation. We did not make any effort to change the existing VB.Net applications as we were reinventing the wheel.

So the key here is that, the prior experience that a developer holds far outweighs the small differences between the two languages.

What benefits or disadvantages are there that I may not have thought
  of? How big a role do each advantage and disadvantage play?

Although C# and VB differ in a very small level, everything eventually gets compiled into the IL and that is the reason NET Framework is language independent.

That said, there are no disadvantages in using either languages.

Good luck!

ContentLicense: CC BY-SA 3.0

Title: Changing from VB.NET to C#?


问:
What is happening to PHP 6?
I am excited about the changes in PHP 6 previewed in PHP 5.3+. However, I wonder why it takes so long to release PHP 6? Books about it have been published since 2008, and announcements on it since 2007, but I am yet to hear about an alpha or a beta. Why does it take so long to release it? Or is that the way it goes with all languages when they transition to a major release where I guess it takes around 4-5 years to release?</p>

答:
I don't think there's any demand for PHP 6. I mean, what do you expect 6 to have that doesn't already exist? True unicode support is all I can think of, and that doesn't even impact me at the moment.

Also there's been new features added recently, like namespaces and the phar packaging system that need some time to soak in. You don't want to throw even more features at the community before they've adopted the old features.

Finally the industry as a whole has been slow to adopt new versions of PHP. There are still applications being written that target 4.3. The industry and community need to catch up before PHP goes much further.

ContentLicense: CC BY-SA 2.5

Title: What is happening to PHP 6?


答:
The word "Obscure" is probably slightly misleading here, and, may lead people to think "obfuscate" or "partially hide".

The recommendation is that you never ever include any internally generated database keys as part of a public URL if these database records contain any sensitive data.

Its just too easy to play with the numbers in the URL and access other records.

Title: Is obscuring/obfuscating public-facing database ids really a "best practice"?

Body:
I've heard people lecture here and there on the internet that it's best practice to obscure public facing database ids in web applications. I suppose they mainly mean in forms and in urls, but I've never read anything more than a mouthful on the subject.

EDIT: Of course, now that I ask this, I find some resources on the subject:

https://stackoverflow.com/questions/2374538/obscuring-database-ids

https://stackoverflow.com/questions/1895685/should-i-obscure-primary-key-values

http://joshua.schachter.org/2007/01/autoincrement.html

These links satisfied some of my curiosity, but the SO posts don't have many votes and aren't necessarily centered around the topic in this context so I'm not sure what to make of it, and some of them claim that the third link is bogus. I'll leave the rest of my post intact:

I understand the differences between obscurity and security, as well as how the two can work together, but I can't imagine why this would be necessary.

Is there any truth to this, is it just paranoia, or is it just totally bogus altogether?

I can think of ways to do it, but of course it adds a lot of complexity to the application code. Under what circumstances would this be useful? If this is something people frequently do, how is it usually deployed? Hashing the identifiers? Something else? It seems like a lot of work for not much extra security. I'm not looking for real solutions, I just want to get an idea of how/why people would do this in the real world.

Is this really considered a "best practice" or is it merely a micro-optimization of little value?

NOTE: I think a few folks might have gotten the wrong idea: I'm not suggesting that difficult-to-guess ids would be the only security mechanism, obviously there would have be the usual access checks. Let's assume those are in place, and that simply knowing the id or hashed id of a record is not enough to grant access.


问:
How do I review my own code?
I'm working on a project solo and have to maintain my own code. Usually code review is done not by the code author, so the reviewer can look at the code with the fresh eyes — however, I don't have such luxury. What practices can I employ to more effectively review my own code?</p>

答:
It seems the common sentiment is that self-review is not effective. I disagree, and I think self-review can catch a lot of issues if done thoroughly.

Here are tips from my few years of experience:

Have a rough checklist handy. These are things you want to flag while you read your code.

Take your code review offline. It might sound wasteful, but take printouts that you can annotate and flip back-and-forth, or the digital equivalent of nicely highlighted pdfs synced to an iPad which is then taken offline. Go away from your desk, so that all you do is review your code distraction-free.

Do it early in the morning, rather than the end of a working day. Fresh pair of eyes is better. In fact, it might help to have been away from the code a day before reviewing it afresh.

Just an FYI - these guidelines were part of recommendations in Oracle a few years ago when I was working there, where the aim was to catch bugs "upstream" before the code went into testing. It helped a lot, although it was considered boring job by a lot of developers.

Title: How do I review my own code?


答:
Most of the people tend to consider their code as their own babies and feed them with ego to rather than reality. Just like any other code reviews, review it as you're seeing someone else's code. Completely forget that you've wrote something. Review each line of the code. A check list would helpful for being aesthetics about reviewing own code. Automated tools for code review can help to some extend. I have used some tools like klocwork (commercial software), This is quite useful while you're working in large projects and several developers are working for it. Always focus on defect detection rather than correction.

But a best practice would be, review yourself and later involve at least two other people for review with distinguished roles.

Title: How do I review my own code?

Body: I'm working on a project solo and have to maintain my own code. Usually code review is done not by the code author, so the reviewer can look at the code with the fresh eyes — however, I don't have such luxury. What practices can I employ to more effectively review my own code?</p>


答:
There are two aspects to this: usability and security.

Security-wise, obscuring IDs is rather pointless; what's important is that the ID must never be the only 'key' to any non-public resource. This means that if you want to give selected users access to a certain page, just requiring the page's ID in the URL is not enough, you have to implement an actual security mechanism such as a username/password login or public/private key authentication, as well as proper authorization (that is, the system must be able to judge on a per-case basis whether user X is allowed to access resource Y, and act accordingly).

Usability-wise, the general advice is to keep artificial keys hidden: they don't have any meaning to the user, and by revealing them in obvious ways, you introduce an extra dependency, one that is particularly hard to handle because it lives outside the realm of software - people will write down, e-mail, fax, print, bookmark, etc., those ID's, and if you ever change them, you're in for some annoying support tickets.


答:
DotNetNuke, a large open source project, made the switch from VB.NET to C# some time ago, and it might be helpful to have a look at their reasons.

Note that their reasons were political rather than technical. In a nutshell, they say (in a much more polite way): "There are a lot of stupid people decision makers who think that C# is faster or technically superior to VB.NET. Since it really doesn't matter whether we put semicolons at the end of our lines or not, we might as well switch to C#, to get rid of this false toy project image."

So, from a technical perspective, I'd recommend you to stay with VB.NET (syntax similarity to what your people are already familiar with), unless there are compelling marketing reasons to switch to C#.

Title: Changing from VB.NET to C#?

Body:
I am working on co-op at a company as a test engineering specialist.  This is not technically a software job, however at the end of the day, I spend most of my time programming.

I am not a programming wiz by any means, but I am very comfortable using VB.NET since that is what projects started at my company previous to my time were written in, and so it is what I have learned and used in the position.

I have gotten the feeling from my time searching for help online when I need it that there is generally more and better support for C# than there is for VB.NET.  This has led me to thinking that it may be beneficial for the company going forward to start programming less in VB.NET and more in C#.

However, almost all projects in my department (since several other people work on small programming projects) are currently written in VB.NET.  Additionally, most of the software design done in our department is relatively simple I would imagine relative to a software focused area of any company. Probably half of it is generating html pages with graphs to visually illustrate certain data.  Taking these two facts into account, there are obvious disadvantages to trying to switch the main programming language used.  Also, the vb.net language is very similar to VBA (for excel) and VBScript, which are also used quite a bit in my area of the company.

I am basically not sure if it would be worth the work to change the main language used since there is not a lot of complicated programming done, and similar languages are necessary anyways it seems.

I was curious what additional insight experienced programmers may be able to offer me regarding changing the main language used in my area from VB.NET to C#?  What benefits or disadvantages are there that I may not have thought of?  How big a role do each advantage and disadvantage play?

What is your overall opinion on the idea of changing from VB.NET to C#?


答:
No, you absolutely, positively don't want to allow access to arbitrary resources just by knowing their internal id. This is the internet, whatever malicious, criminal, or plain childish presence you might imagine to exist, actually exists, and sooner or later they will come to your site. Unless everything you could ever serve is completely public for everyone (and if you have even one customer, that is guaranteed not to be the case), you must restrict access to those who are actually authorized to have it.

The usual solution is to use authorization tokens of some kind that are stored in an encrypted session, and checks that verify whether something is supposed to be visible to the authenticated user before actually sending it out. This can be an actual security manager, such as the one that ships with the JDK, or any other component that fulfills the same role, as long as it does so consistently. (Whether to expose internal IDs to someone who is already authenticated or not is also an interesting question with various pros and cons, but it is less security-essential.)

The value of doing this is hard to calculate until you are actually attacked by someone who means business. Then it's usually the difference between going out of business and just shrugging off yet another foiled script kiddie.


问:
How do programmers quit a job?
I'm thinking about leaving my current employer and wondering how one goes about that process in the programming world. We have a lot of projects on the go at the moment and I'm the only developer. We have 4-5 projects that are fairly big and need to be done in the next few months and even a few longer than that.

I'm leaving because I'm the only employee and that's doing me no good. I'm young and want to learn, so a team would be nice. It's also too much work and the company is managed horribly.

I have no contract to worry about so I could theoretically quit and just not come back without notice. Just wondering how this is normally handled.

Should I write a resignation letter

How much notice should I give

Should I give a reason for leaving

Should I go to my boss who is the main reason I'm leaving or go to his boss?

Overview of replies

From the feedback here, it looks as though it's best to give 2-4 weeks of notice, and present a written resignation. Don't go into detail explaining why you're leaving in most cases. Don't burn bridges. Be professional.

答:
No matter what you do, do it in a respectful way. It will come back to you in full circle. I've been called back by many companies that i've left and i've gotten contract work from them. Give them at least 2-4 weeks so they can find a replacement.

Would you want your mechanic quitting in the middle of fixing your car without having another to take over?

Just my 2 cents. In the end it is all about how you feel. But I would bring it up to them and ask them to hire another person. Maybe a Sr dev this time. If you're young then I suggest you stay and earn exp in years. Take side jobs to get your learning in. Companies don't want to pay you to learn on the job.

Title: How do programmers quit a job?


问:
Models per database table?
I am using codeigniter, and have found myself in a similar situation where I have repeated Model methods.
I am creating a Model per Controller. But I would creating a Model per database table be considered good practice? That way methods aren't written twice.

Instead of Model per Controller or Several small Models that  are shared.

Example if I have a model method get_user($user_id) I could write it on users_models.php ...

One of the downsides I see of this is that I might have to call several models, rather than just controllername_models.php .

Could loading several models where several methods might not be used from a controller affect performance and speed? What could be the best way to tackle this down?

Note: There are similar question, but they do not cover the ground of Model per database table.

答: I's say that a model per table is just recreating your database in a class structure. It is known as a anemic model and considered an anti-pattern. That is because classes are intended to have both data and behaviour. If you restrict your models to a single table, where do you put the code (behaviour) that needs to deal with data and behaviour from multiple tables? Your controllers would then need models that use one or more of these "table" models... So, apart from in the most basic of apps, you gain little if anything from this approach.</p>

Title: Models per database table?


答: Give it 3 months, then go back and look at your code. I promise you, if you can't find something wrong with it (or question who wrote this junk!) you are a better man than I!</p>

Title: How do I review my own code?


问:
Do you believe it's a good idea for Software Engineers to have to work as Quality Assurance Engineers for some period of time?
I believe it is.  Why?

I've encountered many Software Engineers who believe they are somehow superior to QA engineers.  I think it may help quench this belief if they do the job of a QA engineer for some time, and realize that it is a unique and valuable skill-set of its own.

The better a Software Engineer is at testing their own programs, the less cost in time their code incurs when making its way through the rest of the software development life-cycle.

The more time a Software Engineer spends thinking about how a program can break, the more often they are to consider these cases as they are developing them, thus reducing bugs in the end product.

A Software Engineer's definition of "complete" is always interesting...if they have spent time as a QA engineer maybe this definition will more closely match the designer of the software's.

Note I make above suggestion with a small time-frame in mind as I am aware having someone work in a position that is not the position they are hired for is definitely a recipe for losing that developer.

What do you all think?

答: Software testing is the destructive process rather than constructive. But programmer think of constructive to their product to ensure the product completed on time and with in budget. If software developer think like destructive of their own product then who will be next to built the product. So each portion of software development cycle must be done by the people assigned in each portion of development cycle. If you engaged in two or more field then its is sure your will never be perfect on any of them so do one things either programmer or QA or any other options and be perfect on that.</p>


问:
What code smell best describes this code?
Suppose you have this code in a class:

private DataContext _context;

public Customer[] GetCustomers()
{
    GetContext();

    return _context.Customers.ToArray();
}

public Order[] GetOrders()
{
    GetContext();

    return _context.Customers.ToArray();
}

// For the sake of this example, a new DataContext is *required*
// for every public method call
private void GetContext()
{
    if (_context != null)
    {
        _context.Dispose();
    }

    _context = new DataContext();
}
```

This code isn't thread-safe - if two calls to GetOrders/GetCustomers are made at the same time from different threads, they may end up using the same context, or the context could be disposed while being used. Even if this bug didn't exist, however, it still "smells" like bad code.

A much better design would be for GetContext to always return a new instance of DataContext and to get rid of the private field, and to dispose of the instance when done. Changing from an inappropriate private field to a local variable feels like a better solution.

I've looked over the code smell lists and can't find one that describes this. In the past I've thought of it as temporal coupling, but the Wikipedia description suggests that's not the term:

Temporal coupling

  When two actions are bundled together into one module just because they happen to occur at the same time.

This page discusses temporal coupling, but the example is the public API of a class, while my question is about the internal design.

Does this smell have a name? Or is it simply "buggy code"?

答:
Its just buggy code.

```<code>    if (_context == null)
    {
        _context.Dispose();
    }
</code>```

If ever _context == null then you will be calling a method on a null object so it will just fall over. There is no reason to reinstanciate the datacontext for every call.

Body:
Its just buggy code.

    if (_context == null)
    {
        _context.Dispose();
    }

If ever _context == null then you will be calling a method on a null object so it will just fall over. There is no reason to reinstanciate the datacontext for every call.


问:
Why are statements in many programming languages terminated by semicolons?
Is there a reason that a semi-colon was chosen as a line terminator instead of a different symbol?

I want to know the history behind this decision, and hope the answers will lead to insights that may influence future decisions.

答:
Many languages use syntax that is modeled after C (which was modeled after B - thanks @Crollster). As can be seen in the comments, there is a long chain of such languages... B was inspired by PL/I, which was preceded by ALGOL at using the ; as a separator.

Since in C the statement terminator is ;, these languages follow suit.

As for why it was selected as a statement terminator in C - possibly because of its use in English "to indicate interdependent statements".

C was also invented on the PDP-11 at a time where there was limited amount of memory available for character sets, so the inventors of the languages had to work within these constraints.


答:
In English the semicolon is used to separate items in a list of statements, for example

She saw three men: Jamie, who came from New Zealand; John, the
  milkman's son; and George, a gaunt kind of man.

When programming you are separating a number of statements and using a full stop could be easily confused for a decimal point.  Using the semicolon provides an easy to parse method of separating the individual program statements while remaining close to normal English punctuation.

Edit to add

In the early days when memory was expensive, processing slow, and the first programming languages were being devised, there was a need to split the program up into separate statements for processing.  Some languages required that each statement was placed on a line so that the carriage return could act as the statement delimiter.  Other languages allowed a more free format to the text layout and so required a specific delimiter character.  This character was chosen to be the semicolon, most likely because of the similarity to its use in the English language (this has to be a supposition; I was not there at the time) and as it did not produce a conflict with the other punctuation marks and symbols that were required for mathematical or other syntactic purposes.

Edit again

The need for some terminator character goes back to the requirements for parsing the language text.  The early compilers were written in assembly language or, in some cases, directly in hand crafted binary machine instructions.  Having a special character that identified the end of the statement and delimited the chunk of text that is being processed makes the processing that much easier.  As I said above, other languages have used the carriage return or brackets.  The Algol, Pascal, Ada, BCPL, B, C, PL/M, and other families of languages happen to use the semicolon.  As to which one was first to use this particular character, I do not go back far enough in history to remember.  Its choice and adoption makes perfect sense as

Its use mirrors the use in normal English punctuation.

Other characters (e.g. the full stop) could be confusing as they already have a common use (a full stop is also used as a decimal point).

A visible punctuation character allows free format code layout.

Using a similar delimiter character in derivative or later languages builds upon the familiarity gained by all of the programmers that have used the earlier language.

As a final remark, I think that there has been more time spent on these answers and comments than was spent in deciding to use the semicolon to end a statement when designing the first language that used it in this way.

Title: Why are statements in many programming languages terminated by semicolons?

Body:
Is there a reason that a semi-colon was chosen as a line terminator instead of a different symbol?

I want to know the history behind this decision, and hope the answers will lead to insights that may influence future decisions.


答:
If you really must instantiate the context in every call (I dont know why you would need to do this) then make it explicit

```<code>public Customer[] GetCustomers()
{
    using (var context = new DBContext())
    {
         return context.Customers.ToArray();
    }
}

public Order[] GetOrders()
{
    using (var context = new DBContext())
    {
        return context.Customers.ToArray();
    }
}
</code>```

That still isn't perfect code as it's tightly bound to the DBContext class and impossibly to isolate for unit testing

Title: What code smell best describes this code?

Body:
Suppose you have this code in a class:

private DataContext _context;

public Customer[] GetCustomers()
{
    GetContext();

    return _context.Customers.ToArray();
}

public Order[] GetOrders()
{
    GetContext();

    return _context.Customers.ToArray();
}

// For the sake of this example, a new DataContext is *required*
// for every public method call
private void GetContext()
{
    if (_context != null)
    {
        _context.Dispose();
    }

    _context = new DataContext();
}
```

This code isn't thread-safe - if two calls to GetOrders/GetCustomers are made at the same time from different threads, they may end up using the same context, or the context could be disposed while being used. Even if this bug didn't exist, however, it still "smells" like bad code.

A much better design would be for GetContext to always return a new instance of DataContext and to get rid of the private field, and to dispose of the instance when done. Changing from an inappropriate private field to a local variable feels like a better solution.

I've looked over the code smell lists and can't find one that describes this. In the past I've thought of it as temporal coupling, but the Wikipedia description suggests that's not the term:

Temporal coupling

  When two actions are bundled together into one module just because they happen to occur at the same time.

This page discusses temporal coupling, but the example is the public API of a class, while my question is about the internal design.

Does this smell have a name? Or is it simply "buggy code"?

Body:
If you really must instantiate the context in every call (I dont know why you would need to do this) then make it explicit

public Customer[] GetCustomers()
{
    using (var context = new DBContext())
    {
         return context.Customers.ToArray();
    }
}

public Order[] GetOrders()
{
    using (var context = new DBContext())
    {
        return context.Customers.ToArray();
    }
}

That still isn't perfect code as it's tightly bound to the DBContext class and impossibly to isolate for unit testing


问:
Ensure data entered by users adjusts to what actually is
This is more of a usability issue I'd say, looking of suggestions on it.

I have a system that depends on the data entered by the users to be correct, as in the address exists, the name is correct, etc. This is all for places.

Now the way I figured I could do this is that I have every entry peer reviewed, as in, have 5 other users check and ensure the data is correct before allowing it to be indexed and viewed on the site. The problem with this approach is that the site isn't one where the users will inhabit long, just log on look for a place and that's it, so they might not be inclined to verify that other user's entries are correct.

What do you think about this, can anyone suggest a solution that might adjust to my situation?

答:
It depends on who has the most benefit from the correct data. Do the users of the site have a benefit for themselves if they enter they own data correctly? For example, will they miss a newsletter if they make a typo in entering their correct email address? Then you don't need any peers, just make it easy for your users to double-check the data they entered into the registration form. You could display the data in a comprehensive, easy-to-read dialog and ask the users explicit for confirmation, and offer them always an obvious way to step back to correct any typos.

When the users don't have a real benefit, who else has (and so has an interest in getting the data right)? Other people visiting your site? Then make it easy for them to notify the admin or the address holder when they find wrong data entered into your system. For example, here on SE, the "flag" button provides an easy way to mark posts as probably problematic - create something similar.

And what about living with some errors? Is it really so bad if wrong data goes into the system? Sometimes it is better to allow any data to be entered and viewed, so it gets easier for anyone to see what data is in the system, so you get more feedback about errors. EDIT: here is an additional idea: add a "confirmation" button (or "this information was helpful" button) to each address, and display the statistics how many people confirmed the address to be valid. Or just an "up/downvote" buttons, just like here on SE. This gives everyone more transparency about the quality of the data.


问:
How to control work of programmers (outsourcers)
Some time ago I decided to outsource web development projects (php coding & design). I've opened small office abroad with manager and couple of programmers and designer. I just started but already have a problem controlling their work.

Some programmers are fast, others work much slower. I pay them fixed salary, so it matters for me if they do their job on time.

When they work from office, I at least have a person responsible for the project to tell if they really worked. But sometimes they work from home and in that case I have no way to know if they really spent that time working on some issue.

Some of my ideas were: controlling amount of code done with svn, strict deadlines, everyday reporting.. But nothing seems perfect to me. It creates even more work from my side.

Can anyone suggest a way of fair judgement on how much really time was spent on actual work? How to stimulate people to work? Maybe create some bonus system if work is done fast? Any idea/experience on this topic would be highly appreciated.

答:
You must define performance metrics and goals that they must meet. If you were doing any type of Agile and/or SCRUM then you wouldn't have this problem. There are many free applications to help with this. Rally (rallydev.com) is a great one (not free!!)

Set time lines and goals and hold them to it. Seems like you need to apply basic managerial skills. If they don't produce, then get rid of them. You pay them for results. Would you give $10 to Mc Donalds for 1/2 of a hamburger?

If you're a developer of any type then you should be able to break down a project come up with time estimates for each part. Give the estimates to the developers and you and your team can then discuss them and agree. If you say 5 hours and they say 15, make them explain why it will be 15 and not 5. Even if you don't know what they are talking about, you can smell BS. Call them on it and make them explain it. That will cut down the crap. This is what I do everyday and it works even with difficult employees.


问:
How to get JMS to front end
I currently have a web application and I would like to add a messaging feature to it.
In order to do that, I use JMS(actually OpenMQ, the implementation provided with Glassfish 3).
The problem is that I do not know how to get the message notification from the background(from the listener) to the foreground.
I am using JSF as a framework, if it does have an importance.
Could you please tell me how should I notify the user about a received message(like a chat).
Any suggestions are welcomed.</p>

答:
You may be interested in Comet, a programming model that allows the server to push data to a client. There are implementations for JSF, look at this blog post about Richfaces integration for an example.

HTML 5 specifies WebSockets that can be used for server push, but not all browsers support it.

The simple alternative is to simply poll the server at regular intervals, that might create a lot of unnecessary messages though.

Title: How to get JMS to front end


问:
Protecting proprietary code linking with LGPL v3 code
I've been warned that LGPL v3 forbids any kind of modifications that would prevent reverse-engineering, including software protection such as obfuscation.

In practice, does this license make it illegal to use something like SecureSWF, or simply a JavaScript minifier, when linking a program with a LGPL-licensed library?

答:
For legal purposes, JS minifiers can be treated as compilers. They take readable input and produce logically equivalent, but more efficient output. It follows that using a JS minifier on LGPL sources is allowed, iff you do make the un-minified sources also available.

Obfuscation is pointless as the (L)GPL requires you to also make the source available in a reasonable (un-obfuscuated) format.

OwnerDisplayName: Warren Seine


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
Heroic Coding

Coding late into the night, working long hours, and clocking lots of overtime are a sure sign that something went wrong.  Further, my experience is that if you see someone working late at any point in the project, it only ever gets worse.  He might be doing it just to get his one feature back on schedule, and he might succeed; however, cowboy coding like that is almost always the result of a planning failure that will inevitably cause more of it soon.  So, the earlier in the project you see it, the worse it will eventually become.


答:
To start things off, this is a hard problem since there really is no good metric that you can use to rank how productive one developer is versus another one. If you use something like lines of code (LoC) you may find that one developer only writes 1000+ LoC, but if its just getting information from the database, is that nearly as hard as the 200 LoC that someone else wrote for parsing data that is being entered, or even the one line of code that was written by someone chasing down a nasty bug?

One idea that did come to mind was having a tracking system where in the tasks that need to be done would be entered (i.e. "Get x from the database and display it to users", "Fix the stack overflow but in the y module") and have all of your developers "vote" on how many hours they think it would take them to do each task. Once you have everyone vote, you could average that out and see how they compare to what developers are actually putting into fix the problem. There would likely be a bit of calibration involved and there are still ways to game the system, but it might be a way to get a fair idea of what they expect of each other an thus possibly a fair metric to use for judging them.

Title: How to control work of programmers (outsourcers)

Body:
Some time ago I decided to outsource web development projects (php coding & design). I've opened small office abroad with manager and couple of programmers and designer. I just started but already have a problem controlling their work.

Some programmers are fast, others work much slower. I pay them fixed salary, so it matters for me if they do their job on time.

When they work from office, I at least have a person responsible for the project to tell if they really worked. But sometimes they work from home and in that case I have no way to know if they really spent that time working on some issue.

Some of my ideas were: controlling amount of code done with svn, strict deadlines, everyday reporting.. But nothing seems perfect to me. It creates even more work from my side.

Can anyone suggest a way of fair judgement on how much really time was spent on actual work? How to stimulate people to work? Maybe create some bonus system if work is done fast? Any idea/experience on this topic would be highly appreciated.


问:
Where is the application of Calculus (of continuous quantities) in Computer Science or programming
I am a Software Engineer professional. I have studied calculus as a core course in my graduation studies. I want to ask question, that what/where is the implementation of calculus in computer science?</p>

答:
Calculus is useful for looking at changes in physical quantities so is mainly useful in the physical sciences. Programming mostly only deals with calculus when the problem domain requires it.

But of course there is also the meta-problem of algorithms for good numerical approximations of integrals or differential equations e.g. http://en.wikipedia.org/wiki/Numerical_integration and http://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods
which are certainly computer science orientated.

I've not used calculus in programming since university (which was to implement integration by simpson's rule in FORTRAN)


答:
Consider doing a Fagan inspection by yourself - you'll have to adapt the process because you're by yourself, but you should be able to get quite a bit of value out of it.  The trick is going to be to find the right "ruleset" to evaluate your code against as a solo dev, and then having the discipline to ask those questions in a critical, analytical, merciless frame of mind each time.  I suspect you may want to brainstorm your own 4-5 crucial questions to start with, and then evolving it over time.  Some people are against formal inspections because they seem to be so time-intensive... before you decide that they're too expensive, bear in mind all the statistical evidence that doing inspections properly actually reduce project time.  Here's a Wikipedia link that you can start further research with:

http://en.wikipedia.org/wiki/Software_inspection

There have been a few books too, e.g. Google for "Software Inspection Process" by Strauss and Ebenau.

Another option is to pay someone to inspect an important project - or perhaps pay them occasionally to do inspections of all your code.  This guy's pretty good, we've flown him out a number of times to train our newer devs:

http://www.javaspecialists.eu/

Title: How do I review my own code?


答:
Computer Science and Calculus have nothing to do with each other, besides the somewhat incorrect assumption by academics that practicing programmers will require higher math.  I say "somewhat incorrect", because whether you will or won't will depend entirely on what your "problem domain" will be.  If you're writing "business logic", like many programmers, you'll probably never use any math higher than basic arithmetic.  If you're writing molecular-modeling, like a physical- or chemical-scientist, you'll use it every day.

I have to say that in over 30 years of programming for a living, writing operating system, systems management, web server, and other complex programs, I've only ever needed higher math once, and only because I didn't know where to find the already-published algorithm that required only arithmetic.

Title: Where is the application of Calculus (of continuous quantities) in Computer Science or programming

Body: I am a Software Engineer professional. I have studied calculus as a core course in my graduation studies. I want to ask question, that what/where is the implementation of calculus in computer science?</p>


答:
There are a few areas where calculus is needed, more specifically differential equations.

Every car company has to test its models to see how it behaves in crash situations. They do this by placing a multitude of sensors all over the car and crashing it. The information received from those sensors needs to be interpreted and analyzed.

If you ever write software that does this, then you'll be dealing a lot with differential equations. The angles at which each part of the car is bent from the crash are passed through these equations to get the values of the forces involved. The deceleration values must also be computed using such equations. I don't know too much about this, though...

This is only one of the applications of calculus in computer programming. Maybe someone knows other scenarios.

Programmers have always complained that various areas of mathematics don't ever apply in their work (and therefore there's no reason to learn it). This is mostly true, but sometimes you do need to know such concepts to get the job done. For example, vector spaces knowledge (from linear algebra) can be of tremendous help when making 3D rendering engines (for games, for example).


问:
Please explain the benefit(s) of using an XML-based syntax (e.g. XAML) instead of normal source code (e.g. WinForms)?
First off, please note that this question is not about WPF vs. WinForms.

What are the highest-ranking benefits that led Microsoft to invent XAML in favour of the “old” approach of generating compilable C# code?

My impression is that other developers seem to find a lot of downsides to it, but Microsoft went with it regardless, which must mean that there is a benefit that I am not seeing. I would like you to explain to me what it is that I am missing.

答:
One point I dont see in alot of answers is that xaml encurages the core of wpf desgin principals. Seperate the visual representation and visual logic (in pratice this is limited to triggers and such but assuming no custom controls this is often all you need) from the business logic. This also couples well as others have noted with a expresive syntax for binding, attached propertys and other meta data which can be more verbose in normal C# code.

On a more personal opinion note, one thing I find nice about xaml is it beter represents the visual hierarchy of controls than just generating code. At a glance its easy to see how one control is related to the others.


答:
Computer science usually deals with finite things. However there are cases where you use real functions and apply analytic methods, sometimes including infinitesimal calculus.
One is when you need to express relations for problems of arbitrary size and granularity. This often happens in information theory e.g. in Shannon capacity or information entropy. Another sometimes occurs when calculating upper or lower bounds. Many quantities in graph theory are complex sums, that cannot be directly calculated, but can be limited by real functions or integrals. And even basic stuff like asymptotic behaviour is defined in terms of limits, so you need at least the basic concepts.

As practitioner, you probably won't need to do those calculations, but understanding the concepts makes it easier to reason about choice of algorithms and practical limits you are to encounter, especially when you get to something that involves correction codes, compression or just some complex graph algorithm. Or statistics, which also uses analysis a lot.

Also it's difficult to teach just part of mathematics without ever touching infinitesimal calculus, which includes the mathematics mainly used in computer science (graph theory, linear programming, optimization etc.)


问:
Modelling project structure for Management
The project I am putted in is running awful. :-) Main Problem is a missing architecture and a missing guidline how to organize projects. In this case I have done a sample project architecture with UML class and component diagrams and layer diagrams. The main problem is, that I have to present this architecture to the management. But the management is not familiar with UML or Layer Diagrams and for most of them its not possible to understand the logic behind it.

In that case I want to present the management a visualized project structure with easy understanding. I've searched for some ressources and examples with easy understanding visualizations, but was not able to find one.

So my question is how you would visualize your software architecture to the management, which techniques do you use?

Little Note: its a very big sharepoint project with more than 50 sub projects.

答:
UML is a great way to communicate design to technical resources on a project, though in my experience, the vast majority of non-technical project resources get lost with it.  UML does indeed require a minimal level of training to fully understand it or formulate it.  Some non-technical peers may be experts in Use Case diagrams lets say, but when they see a component diagram it might as well be written in kanji.

I find that knowing your audience for the diagram is important before you start drawing.  Non-technical peers generally have an easier time understanding and following Flowchart diagrams rather than Activity or Sequence diagrams.  They may also just want labeled boxes and arrows instead of a full UML component diagram or deployment diagram.  Sometimes I will do two sets of documents, one simplified for non-technical peers and one in UML for technical peers.  Other times if I am running short on time I don't even bother with the UML diagrams because most of the time the technical person can generally understand the complexities in the simplified diagram anyway.

Another important question you have to ask yourself is why your non-technical manager finds these documents important?  Is it because the project is running into problems and the urge to micro-manage is setting in?  Is it to assist a quasi-technical sales person in better explaining the advantages of your software and architecture to prospective clients?  It could be as shallow as a manager wanting to pin up complicated looking diagrams in his office or technical area to try and impress visitors he brings to the office (true story).  The bottom line is to know your audience and know it well.


答:
Calculus can be used to solve recursion complexity calculations.

(The recursion's complexity can be expressed with infinite discrete sums which can be solved with their continuous counter-parts.) [ 1 ][ 2 ]

Also both calculus and other forms of maths are used in various applied computer science.

E.g. Physics Engines, Signal & Image Processing, Computer Vision, Information Theory.


答:
Main Problem is a missing architecture

What problem does your architecture solve? Even the most poorly designed application has an architecture, so unless you're starting from scratch, one exists. In your case, maybe no one bothered to document it. Management wants to know that you have one that gives the project some sort of advantage (e.g. performance, ease of maintenance, code reuse, accepted standards, etc.).

missing guidline how to organize projects.

They'll feel more comfortable if you don't appear to be working in chaos. Prioritize the 50 sub projects. Designate someone who is tracking the progress. Show them you have a system, so you know developers are getting things done. Can you show the architecture is conducive to this type of project?

Unfortunately, they really want to know: How Long? and How Much? You should be able to answer these questions, but it may not be as accurate as they want.

Title: Modelling project structure for Management

Body:
The project I am putted in is running awful. :-) Main Problem is a missing architecture and a missing guidline how to organize projects. In this case I have done a sample project architecture with UML class and component diagrams and layer diagrams. The main problem is, that I have to present this architecture to the management. But the management is not familiar with UML or Layer Diagrams and for most of them its not possible to understand the logic behind it.

In that case I want to present the management a visualized project structure with easy understanding. I've searched for some ressources and examples with easy understanding visualizations, but was not able to find one.

So my question is how you would visualize your software architecture to the management, which techniques do you use?

Little Note: its a very big sharepoint project with more than 50 sub projects.


问:
What design patterns are the worst or most narrowly defined?
For every programming project, managers with past programming experience try to shine when they recommend some design patterns for your project. I like design patterns when they make sense or if you need a scalable solution. I've used Proxies, Observers and Command patterns in a positive way for example, and do so every day. But I'm really hesitant to use say a Factory pattern if there's only one way to create an object, as a factory might make it all easier in the future, but complicates the code and is pure overhead.

So, my question is in respect to my future career and my answer to manager types throwing random pattern-names around:

Which design patterns did you use, that threw you back overall? Which are the worst design patterns, the ones that you should consider except in the one single situation where they make sense (read: which design patterns are very narrowly defined)? (It's like I was looking for the negative reviews of an overall good product of Amazon to see what bugged people most in using design patterns.) And I'm not talking about Anti-Patterns here, but about Patterns that are usually thought of as "good" patterns.

Edit: As some answered, the problem is most often that patterns are not "bad" but "used wrong". If you know patterns, that are often misused or even difficult to use, they would also fit as an answer.

答:
There are no bad patterns only bad people.

I'd much rather inherit easily readable code that does something clear but is a little verbose or not(queue evil villian music) re-usable(gasp!) than some mish mash of InheritAbstractTemplateFaucetSink<Kitchen>.

Re-usable code is great! Chances are you are not writing code that will be re-used or re-writing similiar logic for another application would take you less time than some insane attempt to re-use some other application's code.

For further reading crack open some of the C code in the sane implementations of the posix headers or the clibs and play spot the pattern. This code was written by some of the smartest and most dedicated programmers in the world. Do you know how many Abstract Factory Patterns you're going to see? ... NONE!. Even better chances are if you understand the other parts of whats going on, you'll find the logic very easy to understand and trace.

My point is this most of the "patterns" were not created to make code better they were created to sell books and modelling software. If you are good at programming you will probably eschew most of these and write clear,concise, and cleverly designed code that solves your problem. When you have another problem you will write clear, concise, cleverly designed code to solve that problem. If your goal is to write less code than I would think your not cut out to be a programmer. I love writing code and want to write it as much as possible. When I re-write something I've already written I do it tens times as fast and get to get rid of all the things I wasn't happy with the first time I did. As a bonus I get to do it with none of the limitations of the first problem set because its a new problem(I probably have 15 scripts in 5 different languages that start tomcat floating about).

With that I will leave you with probably the best(relevant) quote in computer science.

"There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult."

Tony Hoare(inventor of the quicksort, father of modern OS design, creator of Hoare logic, and Turing award recipient)


问:
Is Information Technology really Engineering?
While travelling I met a mathematician who was sitting near me. In a discussion he said: "...there is nothing like engineering in IT or rather programming". A true engineering is what Architecture is, what Electrical and Mechanical is.

It made me think and I was puzzled. A percent of my brain agreed also because in Indian Army, there is no subject like Computer Engineering in the Engineering Corps. They don't consider programming as engineering. This is what I heard few years back, I don't know what Indian Army thinks now.

What are your views?

答: Software engineers in an engineering company are engineers.  I'm talking about places like defense contractors, equipment manufacturers, etc.   We follow rigorous processes for: creating requirements and design documentation, doing detailed analysis that the design will meet requirements before any code is written,  performing code reviews and unit tests, planning and performing integration and qualification tests.   Documents are reviewed by boards of peers and stakeholders, tests are witnessed by the QA organization and results presented to the customer for formal acceptance.   Software engineering as practiced in these places is a rigorous, scientific process.


问:
A Class named Class?
This is more of a style question, but it is something I am currently pondering for a project of mine.

Assume that you're creating an application which is modeling a school. So there are entities like Student, School, etc. Now this is all fine and intuitive until you get down to Class, as (in most languages) Class is a reserved word. So, given that Class is a reserved keyword, what would you call such an entity that models a school class?

答: You could declare the entity as ClassRoom!</p>

Title: A Class named Class?


答:
It depends. Are you going to just be told what to program, or are you going to know much about the content area?

I've worked for years in graphics UIs and mathematical modeling, specifically pharmacometrics and biostatistics.
I need to understand ordinary differential equations, frequentist and bayesian statistics, pharmacological modeling, and optimization algorithms.
Every so often I need to solve calculus problems that nobody has figured out before, or if they did, they didn't publish it, or if they published it, they only did easy cases.
I have to handle the hard cases as well.

All this is in a field where mistakes can be very costly, so it's important to be able to make air-tight justifications.
Programming is fine, but it's only part of the story.


问:
Software bundle containing LGPL libraries as Java Fat-Jar Archive
At work, we're deploying a software bundle of a Java application (written by us) which has lots of external dependencies, most of them being LGPL and BSD-licensed third-party-libraries distributes as JAR archives.

Currently, we're deploying a test-client of the software which is distributed as a single java fat jar archive, created by the Maven assembly plugin, which does roughly the following:

extract all dependencies

rebundle them as a single jar-archive

All class files are extracted, and then bundled back into a single JAR file with our own application. I realized that also some files get overwritten, mostly LICENSE.txt-files, due to having the same name.

I'm wondering whether this is correct and complies with the LGPL license. What would be a better way to distribute the software? How would this particular package be best organized?

We did not incorporate any source code directly into our source files, nor did we touch the binary files. The source code of the libraries accompanies the whole product. (It is software that is internally used, not deployed to customers or anything, but I guess that does not matter.)

PS: I asked the same question on Stack Overflow, and I was suggested to ask it here.

答:
This is really a difficult matter that should be discussed with a lawyer. Anyway, overwriting the LICENSE.txt files (which effectively eliminates all but one of them) is definitely a no-go. Renaming them to Foo-LICENSE.txt, Bar-License.txt is the first step you should do immediately.
Concerning the LGPL, offering instructions how to replace the lib withing the fatjar might be enough to comply with section 4e of the LGPL (ask your lawyer). If asking the lawyer is not feasible, directly asking the authors permission to do it like that might be an alternative.</p>


问:
Is obscuring/obfuscating public-facing database ids really a "best practice"?
I've heard people lecture here and there on the internet that it's best practice to obscure public facing database ids in web applications. I suppose they mainly mean in forms and in urls, but I've never read anything more than a mouthful on the subject.

EDIT: Of course, now that I ask this, I find some resources on the subject:

https://stackoverflow.com/questions/2374538/obscuring-database-ids

https://stackoverflow.com/questions/1895685/should-i-obscure-primary-key-values

http://joshua.schachter.org/2007/01/autoincrement.html

These links satisfied some of my curiosity, but the SO posts don't have many votes and aren't necessarily centered around the topic in this context so I'm not sure what to make of it, and some of them claim that the third link is bogus. I'll leave the rest of my post intact:

I understand the differences between obscurity and security, as well as how the two can work together, but I can't imagine why this would be necessary.

Is there any truth to this, is it just paranoia, or is it just totally bogus altogether?

I can think of ways to do it, but of course it adds a lot of complexity to the application code. Under what circumstances would this be useful? If this is something people frequently do, how is it usually deployed? Hashing the identifiers? Something else? It seems like a lot of work for not much extra security. I'm not looking for real solutions, I just want to get an idea of how/why people would do this in the real world.

Is this really considered a "best practice" or is it merely a micro-optimization of little value?

NOTE: I think a few folks might have gotten the wrong idea: I'm not suggesting that difficult-to-guess ids would be the only security mechanism, obviously there would have be the usual access checks. Let's assume those are in place, and that simply knowing the id or hashed id of a record is not enough to grant access.

答:
Obviously it depends on how sensitive the data is but for medium security the very minimum I would do is to include the ID and a checksum value.

Generate the checksum by adding salt (i.e. a set collection of random characters) before and after the ID and doing an MD5 on the value.

On every page that reads the ID value it should generate the checksum value and compares it with the one passed, deny the request if it does not match.

If a potential hacker is able to get enough valid combinations then they may be able to work out the Salt value by brute force, so if you can add another layer of security such as checking the User ID that will also help.


问:
Is MongoDB the right choice in my case?
I'm going to build my first real project in Rails that consist in a web app made of 3 main parts:

The static part where no database is used

The User registration part which will require a database and I can use MySQL since each user's row will have the same fields

The "App" where users will be able to create, organize, edit... items in collections and share them with other users

There will be several item types and each one will have different options for example I may have "video" items with the following options:

id

user_id

collection_id

title

platform (if embedded)

url (if embedded)

file name (if hosted on my app)

file size (id hosted on my app)

and "map" items:

id

user_id

collection_id

title

platform (google maps, bing maps...)

location

url

map size

As you can while for users I may use MySQL for items the flexibility of MongoDB may be useful since each item may need different options then another item

Up to now I've always used PHP and MySQL (always on shared hosting for small projects) and scalability is a totally new word for me.

I have time to learn but I would like to be able to do something concrete in something like 1 month.

I've read a lot about MongoDB and NoSQL vs RDMS and MySQL and after trying it I have to say that I like how MongoDB works: no tables, no rows and its documents JSON like so:

In my situation what would you raccomend? why?

About scalability there may be problems with MongoDB? if yes when (in term of DB size) and may these problems slow down my app considerably?

Edit: how the app will work

Since many asked this is how I'd like the app to work:

A user sign up

He's logged in

He create his first collection iside which he can create infinite items

Items are of various type and each type need different data to be saved in the database and type of items may be added or modified

Users may create other collections and items inside it.

So we have CRUD for collections and items inside of them and each collection/item is referred to a specific user

The main problem with MySQL is that it hasn't a flexible schema, there is way to solve this (a workaround?)?

Thinking about NoSQL the only doubt I have is about join, for example given a certain colection I want to retrieve datas related to the User with id = user_id field in the collection

EDIT: Idea to keep using MySQL

Create a field in the "items" table with optional settings, each setting divided by a | or another symbol.

Then I will save somewhere a structure of each item optional settings, for example the "notes" item type need two optional settings "colour" and "strange_setting", when I get the data from MySQL i will split the field for optional settings into an array knowing that the first item in the array is for "colour" and so on.

What do you think? there are problem with that solution? do you have other ideas?

答:
So, your design gets to save into your database two different kind of objects:

User object (which have always the fields).

Apps objects (which can have different fields). An app will belong to one user only.

A collection could or not me made as a different object, as is just a tag to group different apps. For the sake of argument, let's say there are no collections and users have just a list of applications.

While I think is achievable on MySQL, in MongoDB you'll have a greater flexibility in terms of the structure of app objects, and probably it will map more naturally your representation into the database, making the code simpler.

In MySQL you'll have problems dealing with different formats for different apps, but it is possible. Some ideas:

You can create an intermediate table with all the common info between all the objects (id, user_id, title, etc), then the type, so you can search for it on another table with only the non-common fields for that format (e.g. file_name and file_size for files). You'll need to create a different table for each different format. If both tables are indexed by app_id (Primary key), it will be fast enough, as accessing a table by an indexed value is fast.

You can encode the data in some format and store standardized. E.g., encode the non-common data in JSON as a string and store it on a VARCHAR field. Be careful with the size of that field so you don't run out of space. The format can be complex (JSON) or simple (just values separated by commas)

You can create different "generic" fields, something like int1, int2, str1, str2, and define that str1 for an app type is "file_name" while for a different type could be "location".

On MongoDB, it could be as simple as just using two MongoDB collections, one for the users and another one for the apps. Assuming some sort of limit (which is not the case, as you described, but just for saying), you could even store the apps inside the user object, as a list.
Storing and retrieving the data is more natural, as you can store any kind of object, no matter which are the fields. You can search by user_id to get all the apps that belongs to a user.
On MongoDB you loose anyway the possibility of doing join queries, but in this case I think the basic queries will be retrieving the user and retrieving the apps related to the user. If you plan to do a lot of stuff like "give me the users who have more than two collections with three applications or less on each", you'll have to generate it not as a join query, but as a process in code, and will be less natural than in a relational database and can take more time to process. If you want to search for parameters (e.g. give me all the apps that belong to a particular user; give me all the apps that are of type X), that's quite easy on MongoDB and don't need to use joins.

I'm not sure about the support of MongoDB on Rails. I have use it in Python and JavaScript.

EDIT: Added comment about time when accessing two tables and another MySQL option

Title: Is MongoDB the right choice in my case?


问:
Javascript naming conventions
I am from Java background and am new to JavaScript. I have noticed many JavaScript methods using single character parameter names, such as in the following example.

```<code>doSomething(a,b,c)
</code>```

I don't like it, but a fellow JavaScript developer convinced me that this is done to reduce the file size, noting that JavaScript files have to be transferred to the browser.

Then I found myself talking to another developer. He showed me the way that Firefox will truncate variable names to load the page faster.  Is this a standard practice for web browsers?

What are the best-practice naming conversions that should be followed when programming in JavaScript? Does identifier length matter, and if so, to what extent?

答:
No, not all browsers will automactically shorten the JavaScript to help with performance.

However, in the case of JavaScript, you should not sacrifice code readability/maintainability for gains in processing speed or security because there are tools called obfuscators and other tools called shinkers (or compressors) which were designed for this purpose.

Remember, don't pre-optimize. If your page is loading quickly enough, and you don't have any overly-sensitive content in your JavaScript, don't worry about it. Name your variables with meaningful names. Code readability is highly important for maintainability and should rarely, if ever, be sacrificed.

If you'd like a reference to some good JavaScript coding conventions, I recommend using these.

Title: Javascript naming conventions


问:
What are the advantages to using SQL query builders?
Are there any advantages to using a query builder, rather than using raw SQL?

E.g.

```<code>$q->select('*')
  ->from('posts')
  ->innerJoin('terms', 'post_id')
  ->where(...)
</code>```

vs:

```<code>SELECT * FROM posts WHERE ...
</code>```

I see that many frameworks use these kind of abstraction layers, but I fail to understand the benefits.

答:
Query builders are a pet hate of mine, so much so I wrote my own Framework (Apeel) to avoid using them!

If you use PDO (which I definately recommend you do) then santising the input is handled for you.

Like someone else said, although they do make it easier to switch between databases they tend to support "Lowest common denominator" functionality and will either not support or have poorer performance for more advanced features.

I've been developing systems with databases since around 1986 and in all that time I've rarely encountered a company actually changing the database they use other than when they needed better performance.  If you are changing databases for better performance then it makes a lot more sense to spend your time hand-optimising your queries to get the best out of the new database rather than take the hit of a query builder for the sake of simplicity.

The time spent getting to grips with the qwirks of a query builder (then re-learning when you switch to a better one) would be far more productively spent learning how to optimise your SQL.

Anyway that's why NOT to use one, some people love them though.


问:
Can the JSF 2.0.0 code be converted to JavaScript/HTML5?
I am developing an application using WebSocket to exchange messages; it is based on JSF 2.0.0, but the idea is similar and HTML5 have WebSocket support.

Is the only difference between those language the used tag and the syntax? Is the logic behind it the same?

I wonder if there any converter for this.

答:
I think your general misunderstanding is that JSF 2 and HTML 5 are seperate technology stacks and this doesn't have to be the case.  JSF 2 is a specification for server based lifecycle, server side events and streamlined Ajax based web controls.  In this way it is similar to ASP.NET.  There are many different implementations of this (Eg. Mojarra, MyFaces, etc...) and these can in turn be supplemented by third-party component libraries that enhance the control set (Eg. Primefaces, IceFaces, RichFaces, PrettyFaces, etc...)

A JSF component will be defined by server side code but renders to HTML markup on the web page.  This means that JSF components can render HTML5 and there are real examples of this: http://www.primefaces.org/showcase/ui/fileUploadHome.jsf

So there is really nothing to "convert".  One can create a custom or composite JSF component that renders any HTML5 content that you desire.


问:
How to minimize typos when you code?
I make a lot of typing mistakes when I program. I have a good keyboard writing speed but I try to write faster and in the process end up making typos.

I want to type faster, but make less errors. Can I do something to improve the situation?

答:
Editors such as vim have mapping that allow you to change a word into another word.  For example:

```<code>map teh the
</code>```

will change all instances of teh into the as you type. The user need not even know that they typed "teh" as it will only appear for less than a second before being changed to "the".

Title: How to minimize typos when you code?

Body:
Editors such as vim have mapping that allow you to change a word into another word.  For example:

map teh the

will change all instances of teh into the as you type. The user need not even know that they typed "teh" as it will only appear for less than a second before being changed to "the".


答: The only thing that will make you type correctly more often is to practice.  Or to make errors very painful, as those of us who started on punched-cards might remember - a single keystroke error usually resulted in retyping the entire line.</p>

Title: How to minimize typos when you code?

Body:
I make a lot of typing mistakes when I program. I have a good keyboard writing speed but I try to write faster and in the process end up making typos.

I want to type faster, but make less errors. Can I do something to improve the situation?


答: There's nothing for it but to practise. Jeff Atwood wrote a blog post on the subject a while back. Mavis Beacon software is still around so that's a good place to start, but I'm sure there are plenty of free, online resources to be found.</p>

Title: How to minimize typos when you code?


问:
mercurial or tfs for codeplex?
I've been working on a .NET personal project for a little while now and it's almost ready to go open source.

I've decided (arbitrarily) to host it on codeplex. Codeplex offers TFS or mercurial.

I'm wondering which I should pick. Consider:

I've only ever used subversion.

I'm using VS 2010 express as my IDE.

Tools must be free (so the mercurial client if I go that route).

From what I've been hearing, mercurial sounds interesting but I know very little about it so if there's a learning curve, then I don't want to add too many more learning objectives to the project.

I don't expect any contributors.

So I guess the actual question is, is mercurial easy enough to use with codeplex and does it add anything that the TFS option doesn't?

答:
Mercurial

I like Mercurial provided you install TortoiseHG and VisualHG tools.

The best feature is that you can create a "branch" to try out some funky new code by just copying your enlistment directory in Explorer.  This copy will sync back to Codeplex without changing any settings if all goes well.  If it goes poorly, delete the directory and 'all is forgiven'.

Title: mercurial or tfs for codeplex?


答: Make sure you use auto-completion/Intellisense wisely if you're using an IDE or (I suppose) some text editors. If you use them well, you only have to get the spelling correct once :)</p>

Title: How to minimize typos when you code?


答:
I suppose its a bit obvious, but I think practice makes perfect is what you should remember here. I am not a big time coder in any sense, but I do some work in R, VBA, VB.Net and a bit of C# and you could essentially plot my increase in speed and decrease in errors as a function of time and the number of projects I had done in that language. The first time I wrote something in vb.net to automate excel or fit a model in R it was an ordeal that was full of mistakes, but now I can sit down and bang out simple office automation very quickly and the number of mistakes I make in a fraction of what it was.

I think there is also a bit of a recency effect. If I take a few months off of a particular language (or worst case scenario, coding in general) the first projects I do on my return are quite painful, but it comes back pretty quickly.

Title: How to minimize typos when you code?


问:
Should we do entity-relationship modeling or object-oriented modeling first?
When building an application from scratch, should I start with the object-oriented (OO) model or the entity-relationship (ER) model?</p>

答:
The ER model dictates how the application's data will be persisted, and the OO model decides how that same data will be stored in memory, or while the application is running.  So, Database schema design (ER model) and class stucture design (OO model) are related design considerations, and can usually even be thought about concurrently.  In fact, if you are using an Object-relational mapping (ORM) tool, your ER model and your OO model may be one and the same.  In other words, your classes (OO model) may be annotated in such a way that they, themselves, specify the ER model.

Before designing, though, make sure you have a very good idea of the actual requirements of the software, what it will be used for, how it will be used, and who will use it.  Many developers start thinking about design decisions before they fully understand the needs to be addressed by the product, and end up with a design that is ill-suited for the true purpose of the application.


答:
Without knowing what tools you are using, I can't give specific, detailed advice, but consider using more automated solutions.

Integrated Development Environments will provide you with a number of features that should help alleviate your problems. Examples include code completion for method names and variables, sorted views over the various members of your classes, built-in documentation, and in most cases the ability to spell-check at least your comments. Also, code generation might help with tasks such as importing/including the right files, generating boilerplate code, and so on. Minimizing the amount of typing that you do would minimize the opportunities for you to make typing errors.

Of course, it might be an option to just simply slow down. It's not a race to the finish. It's common knowledge that preventing mistakes early is preferable to finding them later and needing to fix them. If you are using tools that can prevent, detect, or fix mistakes, you'll save time when you produce your outputs - no more typos leading to compile errors, for example.

Title: How to minimize typos when you code?


答:
Don't worry about the file size prematurely.  While it is always a concern, readability and maintainability is more important.

With that said, you should probably be servining minified (e.g., via YUI Compressor) versions of your scripts anyway.

If you're interested in best practices for web development in general, I suggest reading What should every programmer know about web development?

Title: Javascript naming conventions

Body:
I am from Java background and am new to JavaScript. I have noticed many JavaScript methods using single character parameter names, such as in the following example.

```<code>doSomething(a,b,c)
</code>```

I don't like it, but a fellow JavaScript developer convinced me that this is done to reduce the file size, noting that JavaScript files have to be transferred to the browser.

Then I found myself talking to another developer. He showed me the way that Firefox will truncate variable names to load the page faster.  Is this a standard practice for web browsers?

What are the best-practice naming conversions that should be followed when programming in JavaScript? Does identifier length matter, and if so, to what extent?


答:
You might want to try to observe the principle of delaying architectural decisions as long as possible. The thought goes, that you will know more in the future about your problem domain than you do right now - so, any decisions you make today are suspect.

Another good principle to pair this with might be to try to attempt the riskiest parts of your requirements first - the thought being that if you do the easy parts, then find that the risky parts move you in a different direction, you don't have to re-do the easy parts.   Risky here meaning things you aren't sure how you should do them.

Given these two, and given that I often try to approach things from an OO perspective, you might try to start with an OO model of the riskiest parts of your application first, and implement a least possible amount of code that can work that satisfies the risky requirements. Then, begin expanding your OO model as needed to add functionality you are going to need. All the while, you can completely delay your decision on whether to use SQL or NoSQL or flatfiles or cloud storage or whatever ... and you may eventually find you don't want relational at all (obviating the need for an ER model).

Title: Should we do entity-relationship modeling or object-oriented modeling first?

Body: When building an application from scratch, should I start with the object-oriented (OO) model or the entity-relationship (ER) model?</p>


答:
contrary to joshin4colours answer, I say the opposite is true. Intellisense is great as an aide, but it will not improve your typo's. It will just make you target a different set of keywords ;)

so:

practice makes perfect go play a typing game

Title: How to minimize typos when you code?


问:
Why are statements in many programming languages terminated by semicolons?
Is there a reason that a semi-colon was chosen as a line terminator instead of a different symbol?

I want to know the history behind this decision, and hope the answers will lead to insights that may influence future decisions.

答:
FORTRAN used carriage return to delineate statements.  COBOL used period.  LISP didn't use anything, relying on parentheses for everything.  ALGOL was the first language to use semicolon to separate statements.  PASCAL followed ALGOL's lead, using semicolon to separate statements.

PL/I used semicolon to terminate statements.  There is a difference, and it is easily seen in PASCAL.  Ada followed PL/I's lead on this one item, rather than ALGOL's.

Semicolon as statement separator or terminator was quickly accepted by the computer science community as a useful notation, and, as far as I know, every subsequent block-structured language followed ALGOL's lead and used semicolon to separate or terminate statements.

I was told many years ago that BCPL used both semicolon AND carriage return as statement separators/terminators, but I never used the language myself and am unable to verify this.  At some point, the use of carriage return to separate or terminate statements was dropped from the BCPL descendants.  BCPL begat B, B begat C, C begat C++, Java, D and a whole host of things considerably less well-thought-out than PASCAL and Ada.


答:
If your IDE has syntax colouring, most typos will give you immediate visual feedback. When you successfully type int it changes colour as soon as you press space. When you mess up and type nit it does not. The immediacy of this feedback should, if you care about reducing typos, help you to avoid errors.

So three suggestions:

use an IDE that gives you the maximum feedback as you type

use an IDE that autocompletes so you don't have to type so much

pay attention to the quality of your typing and it is likely to improve

Don't worry so much about being fast. Fast will come later. It's true in typing as in code, that while performance is a feature, correctness is mandatory. :-)

Title: How to minimize typos when you code?


答:
This is pretty much pure guess work, but looking at a standard QWERTY keyboard restricted to ASCII values the natural characters for termination/separation would be .!?,:; and carriage returns. of those !?: should be immediately disqualified for taking multiple keys and statement termination is going to be a very common thing. Periods would be disqualified because they are easily confused with decimal points which would make them unnecessarily complicated to be a terminator given the limited space of initial computers. carriage returns would be disqualified after lines of code had potential to be longer than what can be shown on a single line on the screen, so it would be more difficult to read a program when lines had to be scrolled horizontally, or require additional characters to create a continuation on the next line which again adds complexity. this leaves , and ; as options, of those , is used much more often in writing compared to ; so the semicolon is chosen because its the easier to type, less confusing because its adding meaning to a character with limited meaning and less complicated because special cases don't really exist with its use.

The semicolon was chosen because it was the best character based on laziness and simplicity.


问:
Constructor parameter validation in C# - Best practices
What is the best practice for constructor parameter validation?

Suppose a simple bit of C#:

```<code>public class MyClass
{
    public MyClass(string text)
    {
        if (String.IsNullOrEmpty(text))
            throw new ArgumentException("Text cannot be empty");

        // continue with normal construction
    }
}
</code>```

Would it be acceptable to throw an exception?

The alternative I encountered was pre-validation, before instantiating:

```<code>public class CallingClass
{
    public MyClass MakeMyClass(string text)
    {
        if (String.IsNullOrEmpty(text))
        {
            MessageBox.Show("Text cannot be empty");
            return null;
        }
        else
        {
            return new MyClass(text);
        }
    }
}
</code>```

答:
When I used to work in c++, I didn't use to throw exception in constructor because of memory leak problem it can lead to, I had learned it the hard way. Anyone working with c++ knows how difficult and problematic memory leak can be.

But if you are in c#/Java, then you don't have this problem, because garbage collector will collect the memory. If you are using C#, I think it is preferable to use property for nice and consistent way to make sure that data constraints are guaranteed.

```<code>public class MyClass
{
    private string _text;
    public string Text
    {
        get
        {
            return _text;
        }
        set
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentException("Text cannot be empty");
            _text = value;
        }
    }

    public MyClass(string text)
    {
        Text = text;
        // continue with normal construction
    }
}
</code>```

Body:
When I used to work in c++, I didn't use to throw exception in constructor because of memory leak problem it can lead to, I had learned it the hard way. Anyone working with c++ knows how difficult and problematic memory leak can be.

But if you are in c#/Java, then you don't have this problem, because garbage collector will collect the memory. If you are using C#, I think it is preferable to use property for nice and consistent way to make sure that data constraints are guaranteed.

public class MyClass
{
    private string _text;
    public string Text
    {
        get
        {
            return _text;
        }
        set
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentException("Text cannot be empty");
            _text = value;
        }
    }

    public MyClass(string text)
    {
        Text = text;
        // continue with normal construction
    }
}


问:
Becoming a Better Bug-Fixer
I love being a programmer. There, I said it. However, with that said, I've realized lately that I really can't stand bug-fixing. At all.

In fact, while I'm developing something, my productivity is extremely high. Even when writing unit-tests and doing self testing of my development, I'm generally really productive. I can focus well, and I can get tasks done.

However, when QA time comes around and I'm working on fixing bugs, my inspiration takes a massive nosedive. I have to force myself with pretty extreme measures (you know, high BPM music, excessive amounts of caffeine, etc.) to get anything done. My job is usually involved with stepping into an existing massive project and adding new features or fixing bugs, so I can't exactly tell my employer that I need a couple weeks to write unit tests for all of their code :) In addition, the server technology that we often use is very prohibitive to both unit and integration testing, as it has quite a few Java classloader issues. I'm not completely against bug-fixing, sometimes it can be fun, but it's not fun at all when you have to make minor changes and wait 30 seconds to 3 minutes to be able to see if they worked or not (due to the way the system works).

How can I improve my productivity and motivation when bugfixing? Is this something that most programmers deal with?

答:
In this type of a situation, you need some kind of creative challenge.  Normally, it's writing code, but here it isn't.

But, all is not lost.  Work on solving your meta-problems and pour your energy into that.  Why does it take 30 seconds to 3 minutes to get feedback?  How can you shorten that time?  (Maybe you can write some kind of script or utility app that you don't check in that helps you do this).  That's your new problem domain -- your new creative challenge.

Personally, anytime I'm in a defect fixing phase, I identify my biggest barriers to getting it done quickly and painlessly, and I automate what I need to automate to remove those barriers.  This often results in boosted productivity and additions to my personal portfolio to boot.

So, in short, I'd say "always be developing."  :)

Title: Becoming a Better Bug-Fixer


答:
I've been in your shoes.
Build automated tests when and where you can.  It doesn't have to be all at once.  When you find a bug, take a minute to try to program a test case.  If you can't program a test case, write a quick blurb somewhere about how to manually test it, e.g. click-here, type this, etc. and put it into some sort of Knowledge Base.

Debugging can be very tiresome, especially with complicated code you didn't write.  Come up with a goal, "Fix Bug 13533 by Friday".  Then setup a reward if you meet the goal, "Grab a pint with my mates Friday night".  This will help make it a bit more rewarding.

Other than that, sometimes work is just that... work.

Title: Becoming a Better Bug-Fixer

Body:
I love being a programmer. There, I said it. However, with that said, I've realized lately that I really can't stand bug-fixing. At all.

In fact, while I'm developing something, my productivity is extremely high. Even when writing unit-tests and doing self testing of my development, I'm generally really productive. I can focus well, and I can get tasks done.

However, when QA time comes around and I'm working on fixing bugs, my inspiration takes a massive nosedive. I have to force myself with pretty extreme measures (you know, high BPM music, excessive amounts of caffeine, etc.) to get anything done. My job is usually involved with stepping into an existing massive project and adding new features or fixing bugs, so I can't exactly tell my employer that I need a couple weeks to write unit tests for all of their code :) In addition, the server technology that we often use is very prohibitive to both unit and integration testing, as it has quite a few Java classloader issues. I'm not completely against bug-fixing, sometimes it can be fun, but it's not fun at all when you have to make minor changes and wait 30 seconds to 3 minutes to be able to see if they worked or not (due to the way the system works).

How can I improve my productivity and motivation when bugfixing? Is this something that most programmers deal with?


答: If software development is boring, you are doing it wrong.  In other words, it's not a problem with you, but a problem with your platform and process.  Have you considered looking for a position using a dynamic language (e.g. Python, Ruby, JavaScript), where you don't have to wait for server restarts?</p>

Title: Becoming a Better Bug-Fixer


问:
How to respond when you are asked for an estimate?
We, as programmers, are constantly being asked 'How long will it take'?

And you know, the situation is almost always like this:

The requirements are unclear. Nobody has done an in depth analysis of all the implications.

The new feature will probably break some assumptions you made in your code and you start thinking immediately of all the things you might have to refactor.

You have other things to do from past assignments and you will have to come up with an estimate that takes that other work into account.

The 'done' definition is probably unclear: When will it be done? 'Done' as in just finished coding it, or 'done' as in "the users are using it"?

No matter how conscious you are of all these things, sometimes your "programmer's pride" makes you give/accept shorter times than you originally suppose it might take. Specially when you feel the pressure of deadlines and management expectations.

Many of these are organizational or cultural issues that are not simple and easy to solve, but in the end the reality is that you are being asked for an estimate and they expect you to give a reasonable answer. It's part of your job. You cannot simply say: I don't know.

As a result, I always end up giving estimates that I later realize I cannot fulfill. It has happened countless of times, and I always promise it won't happen again. But it does.

What is your personal process for deciding and delivering an estimate? What techniques have you found useful?

答:
Sometimes estimating becomes an enormous challenge for you and your team, especially when we are talking about software project estimation.

Once we had decided to share our experience and our knowledge about software estimation process and defined four distinct types of estimations:

ballpark figure

service estimate

feature estimate

componential estimate

Of course, those types are distinct. Ballpark is what is often called a “guesstimate”. So it's an approximate number or range that gives a general idea of cost and that may help a prospect decide whether they would like to take the discussion further.

As a rule, clients need a ballpark figure at the beginning of the project. And our advise is: discussion of the project and providing ballpark figures should just be steps well towards receiving componential estimate (which is flexible, one can make use of componential type estimate for the whole development process. No need to re-estimate from scratch when you want to add, remove or replace features, services etc).

Everyone should keep in mind the risks that come with software development estimating: underestimating, overestimating, total epic fail scenario etc.

You can read more on our blog!

http://blog.lemberg.co.uk/project-management/software-estimation-process/

Hope this information will help you!