答:
The main difference being that short int takes 2 bytes of memory while int takes 4 bytes, and short int has a lesser value, but we could also call this to make it even smaller:

This is incorrect. You can't make assumptions about how many bytes each type holds, other than char being one byte and at least 8 bits per byte, along with each type's size being greater than or equal to the previous.

The performance benefits are incredibly minuscule for stack variables - they'll likely be aligned/padded anyway.

Because of this, short and long have practically no use nowadays, and you're almost always better off using int.

Of course, there's also stdint.h which is perfectly fine to use when int doesn't cut it. If you're ever allocating huge arrays of integers/structs then an intX_t makes sense as you can be efficient and rely on the size of the type. This is not at all premature as you can save megabytes of memory.


问:
Structuring database for multi-object "activity" and "following" functionalities
I am working on a web application which operate with different types of objects such as user, profiles, pages etc. All objects have unique object_id.

When objects interact it may produce "activity", such as user posting on the page or profile. Activity may be related to multiple objects through their object_id.

Users may also follow "objects" and they need to be able to see stream of relevant activity.

Could you provide me with some data structure suggestions which would be efficient and scalable? My goal is to show activity limited to the objects which user is following I am not limited by relational databases.

Update

As I'm getting advices on ORM and how index things, I'd like to again, stress my question. According to my current design model the database structure looks like this:

As you can see - it's quite easy to implement database like that. Activity and Follower tables do contain much larger amount of records than the upper level but it's tolerable.

But when it comes for me to create a "timeline" table, it becomes a nightmare. For every user I need to reference all the object activities which he follows. In terms of records it easily gets out of control.

Please suggest me how to change this structure to avoid timeline creation and also be abel to quickly retrieve activity for any given user. Thanks.

答:
It's hard to say without knowing too much more, but it sounds like you want something very generic. Maybe something like this would help:

```
activity
--------
  activity_id  - the ID of the activity
  participating_object_id - ID of a participating object
  activity_type_id - ID of the Type of activity
  activity_datetime - When this activity occurred
  data - context data of the activity
```

This would let you have things like:

```
activity_id | participating_object_id | activity_type_id | date  | data
------------+-------------------------+------------------+-------+-----
1           | 2                       | 3                | ...   | this is a post
1           | 84                      | 3                | ...   | user@somewhere.com
```

This describes an activity instance (ID #1): a user (object #84, context data "user@somewhere.com") created a posting on a forum (activity type 3) whose object ID is 2, and the posting contained the text "this is a post".

You'll probably need to expand on this as your situation requires.

...actually, now that I think about it, the data column is probably not needed, since you can get any data you want from your base object table (whatever it looks like) by querying it using the values in participating_object_id.

ContentLicense: CC BY-SA 3.0

Body:
It's hard to say without knowing too much more, but it sounds like you want something very generic. Maybe something like this would help:

activity
--------
  activity_id  - the ID of the activity
  participating_object_id - ID of a participating object
  activity_type_id - ID of the Type of activity
  activity_datetime - When this activity occurred
  data - context data of the activity

This would let you have things like:

activity_id | participating_object_id | activity_type_id | date  | data
------------+-------------------------+------------------+-------+-----
1           | 2                       | 3                | ...   | this is a post
1           | 84                      | 3                | ...   | user@somewhere.com

This describes an activity instance (ID #1): a user (object #84, context data "user@somewhere.com") created a posting on a forum (activity type 3) whose object ID is 2, and the posting contained the text "this is a post".

You'll probably need to expand on this as your situation requires.

...actually, now that I think about it, the data column is probably not needed, since you can get any data you want from your base object table (whatever it looks like) by querying it using the values in participating_object_id.


问:
Is it a good practice to use smaller data types for variables to save memory?
When I learned the C++ language for the first time I learned that besides int, float etc, smaller or bigger versions of these data types existed within the language. For example I could call a variable x

```<code>int x;
or
short int x;
</code>```

The main difference being that short int takes 2 bytes of memory while int takes 4 bytes, and short int has a lesser value, but we could also call this to make it even smaller:

```<code>int x;
short int x;
unsigned short int x;
</code>```

which is even more restrictive.

My question here is if it's a good practice to use separate data types according to what values your variable take within the program. Is it a good idea to always declare variables according to these data types?

答:
The OP said nothing about the type of system they are writing programs for, but I assume the OP was thinking of a typical PC with GB's of memory since C++ is mentioned.  As one of the comments says, even with that kind of memory, if you have several million items of one type -- such as an array -- then the size of the variable can make a difference.

If you get into the world of embedded systems -- which is not really outside the scope of the question, since the OP doesn't limit it to PCs -- then the size of data types very much matters.  I just finished a quick project on a 8-bit microcontroller which has only 8K words of program memory and 368 bytes of RAM.  There, obviously every byte counts.  One never uses a variable bigger than they need (both from a space standpoint, and code size -- 8-bit processors use a lot of instructions to manipulate 16 and 32-bit data).  Why use a CPU with such limited resources?  In large quantities, they can cost as little  as a quarter.

I'm currently doing another embedded project with a 32-bit MIPS-based microcontroller which has 512K bytes of flash and 128K bytes of RAM (and costs around $6 in quantity).  As with a PC, the "natural" data size is 32-bits.  Now it becomes more efficient, code-wise, to use ints for most variables instead of chars or shorts.   But once again, any type of array or structure must be considered whether smaller data types are warranted.  Unlike compilers for larger systems, it is more likely variables in a structure will be packed on an embedded system.  I take care to always try to put all 32-bit variables first, then 16-bit, then 8-bit to avoid any "holes".


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Class naming conventions that demonstrate a poor understanding of the abstraction they're attempting to create. Or that don't define an abstraction at all.

An extreme example comes to mind in a VB class I saw once that was titled Data and was 30,000+ lines long...in the first file. It was a partial class split into at least half a dozen other files. Most of the methods were wrappers around stored procs with names like FindXByYWithZ().

Even with less dramatic examples, I've sure we've all just 'dumped' logic into a poorly conceived class, given it a wholly generic title, and regretted it later.

ContentLicense: CC BY-SA 2.5


问:
Why is naming a table's Primary Key column "Id" considered bad practice?
My t-sql teacher told us that naming our PK column "Id" is considered bad practice without any further explanations.

Why is naming a table PK column "Id" is considered bad practice?

答:
This question has been beaten over and over again, but I thought that I too would add my opinion.

I use id to mean that that is the identifier for each table, so when I join to a table and I need the primary key I automatically join to the primary key.

The id field is an autoincrement, unsigned (meaning that I never have to set its value and it cannot be negative)

For foreign keys, I use tablenameid (again a matter of style), but the primary key I join to is the id field of the table, so the consistency means I can always check queries easily

id is short and sweet too

Additional convention - use lower case for all table and column names, so no issues to be found due to case


问:
Is the creation of brand new software generally a major part of most programming jobs?
I have worked in software development for over 10 years now, and it's dawning on me that I rarely get to create anything "new".  I realize that "new" is a vague term, but I would define it as anything from an obvious new large-scale project to a new large feature in an existing project (say something that would require some thought into its design, and that might take 2 weeks or more to complete).  Maybe a rough guideline is something is new if it requires a written spec.  I think most programmers know what I'm talking about - you're in the zone, writing a ton of code at a fast pace.

Anyway, thinking back to what I've done, I'd estimate that less than 10% of my time is spent on "new" work.  There are things like "adapt this existing system to work in this new environment", which certainly requires a lot of planning, but the actual coding and "new stuff" comes down to making tiny changes in many places throughout the code.  Likewise for small feature requests - if I know what to do, these can often be finished in under an hour, and if I don't, it's just a lot of reading code and figuring out what to do (which frustrates me because I learn much better by doing, not by reading).

In general I feel like I am not really creating anything most of the time.  I kind of assumed that this was the case at most places - a new product would come out rather quickly and at that point everyone would be excited and banging out the code at a fast pace, but then once live it moves into maintenance mode, where few of the subsequent changes would be considered "new & creative".

Am I wrong?  Am I accurately describing most programming jobs, or do most programmers feel like they are often creating new things?

答:
You will spend your time creating new functionality and changing the functionality of existing code in order to conform to the new specification.

Others are calling that maintenance but that's a horrible term. It's a redesign and a refactoring or re-coding of the software to make it conform to a new idea of what the program should do.


问:
Whose responsibility is a bug fix patch?
A situation that has arisen several times in open source projects goes like this:

I notice a bug in our deployment, and figure out a quick hack patch. (For example, simply commenting out code that we don't actually need.)

I spend a little bit of extra effort to figure out the real bug, come up with a patch, and submit it via a Git pull request, or similar.

My pull request is rejected. Perhaps the patch was imperfect (eg, included lines it shouldn't have), perhaps it violated coding style, perhaps it had other ramifications. Or maybe I did something wrong in Git - the pull request should have been rebased or something. A maintainer provides feedback about how to improve the patch, and requests that I resubmit it.

At this point I'm confused about how far I should proceed. As far as I'm concerned, I don't have a problem: I fixed it back in step 1. I've reported the issue, I've even taken steps to fix it for others. But I don't feel that it's "my" pull request, so I don't feel that responsibility for improving the patch should come to me.

One particular situation that irks me is after discussion about the failings of my patch, we reach agreement on a mailing list about what the correct patch would be (ie, how it should behave, sometimes including every line of code spelt out). Then, it is still presumed to be my responsibility to actually generate and submit the patch.

Is there a standard etiquette in these situations? How are they resolved? Is my reaction unusual? How far are you expected to go to get your bug fix accepted?

(Note when I say "open source project", some of these are very small, but may not be hobbies - simply small software projects which are of use to several organisations, who commit developer resources to working on them. In case the obvious answer is "fix the patch and resubmit", understand that I have responsibilities to my employer to work on stuff that is of benefit to them. Spending time fixing a bug that doesn't affect us would be wrong...)

答:
As far as I'm concerned, if you find a bug or have an enhancement request, are not a contributor to the project, and have submitted a defect report through the appropriate channels, you are done. In terms of giving back to the community, anyone who is using an open source project and finds a defect should report it.

Attempting to find a solution, design it, and implement it is a bonus to the project. If you have done this, it might be a good idea to submit it, either via a pull request or perhaps sending file deltas to the development team along with the defect report or enhancement request to give them something to work with. However, they are under no obligation to accept your contribution to the project.

Expecting a user to contribute patches seems wrong, to me. It's fairly easy to participate in a discussion about a problem, but it's a much larger time investment to come up with a solution. No project should expect non-contributors to become a contributor just to fix a single issue.


答:
Proceed as far as you're willing to put up with it. It'd be nice to fix up your patch and share it with the world in the main trunk, but if the maintainer doesn't want it, shrug. You can post somewhere your problem, and the patch to deal with it, so that others in the same boat can search for a solution.

And you're not without problem. Your patch won't be in the next upgrade. So you'll have to repatch, and hope it works or massage it into place, whenever you grab a new version. So getting it into the main project will be saving you, and your company, time in the long run.

It's a pain to you, but you're contributing to the community. I certainly appreciate all the work contributors put in. It's not like quality software just magically genesis's from the masses. Someone has to do the work. (So who's awesome? You're awesome). If you don't feel up for it, announce to the community that while you appreciate the discussion of how it should be, you're simply too busy to do it. I mean, what are they going to do? Cut your wages?

Title: Whose responsibility is a bug fix patch?

Body:
A situation that has arisen several times in open source projects goes like this:

I notice a bug in our deployment, and figure out a quick hack patch. (For example, simply commenting out code that we don't actually need.)

I spend a little bit of extra effort to figure out the real bug, come up with a patch, and submit it via a Git pull request, or similar.

My pull request is rejected. Perhaps the patch was imperfect (eg, included lines it shouldn't have), perhaps it violated coding style, perhaps it had other ramifications. Or maybe I did something wrong in Git - the pull request should have been rebased or something. A maintainer provides feedback about how to improve the patch, and requests that I resubmit it.

At this point I'm confused about how far I should proceed. As far as I'm concerned, I don't have a problem: I fixed it back in step 1. I've reported the issue, I've even taken steps to fix it for others. But I don't feel that it's "my" pull request, so I don't feel that responsibility for improving the patch should come to me.

One particular situation that irks me is after discussion about the failings of my patch, we reach agreement on a mailing list about what the correct patch would be (ie, how it should behave, sometimes including every line of code spelt out). Then, it is still presumed to be my responsibility to actually generate and submit the patch.

Is there a standard etiquette in these situations? How are they resolved? Is my reaction unusual? How far are you expected to go to get your bug fix accepted?

(Note when I say "open source project", some of these are very small, but may not be hobbies - simply small software projects which are of use to several organisations, who commit developer resources to working on them. In case the obvious answer is "fix the patch and resubmit", understand that I have responsibilities to my employer to work on stuff that is of benefit to them. Spending time fixing a bug that doesn't affect us would be wrong...)


答:
As scarfridge commented, this is a

Classic case of premature optimization.

Trying to optimise for memory usage might impact other areas of performance, and the golden rules of optimisation are:

The First Rule of Program Optimisation: Don't do it.

The Second Rule of Program Optimisation (for experts only!): Don't do it yet."

— Michael A. Jackson

In order to know whether now is the time to optimise requires benchmarking and testing. You need to know where your code is being inefficient, so that you can target your optimisations.

In order to determine whether the optimised version of the code is actually better than the naive implementation at any given time, you need to benchmark them side-by-side with the same data.

Also, remember that just because a given implementation is more efficient on the current generation of CPU's, doesn't mean it will always be so. My answer to the question Is micro-optimisation important when coding? details an example from personal experience where an obsolete optimisation resulted in an order of magnitude slowdown.

On many processors, unaligned memory accesses are significantly more costly than aligned memory accesses. Packing a couple of shorts into your struct may just mean that your program has to perform pack/unpack operation every time you touch either value.

For this reason, modern compilers ignore your suggestions. As nikie comments:

With standard packing/alignment compiler settings, the variables will be aligned to 4 byte boundaries anyway, so there might not by any difference at all.

Second guess your compiler at your peril.

There is a place for such optimisations, when working with terabyte datasets or embedded micro-controllers, but for most of us, it isn't really a concern.

Title: Is it a good practice to use smaller data types for variables to save memory?

Body:
When I learned the C++ language for the first time I learned that besides int, float etc, smaller or bigger versions of these data types existed within the language. For example I could call a variable x

```<code>int x;
or
short int x;
</code>```

The main difference being that short int takes 2 bytes of memory while int takes 4 bytes, and short int has a lesser value, but we could also call this to make it even smaller:

```<code>int x;
short int x;
unsigned short int x;
</code>```

which is even more restrictive.

My question here is if it's a good practice to use separate data types according to what values your variable take within the program. Is it a good idea to always declare variables according to these data types?


答:
AFAIK, the open source way is that the responsability of fixing bugs is left to the one who care enough about the bug to handle the burden to ensure it is fixed. Depending on the circumstances, I've done everything from simply ignoring an issue to battle up (providing patches and arguing so that they are accepted) to ensure it was fixed.

Everything is right, just don't let people managing the project expect the wrong thing from you (i.e. give them hope that you'll fix the issue properly by discussion options and then do nothing), they probably are aware of more issues than they can handle themselves and will try to make a recurrent contributor of you if they can.


答:
The original bug may only affect you, so it's very much in your interest to get the submission in by doing whatever is required to bring your patch into compliance.  Otherwise the next version you pull (because you need other fixes) will be missing your fix.

You don't want to maintain a list of patches you need to apply every time you pull a new copy of the project - it's just too much trouble.  Take a bit of extra time and get it fixed permanently so you won't have to deal with it again.


问:
Should I include dependencies for which I have the source as projects in my solution?
We have various projects in source control for web and desktop applications. Invariably, many of them use third-party open source projects or even common libraries within our organization as dependencies.

Should we include the full projects of these dependencies in our various solutions? Or should we just include the .dll reference (or equivalent compiled binary) and maintain the source for said dependency elsewhere (say, for debugging purposes only)?

I'm specifically thinking of .NET projects and solutions in Visual Studio, but feel free to replace those terms with JAR or whatever equivalent in other languages and frameworks.

To further specify, I'm asking if a [fictional] Invoice Payments Web App solution tree should look like this:

InvoicePaymentsWeb

InvoicePaymentsDataModel

InvoicePaymentsServices

RickSoftUltraDataGrid

MyCompanyCommonWebLib

And you could individually compile (or change) the various dependencies since they exist entirely within your solution. As opposed to just having the first three projects, referencing the compiled DLLs of the other two, and having the source for the other two exist elsewhere on your machine (or elsewhere in source control).

I'm wondering if this wouldn't potentially fracture the development and/or maintenance of the various dependencies since each solution could have its own specific changes to the source, unless the underlying source control handled sharing the projects internally. What other problems might exist? Would there be any benefit?

答:
Maintaining external sources doesn't really add that much value. If you use particular version of library, it should be enough if you have said binary in your repository. However, if you'll make any changes to library (without making it go live/public - say you needed to add something specific to your company) then it makes sense to have modified sources as part of code base (in fact, you should store them somewhere). If that's the case, such sources should be at top level, just as your libraries directory is:

```<code>Invoices
    Invoices.DataAccess
    Invoices.Reports.Templates
    Invoices.View
    Libraries
    LibrariesSources
    ...
</code>```

Naturally, compiled binaries of changed library would go to Libraries directory and will be referenced from there (as opposed to keeping them in say LibrariesSources\ComplexMath\bin\Release).

Body:
Maintaining external sources doesn't really add that much value. If you use particular version of library, it should be enough if you have said binary in your repository. However, if you'll make any changes to library (without making it go live/public - say you needed to add something specific to your company) then it makes sense to have modified sources as part of code base (in fact, you should store them somewhere). If that's the case, such sources should be at top level, just as your libraries directory is:

Invoices
    Invoices.DataAccess
    Invoices.Reports.Templates
    Invoices.View
    Libraries
    LibrariesSources
    ...

Naturally, compiled binaries of changed library would go to Libraries directory and will be referenced from there (as opposed to keeping them in say LibrariesSources\ComplexMath\bin\Release).


问:
Where does my database schema live in MVC?
I'm starting to check in the SQL files for creating/maintaining our database. Previously SQL files were kept totally separate from our codebase's version control.

I'd like to pragmatically store my database construction/manipulation files with my other code. Do they make the most sense in a subdirectory of my Models or as a separate directory somewhere?

For the most part the SQL statements are the data my Models access, but some other stuff is maintenance scripts ect; stuff that doesn't pragmatically fit into my MVC folder structure.

答:
No.  Your SQL files either define your Schema or they define your data access.

The data retrieved from SQL files are not your model either, or rather database record sets should not be your model.  There should be a level of translation that converts your record sets into data suitable for the Model.

In an ideal scenario your Model will be agnostic of data access logic and should mereley contain data that is pertinent to one or more Views as well as view state information as well.

Your Controller should bridge the gap between the View and the data contained in the Model such that only the Controller is concerned with data access matters.

On another note, if your SQL is NOT code then what is it?  You are right to store SQL in version control because they define your application as much as anything.


问:
Common test cases for XML schema validator
I just wrote my first SAX-based (Java) XML schema validator, where you pass it a schema URL (pointing to the .xsd file), and an XML instance, and it determines whether or not that instance is valid or not.

I'm now looking to write several unit tests for the validator (TDD people, I know, I know!) and was wondering what were some common reasons why XML fails validation.

There are so many elements and attributes in this schema, I could literally write thousands of test cases.  I figured someone here might know of a way to simplify them all down to a manageable set.

答:
You might want to come up with more generic types of errors, rather than element-specific errors (unless you have specific elements that actually need that kind of testing). Some of the ones that I would recommend, just off the top of my head:

Elements in the incorrect order.

Missing mandatory elements.

Invalid lengths of strings on elements that have a length limit.

Invalid element value for an enum-type.

Add children when the parent has xsi:nil="true".

Have no children when child elements are required.

These are the types of validation errors I encounter most frequently on my current project. They can happen to almost any element, so it doesn't matter if the schema has dozens of elements or thousands.


答: We keep each iteration's sql migration scripts in a big ugly .sql file that lives in TFS.  </p>

Title: Where does my database schema live in MVC?

Body:
I'm starting to check in the SQL files for creating/maintaining our database. Previously SQL files were kept totally separate from our codebase's version control.

I'd like to pragmatically store my database construction/manipulation files with my other code. Do they make the most sense in a subdirectory of my Models or as a separate directory somewhere?

For the most part the SQL statements are the data my Models access, but some other stuff is maintenance scripts ect; stuff that doesn't pragmatically fit into my MVC folder structure.


答:
There is a situation where sticking "ID" on every table isn't the best idea:  the USING keyword, if it's supported.  We use it often in MySQL.

For example, if you have fooTable with column fooTableId and barTable with foreign key fooTableId, then your queries can be constructed as such:

```<code>SELECT fooTableId, fooField1, barField2 FROM fooTable INNER JOIN barTable USING (fooTableId)
</code>```

It not only saves typing, but is much more readable compared to the alternative:

```<code>SELECT fooTable.Id, fooField1, barField2 FROM fooTable INNER JOIN barTable ON (fooTable.Id = barTable.foTableId)
</code>```

Title: Why is naming a table's Primary Key column "Id" considered bad practice?

Body:
My t-sql teacher told us that naming our PK column "Id" is considered bad practice without any further explanations.

Why is naming a table PK column "Id" is considered bad practice?

Body:
There is a situation where sticking "ID" on every table isn't the best idea:  the USING keyword, if it's supported.  We use it often in MySQL.

For example, if you have fooTable with column fooTableId and barTable with foreign key fooTableId, then your queries can be constructed as such:

SELECT fooTableId, fooField1, barField2 FROM fooTable INNER JOIN barTable USING (fooTableId)

It not only saves typing, but is much more readable compared to the alternative:

SELECT fooTable.Id, fooField1, barField2 FROM fooTable INNER JOIN barTable ON (fooTable.Id = barTable.foTableId)


答:
I always have a "Dependancies" folder that simply has all the dll's.

There is no need to have the full source of third party libraries unless you plan to modify the code in some way specfic to your needs.

Edit: and it should be in source control!

Title: Should I include dependencies for which I have the source as projects in my solution?

Body:
We have various projects in source control for web and desktop applications. Invariably, many of them use third-party open source projects or even common libraries within our organization as dependencies.

Should we include the full projects of these dependencies in our various solutions? Or should we just include the .dll reference (or equivalent compiled binary) and maintain the source for said dependency elsewhere (say, for debugging purposes only)?

I'm specifically thinking of .NET projects and solutions in Visual Studio, but feel free to replace those terms with JAR or whatever equivalent in other languages and frameworks.

To further specify, I'm asking if a [fictional] Invoice Payments Web App solution tree should look like this:

InvoicePaymentsWeb

InvoicePaymentsDataModel

InvoicePaymentsServices

RickSoftUltraDataGrid

MyCompanyCommonWebLib

And you could individually compile (or change) the various dependencies since they exist entirely within your solution. As opposed to just having the first three projects, referencing the compiled DLLs of the other two, and having the source for the other two exist elsewhere on your machine (or elsewhere in source control).

I'm wondering if this wouldn't potentially fracture the development and/or maintenance of the various dependencies since each solution could have its own specific changes to the source, unless the underlying source control handled sharing the projects internally. What other problems might exist? Would there be any benefit?


问:
Noobie wants to use source control, how would you guide them?
Let's say you know of an anonymous noobie that wants to be lead upon the path of righteousness.  This noobie wants to use some sort of source control tools simply for the experience of using source control tools (and possibly for whatever benefits they bring along with them).

To constrain things further (and to make this possibly even more noobie-tastic), let's say they're stuck in windows developing in visual studio.

How would you guide your neophyte?

答: Give them a copy of TortoiseSVN for a client and CollabNet's SVN server for a server, and have them put their My Documents folder under Subversion control.  As the old joke says, there's no place like $HOME, and living entirely under source control for a few months is an experience they'll never forget.  Plus, when they learn to check in frequently, they'll find that source control is a fantastic backup system.</p>


问:
How do I set up a source code control system for myself?
I program on my desktop in my office, but also sometimes at home in a different room on my laptop, and even away from home.  What I need is a system that automatically or on-demand syncs my work from one to the other, at need.

I do not have a home network setup, and although I guess I could do it, that would be a question for another board, perhaps.  I've thought about some kind of system that would keep the source code in the cloud, but I don't know enough about this to get started.  I need a kind of free or cheap way to do this.

I work in .NET (Windows Phone 7, in fact).

答: If privacy of your code is not as issue then Google Code might a viable solution. It takes care of the hosting part and it is free and fairly easy to setup. It supports Subversion, Mercurial and Git, which all have Windows clients. It also integrates with Google ID's so you can easily add contributors to the project. I host my hobby projects there using Mercurial. I have the TortoiseHg client installed on both my home and work computer, so I could work on my projects during breaks.</p>


答: Source code is useful only when you need to modify something on the third party library. Keeping the binaries on the source control is better than having the whole source code, but using tools like nuget for. Net and mavem for java is much better, because it can resolve the whole dependency tree when you need to update the binaries. </p>


答: Why not use a ORM that can build the scheme for you around your classes? This way you can workout the details at a higher level of abstraction, let the ORM design the schema and then review what its done to change/tweak it based on performance.  </p>

Title: Structuring database for multi-object "activity" and "following" functionalities

Body:
I am working on a web application which operate with different types of objects such as user, profiles, pages etc. All objects have unique object_id.

When objects interact it may produce "activity", such as user posting on the page or profile. Activity may be related to multiple objects through their object_id.

Users may also follow "objects" and they need to be able to see stream of relevant activity.

Could you provide me with some data structure suggestions which would be efficient and scalable? My goal is to show activity limited to the objects which user is following I am not limited by relational databases.

Update

As I'm getting advices on ORM and how index things, I'd like to again, stress my question. According to my current design model the database structure looks like this:

As you can see - it's quite easy to implement database like that. Activity and Follower tables do contain much larger amount of records than the upper level but it's tolerable.

But when it comes for me to create a "timeline" table, it becomes a nightmare. For every user I need to reference all the object activities which he follows. In terms of records it easily gets out of control.

Please suggest me how to change this structure to avoid timeline creation and also be abel to quickly retrieve activity for any given user. Thanks.


问:
How can one best avoid writing bloated GUI code?
I find whenever I work with GUI code, the code tends to bloat faster then other kinds of code. It also seems harder to refactor. Whereas in other kinds of code I can refactor pretty easily -- I find I can decompose a larger class into smaller pieces of functionality -- with most GUI frameworks I'm often bound to a framework that requires my widget/control/whatever class to implement a lot more things more directly in the widget/control/whatever. Sometimes this is due to needing to either (a) inherit off of some base widget/control/thing or (b) need access to protected methods.

I typically also have to, for example, respond to a large variety of inputs via signals/events/whatever from the framework to implement all the modes of interacting with the user. I might need in one GUI widget/control to handle a large variety of input/output that might include:

a right click/context menu

reacting to selections from the context menu -- which may be many

a special way to paint the GUI

react to keyboard input

buttons, checkboxes,

etc etc

... all the while manage the classes under the GUI representing business logic.

A simple straight-forward GUI can have its code grow pretty quickly, even when seperating out buisiness logic and using MVC, I find GUI code is a big magnet for change.

Is there any way to manage GUI code in a sane way and avoid letting it become a broken window? Or is a mass of random event handlers/overridden methods really the best we can do for GUI code?

答:
For some reason GUI code creates a blind spot in developers about separation of concerns.  Maybe it's because all the tutorials lump everything into one class.  Maybe it's because the physical representation makes things seem more closely coupled than they are.  Maybe it's because classes get built up slowly so people don't recognize they need refactoring, like the proverbial frog being boiled by slowly turning up the heat.

Whatever the reason, the solution is to make your classes a lot smaller.  I do this by continually asking myself if it's possible to put what I'm typing into a separate class.  If it's possible to put into another class, and I can think of a reasonable and simple name for that class, then I do it.


答:
ID is bad for the following reasons:

If you do a lot of reporting queries you always have to alias the columns if you want to see both. So it becomes a waste of time when you could name it properly to begin with.  These complex queries are hard enough (I write queries that can be hundreds of lines long) without the added burden of doing unnecessary work.

It is subject to causing code errors. If you use a database that allows the use of the natural join (not that I think you should ever use that but when features are available somebody will use them), you will join on the wrong thing if you get a developer that uses it.

If you are copying joins to create a complex query, it is easy to forget to change the alias to the one you want and get an incorrect join. If each id is named after the table it is in, then you will usually get a syntax error. It is also easier to spot if the join ina complex query is incorrect if the pPK name and the FK name match.


答:
There is one tenet that makes open source culture easier to understand:  the person who does the work decides what to work on.  This is one of its appeals compared to developers' day jobs.  Your #1 priority might be #50 on their backlog.  If you don't fix your pull request, eventually it will probably trickle up to the top and they will take care of it.  However, if you make it easy enough for them, they will take care of it now.

The other reason they ask you to fix your pull request is more magnanimous.  They want you to get credit for your contribution, small as it may be.  If you do the fixing, your name is the one in the author field of the commit.  Most people are proud enough of their contribution to want to see it through, so the maintainers' default modus operandi is to let them.

As far as your responsibility to your employer, if your business is relying on this code you're not doing them a disservice.  Employers know the benefit of a workman taking time to sharpen his tools.


答:
Conjunctions in method names:

public void addEmployeeAndUpdatePayrate(...)

public int getSalaryOrHourlyPay(int Employee) ....
```

Clarification: The reason this rings alarm bells is that it indicates the method likely violates the single responsibility principle.

Title: Which things instantly ring alarm bells when looking at code?

Body:
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

Body:
Conjunctions in method names:

public void addEmployeeAndUpdatePayrate(...)

public int getSalaryOrHourlyPay(int Employee) ....

Clarification: The reason this rings alarm bells is that it indicates the method likely violates the single responsibility principle.


问:
Understanding the problem when things break in production
Scenario:

You push to production

The push broke multiple things

That same build did not break qa or dev

As a developer, you don't have prod access.

There is lots of pressure from above to get things working agian.

Specifics:

PHP/MVC application that is API-driven in Zend.

Deployed to a few servers.

My question:

While investigating, lets say I have a hunch that something is wrong.  But, I don't know for sure.  And, of course, I can't test things in production.  If I have a suggested fix based on that hunch, would it be wise to try and apply it and see if it works, before understanding what the problem is?

答:
While your environment is PHP, I have done a presentation on how to think about it for Java: http://www.infoq.com/presentations/maintaining-production-java-apps

The core issues are the same - to understand possible choke points to troubleshoot the situation: network, filesystem access, log files, deadlocks, etc. Also, to know how to ask the right questions: "System down" - "What specifically do you mean: Is web page slow, is there specific error message, is there timeout", etc.

Plus there are some tools to make troubleshooting easier: Wireshark for network troubleshooting is an absolute best and is worth learning. Others depend on the O/S you use. For Windows, anything from SysInternal (now part of Microsoft) is brilliant. For Unix/Linux, look at truss/strace.

On access to production, operations group should either know how to use those tools/techniques or you have a business case for them (together with you) to learn how to use them. After that, they need a specific set of troubleshooting protocols to run when problem happens, so you could do your analysis offline.


问:
Why do we need private variables?
Why do we need private variables in classes?

Every book on programming I've read says this is a private variable, this is how you define it but stops there.

The wording of these explanations always seemed to me like we really have a crisis of trust in our profession. The explanations always sounded like other programmers are out to mess up our code. Yet, there are many programming languages that do not have private variables.

What do private variables help prevent?

How do you decide if a particular property should be private or
not? If by default every field SHOULD be private then why are there
public data members in a class?

Under what circumstances should a variable be made public?

答:
I'm going to talk about the value of encapsulation from a different perspective using a real example.  Quite some time ago (early 80s) a game was written for the Radio Shack Color Computer called Dungeons of Daggorath.  Some years ago, Richard Hunerlach ported it from a paper assembler listing to C/C++ (http://mspencer.net/daggorath/dodpcp.html).   Some time later, I got the code and began to re-factor it to give better encapsulation, (http://dbp-consulting.com/stuff/).

The code was already factored into different objects to handle scheduling, video, user input, dungeon creation, monsters, etc. but you could definitely tell that it was ported from assembler.  My biggest task was to increase encapsulation.  By that I mean to get different parts of the code to get their noses out of each other's business.  There were many places for example, that would change video variables directly to have some effect.  Some did it with error checking, some not, some had subtly different ideas of what changing that thing meant.  There was much duplication of code.  Instead, the video section needed to have an interface to accomplish the desired tasks, and the code to do it could be all in one place, one idea, one place to debug.  That sort of thing was rampant.  Every object directly accessed every other object and code was duplicated everywhere.

As the code began to get teased apart, bugs that hadn't even been diagnosed went away.  The code became higher quality.  Each task became the responsibility of one place in the code and there was only one place to get it right.  (I still find more every time I make another pass through the code.)

Everything that is visible about your code is your interface.  Whether you mean it to be or not.  If you limit visibility as much as possible then you won't be tempted to put code in the wrong place later.  It makes it obvious what part of the code is responsible for which data.  It makes for better, cleaner, simpler, more elegant design.

If you make an object responsible for its own data, and provide interfaces to everyone else that needs something to happen, your code gets a LOT simpler.  It just falls out.  You have small simple routines that do only one thing.  Less complexity==less bugs.

Title: Why do we need private variables?


答:
One possibility is to use "inheritance", esp. if the objects you refer to have common fields. The schema looks like this:

```<code>followables
    followable_id      primary key
    -- common fields

users
    user_id            primary key references followables(followable_id)
    -- user specific fields

pages
    page_id            primary key references followables(followable_id)
    -- page specific fields

...

random_entities
    ...
    followed_id        references followables(followable_id)
</code>```

This means that both pages and users "are" followables, have followables' attributes and can be referenced alike.

ORMs often create schemas like this to model inheritance, and handle the joining for you.

Do not worry about inefficiency until you can prove it is a problem.

wrt. to efficiency. Write a simple SQL script that inserts test information up to the number of rows you deem you need. Write your queries (remember, you don't want to query your entire timeline, you will normally LIMIT your queries), check their execution speed- with the stuff you mention I'm guessing the performance will be satisfactory. If not, post your queries and the outputs of EXPLAIN.

Body:
One possibility is to use "inheritance", esp. if the objects you refer to have common fields. The schema looks like this:

followables
    followable_id      primary key
    -- common fields

users
    user_id            primary key references followables(followable_id)
    -- user specific fields

pages
    page_id            primary key references followables(followable_id)
    -- page specific fields

...

random_entities
    ...
    followed_id        references followables(followable_id)

This means that both pages and users "are" followables, have followables' attributes and can be referenced alike.

ORMs often create schemas like this to model inheritance, and handle the joining for you.

Do not worry about inefficiency until you can prove it is a problem.

wrt. to efficiency. Write a simple SQL script that inserts test information up to the number of rows you deem you need. Write your queries (remember, you don't want to query your entire timeline, you will normally LIMIT your queries), check their execution speed- with the stuff you mention I'm guessing the performance will be satisfactory. If not, post your queries and the outputs of EXPLAIN.


答:
Short answer: Not if you have a choice.

Long answer: If you don't understand the problem, there are several risks involved in such a patch:

You could break something else, which could even be less reproducible.

You could just mask the problem, making it harder to notice and reproduce (which makes it worse)

You're throwing potential domestic experience away - experience which could make you a better programmer, and at the same time more valuable to your company (i.e. a potential future raise).

On the other hand, I see no harm in first checking if your hypothesized fix works, and if it does - then dig deeper and find out the real reason or other possibly better ways to solve the problem.

Title: Understanding the problem when things break in production

Body:
Scenario:

You push to production

The push broke multiple things

That same build did not break qa or dev

As a developer, you don't have prod access.

There is lots of pressure from above to get things working agian.

Specifics:

PHP/MVC application that is API-driven in Zend.

Deployed to a few servers.

My question:

While investigating, lets say I have a hunch that something is wrong.  But, I don't know for sure.  And, of course, I can't test things in production.  If I have a suggested fix based on that hunch, would it be wise to try and apply it and see if it works, before understanding what the problem is?


答:
You see that there are many tests waiting to be written - very good! Bring order into your ideas of possible tests and get a plan like this:

Go through every tag/attribute and think about things which could go wrong (mostly no subtag/attribute when there should be one or the other way round) and how it should work (often there are only two or three ways which make sense for your specific xsd). Each of these cases should be become a particular test.

Then it's very good to think about other conditions (these are very dependent on your xml and what for you need/use it):

If you have names: should they be unique (maybe in groups or over all)

Are all used names defined and vice versa (second is maybe not so important - but a good warning is gold)

Other combinitions of "if you have this tag/attribute you need another one too at another place!"

Maybe like a certain order in your xml (at first the basic and then combined subtags of a certain kind).

Title: Common test cases for XML schema validator

Body:
I just wrote my first SAX-based (Java) XML schema validator, where you pass it a schema URL (pointing to the .xsd file), and an XML instance, and it determines whether or not that instance is valid or not.

I'm now looking to write several unit tests for the validator (TDD people, I know, I know!) and was wondering what were some common reasons why XML fails validation.

There are so many elements and attributes in this schema, I could literally write thousands of test cases.  I figured someone here might know of a way to simplify them all down to a manageable set.


答:
Here's some pragmatic advice from hard earned experience: don't include whole projects.

That's because IDEs such as Visual Studio or Eclipse (especially Visual Studio) tend to perform really badly when loaded with more and more projects and source code to compile or index.

You're better off just including the DLLs where you need them.

For debugging purposes, you could always keep the code for the library somewhere, and then just open it as a standalone project/solution and attach the debugger to the process that uses that library.

-- Edit

Some people mentioned that it could be a good idea if you plan to modify those 3rd party libraries. I disagree. You don't have to include them in your other solutions to do that. Simply edit them in their own solution, and re-add the newer version.


答:
Some larger organizations like the Company I work for have a policy of decommissioning software after a number of years, perhaps because the development language it was written in is no longer used (Delphi anyone?), or the platform is being replaced (Windows XP), or regulatory requirements demand it. E.g. two tier programs that talk directly to a database are now being decommissioned in favour of three tier that use Kerberized connections for greater security.

Users still need that original functionality, and so a completely new version using the current state of the art techniques gets developed.

Expect a 5-7 year replacement cycle for this type of thing. Eg by 2020, I expect the WPF (Client)/Java (server) software I'm writing now will be old tech and being replaced by something newer.

Title: Is the creation of brand new software generally a major part of most programming jobs?

Body:
I have worked in software development for over 10 years now, and it's dawning on me that I rarely get to create anything "new".  I realize that "new" is a vague term, but I would define it as anything from an obvious new large-scale project to a new large feature in an existing project (say something that would require some thought into its design, and that might take 2 weeks or more to complete).  Maybe a rough guideline is something is new if it requires a written spec.  I think most programmers know what I'm talking about - you're in the zone, writing a ton of code at a fast pace.

Anyway, thinking back to what I've done, I'd estimate that less than 10% of my time is spent on "new" work.  There are things like "adapt this existing system to work in this new environment", which certainly requires a lot of planning, but the actual coding and "new stuff" comes down to making tiny changes in many places throughout the code.  Likewise for small feature requests - if I know what to do, these can often be finished in under an hour, and if I don't, it's just a lot of reading code and figuring out what to do (which frustrates me because I learn much better by doing, not by reading).

In general I feel like I am not really creating anything most of the time.  I kind of assumed that this was the case at most places - a new product would come out rather quickly and at that point everyone would be excited and banging out the code at a fast pace, but then once live it moves into maintenance mode, where few of the subsequent changes would be considered "new & creative".

Am I wrong?  Am I accurately describing most programming jobs, or do most programmers feel like they are often creating new things?


问:
What is REST (in simple English)
Lately I have become interested in familiarizing myself with REST. I tried reading wiki entry on REST, but it was of no help. I would really appreciate it if someone can explain in simple English (that is without unnecessary tech jargon)

What is REST?

What position it occupies in web architecture ecosystem?

How tightly (or loosely) it is coupled with protocol?

What are the alternatives to REST and how does REST compare with them?

I understand it may not be possible to answer this in one or two paragraphs, in that case relevant links will be highly appreciated.

答:
While REST is an abbreviation of Representational State Transfer, it may be easier to consider the idea of performing various actions through a somewhat intuitive interface.

For example, a URL such as http://www.mysite.com/FindProduct/125/ could be interpreted as someone wanting to information on the product with an id of 125.

While REST is usually thought of in terms of HTTP, the concept could be applied to other protocols as noted in the Wikipedia reference.

Other examples of REST that may be useful:

Learn REST: A Tutorial

A RESTful Web service, an example

Title: What is REST (in simple English)


问:
With continuous integration in .NET, is it acceptable to reference DLLs of rarely-changing assemblies?
My company is looking to implement a CI solution pretty soon, and I am worried about one thing in particular... we are scaling up, which means our solutions are growing with more projects. One thing I wanted to look into is to split off rarely changed projects into a separate project, and then having other projects simply reference the compiled DLL, rather than including the projects in their solutions.

For example...

/BLL/DataFramework

/BLL/OrmFramework

/BLL/OrmDataAdapter

/BLL/...

/WebUI/MyWebSite

The Data and ORM projects would rarely be changed, but if not referenced as DLLs would add bloat to all solutions.

Instead I'd like to exclude them from the project and have them build to a Libraries folder (or something similar), so that:

/BLL/...

/Libraries

/WebUI/MyWebsite

Where the ORM and Data assemblies .DLLs are in the Libraries folder.

So the question is...

Is there any reason this would not work with Continuous Integration?

Could I have one solution with these rarely updated classes that will build to the library folder during CI, first, and followed by the other solutions?

Edit: To be clear... we want to keep these projects in the CI cycle, but to not directly reference their projects in every solution.

答:
This would work. I do something similar in that we treat those rarely changed projects as Core
Framework/Architecture dlls and they exist in their own solution. The dlls are published to a reference location and the other solutions reference these dlls in this location as required.

Although rare sometimes a bug is found or an new requirement is identified then a change is scheduled for these Framework/Architecture projects and they are built, unit tested and integration tested against those projects that use them.

Once testing has been completed they are released to the reference location and other projects pick them up on their next build.

All of the non Framework/Architecture projects are on a CI cycle and we have never had an issue with this approach.

Another advantage of this approach is that you have a single code base for these Framework/Architecture projects making it easy to control access if you have some IP and also to ensure that all versions of the application that need them are running on the same version.


答: There is no reason using referenced .NET assemblies would not work. As long as you properly include the referenced .NET assemblies in your source control system, your continuous integration server should have no problem using them to build your Visual Studio solutions and underlying projects.</p>

Title: With continuous integration in .NET, is it acceptable to reference DLLs of rarely-changing assemblies?

Body:
My company is looking to implement a CI solution pretty soon, and I am worried about one thing in particular... we are scaling up, which means our solutions are growing with more projects. One thing I wanted to look into is to split off rarely changed projects into a separate project, and then having other projects simply reference the compiled DLL, rather than including the projects in their solutions.

For example...

/BLL/DataFramework

/BLL/OrmFramework

/BLL/OrmDataAdapter

/BLL/...

/WebUI/MyWebSite

The Data and ORM projects would rarely be changed, but if not referenced as DLLs would add bloat to all solutions.

Instead I'd like to exclude them from the project and have them build to a Libraries folder (or something similar), so that:

/BLL/...

/Libraries

/WebUI/MyWebsite

Where the ORM and Data assemblies .DLLs are in the Libraries folder.

So the question is...

Is there any reason this would not work with Continuous Integration?

Could I have one solution with these rarely updated classes that will build to the library folder during CI, first, and followed by the other solutions?

Edit: To be clear... we want to keep these projects in the CI cycle, but to not directly reference their projects in every solution.


答:
I got started thanks to the Pragmatic Press with Pragmatic Version Control using ( Subversion || CVS || Git ).

Actually I think I got started with SourceSafe before that, but I wasn't using it that well and also it was SourceSafe. Really a quick read-through of any of those will get someone up to speed on the concepts pretty effectively.

Title: Noobie wants to use source control, how would you guide them?

Body:
Let's say you know of an anonymous noobie that wants to be lead upon the path of righteousness.  This noobie wants to use some sort of source control tools simply for the experience of using source control tools (and possibly for whatever benefits they bring along with them).

To constrain things further (and to make this possibly even more noobie-tastic), let's say they're stuck in windows developing in visual studio.

How would you guide your neophyte?


答:
Yes, this will work.

But do you really want your repositories filled up with assemblies, which are a lot bigger than the source files? Why not just build them? As long as you don't use Rebuild or change any of the source files, it will be relatively quick as the compiler will figure out that nothing has changed since your last build.

If you're using VS10 or VS11, there's a further option to build those libraries into NuGet packages and deploy those into a local repository, allowing you full control over versioning. This is the best of all worlds.


答:
It would work, and it does work (where I work :) ).

Using build servers like Jenkins/Hudson or other similar software, it is possible to set up build triggers for jobs (e.g. other builds).

You can set it up such that any change to project X triggers a build for X as well as builds for Y, Z, ...

For more information, you can go to Jenkin's homepage.


问:
Depend on built technology, or build your own

Possible Duplicate:

  How to decide between using an existing eCommerce solution and building your own?

I am starting a ecomm business and my site idea is pretty similar in functionality to ETSY. I am sure that I could build it in wordpress (or drupal or magento) and just use plugins to get all the functions i want - but is there risk in being dependent on an outside technology rather than just building something out myself (I do not know web development, yet, but am learning) from scratch like in ruby or something?

答:
It depends on your goal.

If the goal is to learn, then do as much as you can from scratch. Everything you do will teach you about the issues and solutions involved - how the web works, integrating Javascript, using AJAX, browser compatibility etc...

If your goal is to build a working website that will start earning as soon as possible, use as much prebuilt software as possible, in particular pieces that are known to work well together.

In reality, you will end up somewhere in the middle - some software from scratch, some using existing pieces, all held together by some more of your own software. How much from scratch and how much existing will depend on how comfortable you are with either side.


答:
Of course, when you pick up a 3rd party product, there's always a very small risk that one day down the line that product might have support dropped for it, and that may or may not impact the systems you use for your business; however that's something which every business faces these days, so it's no big deal.
(Well, of course it's a big deal if it happens, but it's a risk which you can hopefully manage as part of your overall business strategy by keeping a fallback strategy)

On the other hand I'd say there's far more risk associated with starting a new project by building everything yourself from scratch.   The risks are that you could end up with a product which is unstable, insecure, buggy, etc; and you'll have no support to turn to when something goes wrong - and if your business suffers as a result, you will have noone and nowhere to turn to.

If you're starting a business without having much tech knowledge yourself, then I would think the smartest thing to do would be to spend time researching the kinds of products and services out there which are within your budget, and already widely used by many other businesses in a similar situation to you - chances are you'll have plenty on your plate already without having to worry about building the web functionality from scratch too.

Title: Depend on built technology, or build your own

Body:
Possible Duplicate:

  How to decide between using an existing eCommerce solution and building your own?

I am starting a ecomm business and my site idea is pretty similar in functionality to ETSY. I am sure that I could build it in wordpress (or drupal or magento) and just use plugins to get all the functions i want - but is there risk in being dependent on an outside technology rather than just building something out myself (I do not know web development, yet, but am learning) from scratch like in ruby or something?


答: If you want to have a business that runs quite quickly, especially with you not being a very experienced programmer, Id go for the pre built stuff. In addition, it is going to take you a very long time to create something on par in functionality with e.g. wordpress. You might want to spend that time not reinventing the wheel, but really focusing on some great content to draw customers.</p>


答: First, show them VisualHg, which really fits Visual Studio like a glove to a hand, so they fall in love with it on first sight. Then show them where they can download it, and then, although it's lemon easy to use, also show them these two really swell tutorial sites, that shows a little more than just pretty pictures (although it's got some pretty pictures in there as well): Hg Init and Hg Tip. As soon as they're across that, they can stop calling themselves newbies for sure --> here be dragons.


答:
Ideally, if what you are producing is itself the product - for example, a web service like Etsy as you mention - I'd recommend doing it all yourself and not using an existing CMS.  The reason is once you start moving forward, more and more of your time will be spent fighting with how the CMS works to get it to fit to your particular model/requirements.  And if the system gets popular, you're going to run into all sorts of limitations as the CMS was not designed for your specific purpose.

That said, since you arent currently a very experienced developer and/or are working with minimal resources, for your specific case it might be best to get something up and online using an existing e-commerce system just so you can get some experience running such an application.  And then, if it looks like its going somewhere, after you have the background and understanding of the system's requirements to redevelop the app, you can do so.


答:
Magic Numbers or Magic Strings.

   if (accountBalance>200) { sendInvoice(...); }

   salesPrice *= 0.9;   //apply discount

   if (invoiceStatus=="Overdue") { reportToCreditAgency(); }
```


问:
Mobile Web Framework that will only control rendering and page transitions
I have been using jQueryMobile for a bit now, and there are some things I like about it and others I do not.

First I will give a bit of background.

I have a light weight mobile application that has a few configurations and 6 pages. Ideally I Would like to load all pages into the DOM (they interact with each other quite often and pages will be switched in the same frequency). The application will post for some JSON every n seconds and refresh the values on the page (yes it is primarily a information display app).

with the jQuery Mobile framework the only real thing I like is how easy it is to have a standardized UI a crossed all devices and browsers, I'm really not using too much else out of the framework other than the basic page navigation (if you are familiar with the framework; a bare-bone multi-page design is all i need).

Why I want to step away from jQueryMobile is how weighty it is. Not only do you need to include the mobile library, but also the base jQuery libraries. This I do not like because I'm not using jQuery anywhere else on the site.

Any suggestions on light-weight mobile frameworks that have a similar rendering as jQueryMobile?

答:
Have you tried Zepto.js? It's a 2-5k mobile JavaScript library for modern browsers with a largely jQuery-compatible API, so you can use it with the rest jquery code you have.

Regards,
Tom


问:
Should a new programmer focus on a single technology until he's proficient at it?
Ok, I've been teaching a buddy how to program for a while now. He's a very fast learner, and he's quite good at programming so far. However, he has one "issue" I keep trying to correct.

He jumps in and starts doing highlevel programming without learning some of the basics (He's created a full blown web application but still doesn't know pagination or session management).

This isn't the problem though. He keeps jumping around to new technology (Node.js, MongoDB, EC2, etc). I tried telling him that he should learn some of the basics about his RDMS of choice (MySQL) as he uses it everyday before investing a bunch of time into learning the basics of MongoDB (And probably moving to something new).

Am I the one in the wrong here, or should he try to focus on one thing at a time and get really good at it?

答:
Personally, I think it can be a great idea to sample different technologies and languages when learning to program. Focusing on one technology has the obvious benefit of making you very good at it, but the obvious downside of only knowing a single technology.

But I think the more important subtler downside is that languages and frameworks generally come with an ideology. There are many programmers (maybe most programmers) who only apply one ideology in everything they program. This is often because they learned one framework in one language really well and now they can't see anything without those goggles on.

Especially for someone just learning to program, I don't really think it's an issue to want to try what's out there, and wait to get focused on something until later. After all, it will be difficult to write anything substantial without knowing a technology decently well.


答:
I agree in part. He does need to know the underlying principles - but he doesn't need to just sit down on one thing and get really good at it. Nobody does.

On sitting down with one thing and getting really good

I'm currently working with C# and Microsoft XNA to make a game. I'm learning a lot about XNA as I go, and whilst I'm already pretty competent with C#, my knowledge is expanding bit by bit (today I learned about constraints on type parameters).

However, there's no need for me to become 'really good' at XNA or C#. If I were to finish my project now and move on and never use either of those ever again, I would be completely satisfied and my learning would continue elsewhere.

The principles are important though

At least I understand the underlying principles. When I create things in C# and XNA, I understand what I'm doing - and if I don't, I learn about it.

If I wrote pagination, I would understand how pagination works. If your friend created some pagination and has no idea how it worked, that is a problem. If he didn't create pagination, there's no reason he'd need to know though.

The issue here is: does he know what the @$#! he's doing, or is he a programmer who has no idea how to program?

Title: Should a new programmer focus on a single technology until he's proficient at it?

Body:
Ok, I've been teaching a buddy how to program for a while now. He's a very fast learner, and he's quite good at programming so far. However, he has one "issue" I keep trying to correct.

He jumps in and starts doing highlevel programming without learning some of the basics (He's created a full blown web application but still doesn't know pagination or session management).

This isn't the problem though. He keeps jumping around to new technology (Node.js, MongoDB, EC2, etc). I tried telling him that he should learn some of the basics about his RDMS of choice (MySQL) as he uses it everyday before investing a bunch of time into learning the basics of MongoDB (And probably moving to something new).

Am I the one in the wrong here, or should he try to focus on one thing at a time and get really good at it?


答:
There is good reasoning on both sides of this issue.  Knowing "enough" about a lot of different technologies is certainly valuable.  Knowing "a little" about a lot of different technologies?  Not so much.

Deep knowledge of particular technologies can certainly be valuable - IF there's ongoing demand for them.  Knowing "everything there is to know" about a particular technology? ...most probably overkill.

So, it's all in the balance.  If he ends up building wonderful apps with nosql, why would he have to know the difference between the InnoDB engine and the MyISAM engine?


问:
Understanding blocking and non-blocking frameworks
Could someone help me understand what is the difference between blocking and non-blocking frameworks?

So far, I understand that when request comes to a blocking framework it creates new thread for that request and processes it, if second request comes to server before the first one has finished it execution it will create another thread.

Now for non-blocking server when one request comes to a web server it wont create a thread but will wait for a request to complete and in case another request comes to a framework before first has finished executing it wont be able to process it before it returns result of first request.

Another question I have is what exactly happens with second request in non-blocking framework does browser just waits for server to respond till request expires or something else happens?

If non-blocking frameworks can process one request at a time, how can web apps built with non-blocking frameworks process more requests than ones built with blocking frameworks (assuming that above statement is correct). Does that mean that for each instance of blocking framework on our server we would actually deploy multiple instances of non-blocking framework?

答:
Did I get it right?

I think you've got it backwards.

"blocking" refers to prohibiting other things from proceeding while processing a task.

A server listens on a port for a request.  When it receives one, it can either (a) process the request (not listening for more requests while doing so, blocking further requests until the work is completed) or (b) spawn a thread to handle the request, and immediately return to listening on the port for more requests.

Alternatively, it could dispatch the request to an already spawned thread in a pool of threads it's managing.


答:
To an open source developer, there are two types of problems:

(a) problems without a patch

(b) problems caused by a patch

I think most open source package maintainers/developers LOVE the idea of helping to get a non-core-contributor up to speed with their patches.

Their primary goal, however, is minimizing the number of type-b problems.  That's why the bar is set pretty high.

Some people surmount it.  They become contributors, or maybe even core contributors.  Others give up.  There's a certain Darwinian nature to Open Source - survival of the fittest.

I encourage you to press on and spit-shine your contribution to the point where the team accepts it.  Once you've done a few contributions, they'll trust you further, but you should still make sure your contributions are impeccable.

The end result is totally worth it.  Stuff like being able to say "Do I code?  Yes... You're running something I wrote, every day."

Body:
A situation that has arisen several times in open source projects goes like this:

I notice a bug in our deployment, and figure out a quick hack patch. (For example, simply commenting out code that we don't actually need.)

I spend a little bit of extra effort to figure out the real bug, come up with a patch, and submit it via a Git pull request, or similar.

My pull request is rejected. Perhaps the patch was imperfect (eg, included lines it shouldn't have), perhaps it violated coding style, perhaps it had other ramifications. Or maybe I did something wrong in Git - the pull request should have been rebased or something. A maintainer provides feedback about how to improve the patch, and requests that I resubmit it.

At this point I'm confused about how far I should proceed. As far as I'm concerned, I don't have a problem: I fixed it back in step 1. I've reported the issue, I've even taken steps to fix it for others. But I don't feel that it's "my" pull request, so I don't feel that responsibility for improving the patch should come to me.

One particular situation that irks me is after discussion about the failings of my patch, we reach agreement on a mailing list about what the correct patch would be (ie, how it should behave, sometimes including every line of code spelt out). Then, it is still presumed to be my responsibility to actually generate and submit the patch.

Is there a standard etiquette in these situations? How are they resolved? Is my reaction unusual? How far are you expected to go to get your bug fix accepted?

(Note when I say "open source project", some of these are very small, but may not be hobbies - simply small software projects which are of use to several organisations, who commit developer resources to working on them. In case the obvious answer is "fix the patch and resubmit", understand that I have responsibilities to my employer to work on stuff that is of benefit to them. Spending time fixing a bug that doesn't affect us would be wrong...)


答:
I'm guessing he's attempting other languages because he has something he want to build. You can always return to a language or framework and learn more.

There is a fine line between learning the theory/building a foundation and trying to remain motivated.

At least he's not stuck in a single language. Sometimes you take the good with the bad.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Multiple ternary operators strung together, so instead of resembling an if...else block, it becomes an if...else if...[...]...else block

Long variable names with no underscores or camelCasing. Example from some code I have pulled up: $lesseeloginaccountservice

Hundreds of lines of code in a file, with little to no comments, and the code being very non-obvious

Overly complicated if statements. Example from code: if (!($lessee_obj instanceof Lessee && $lessee_obj != NULL)) which I chomped down to if ($lessee_obj == null)


答:
I think what you are describing is confusing two different things - Synchronous/Asynchronous calling mechanisms and the Reactor design pattern (which is a way for a long running service application to handle multiple service requests).

Blocking is another name for a synchronous call whereby the caller waits until the task finishes before resuming.

Non-blocking is another name for an asynchronous call whereby the caller returns immediately after making the call and may then be informed via an event (or callback) when the task has finished.

Title: Understanding blocking and non-blocking frameworks

Body:
Could someone help me understand what is the difference between blocking and non-blocking frameworks?

So far, I understand that when request comes to a blocking framework it creates new thread for that request and processes it, if second request comes to server before the first one has finished it execution it will create another thread.

Now for non-blocking server when one request comes to a web server it wont create a thread but will wait for a request to complete and in case another request comes to a framework before first has finished executing it wont be able to process it before it returns result of first request.

Another question I have is what exactly happens with second request in non-blocking framework does browser just waits for server to respond till request expires or something else happens?

If non-blocking frameworks can process one request at a time, how can web apps built with non-blocking frameworks process more requests than ones built with blocking frameworks (assuming that above statement is correct). Does that mean that for each instance of blocking framework on our server we would actually deploy multiple instances of non-blocking framework?


问:
How to be productive as an infrequent programmer?
My current day job is mostly project management and client liaison work, but I sometimes get involved in actual coding. I do this either because I have a clear vision of what I want the result to look like (and it's easier to implement than to explain it), because I have relevant expertise, or simply to add resources.

But I'm finding a couple of recurrent issues:

The startup time to being productive can be prohibitive. Installing development tools, getting access to relevant systems, source code etc, and simply getting to the point of a first complete build.

The overhead of working on a fast-moving codebase can be prohibitive. It's not unusual on one of my projects to have to completely rebuild the environment (that is, check out and build all the code again, including creating a new local database, populating it etc) every month or so.

Worst of all, if I stop doing any coding for more than about 2 weeks, I completely lose all my mental "state": I don't remember where things are installed, I don't remember which of several working directories is "the right one", I don't remember how to resolve an error message I've seen several times in the past. (I suspect my mental state attrition is much faster than average.)

I would really appreciate tips from anyone else in this situation. So far, I've worked out this much:

Only code in solid blocks of time - minimum 2 days. I can't get anything done at all in a few hours at a time.

Document, document, document. Keep spreadsheets that store state as much as possible. If there are several systems where code is deployed, record all key directories, port numbers, user names, database names etc etc.

What else?

答:
Here are my thoughts on this situation:

Focus on a technology to be proficient with (or a stack of techs..).

Build a programmer's machine with all the software you need and keep that handy so you don't have to re-build or install things constantly.

Enhance your tech. knowledge of choice by doing small projects frequently. They don't have to be work related all the time. This will allow you to focus on your weaker spots. You will gain more by spending time on learning what you don't know.

Realize that it is not possible for all people to play the roles of a PM and a programmer at the same time (many can do that, but many can't). Each of these jobs demand a lot of time.

Think why are your really so attached to programming. If this is what you want to do for living, make the move. If it is more of a hobby,  you know better than to do that at work :)

Watch your strain level, while you are trying to be good at both jobs. I am afraid that if you leave your current position one day, you won't be a star in either. Maybe you should choose one path and master it.


答:
Your mileage may vary with the following, but this is what I would do if I were in your shoes.  You're in a pretty tough spot with what you're trying to do, so hit it with powertools.

-> if you haven't yet, get the team to build a "dev VM" - a virtual machine which they use as a golden master from which to fire up VMs used for actual development.

The goal is for that VM to fire up with all tools already installed, relevant config files already in place, etc.  The only thing a developer should need to do is create an account for themselves and copy in their repo keys, source control uid/pass, or whatever.

That'll help ensure anyone (you included) can quickly spin up and do a local build, and it'll help eliminate those oh-so-special "the bug is only evident if joe builds the system" moments.

-> check in your APIs first

Build a test harness for your code before the code.  Call the new API you're inventing.  Then build a totally non-functional API that just has the function calls, return types, etc. but no implementation other than "return("example return value") or similar.

This will give the rest of the team something to chew on.  For a team that's accustomed to its members, a new member can be disruptive.  This will help minimize that disruption.

-> choose a full-time developer as your "contact point" and one 5-minute conversation with them every day.  No more, no less.

Let them tell you if they have any issues with what you contributed yesterday. Just listen, don't defend yourself.  Then, tell them what you're hoping to roll into the code today.  Absorb their feedback.  Again, just listen, don't defend yourself.   Thank them for helping you at the end of each of those meetings.

This is key.  You're not one of the core devs - they're a team, you're an add-on to their team.  Getting help from a "mentor" of sorts will pay numerous dividends, and help the team to understand you're not trying to be disruptive.  Believe it or not, very probably, they will look on your contributions to the code base as disruptive, unless you go to some lengths such as this 5-minute-daily-meeting to help ensure you're engaging with the team instead of just throwing code on top of their system.

Title: How to be productive as an infrequent programmer?

Body:
My current day job is mostly project management and client liaison work, but I sometimes get involved in actual coding. I do this either because I have a clear vision of what I want the result to look like (and it's easier to implement than to explain it), because I have relevant expertise, or simply to add resources.

But I'm finding a couple of recurrent issues:

The startup time to being productive can be prohibitive. Installing development tools, getting access to relevant systems, source code etc, and simply getting to the point of a first complete build.

The overhead of working on a fast-moving codebase can be prohibitive. It's not unusual on one of my projects to have to completely rebuild the environment (that is, check out and build all the code again, including creating a new local database, populating it etc) every month or so.

Worst of all, if I stop doing any coding for more than about 2 weeks, I completely lose all my mental "state": I don't remember where things are installed, I don't remember which of several working directories is "the right one", I don't remember how to resolve an error message I've seen several times in the past. (I suspect my mental state attrition is much faster than average.)

I would really appreciate tips from anyone else in this situation. So far, I've worked out this much:

Only code in solid blocks of time - minimum 2 days. I can't get anything done at all in a few hours at a time.

Document, document, document. Keep spreadsheets that store state as much as possible. If there are several systems where code is deployed, record all key directories, port numbers, user names, database names etc etc.

What else?


答:
Weakly typed parameters or return values on methods.

public DataTable GetEmployees() {...}

public DateTime getHireDate(DataTable EmployeeInfo) {...}

public void FireEmployee(Object EmployeeObjectOrEmployeeID) {...}
```


问:
How meaningful is the concept of "software craftsmanship"?
There seems to be a lot of buzz around software craftsmanship lately.

Is it a well-defined concept? What does imply? To what extent is programming effectively a craft activity?

答:
Amongst other uses of the word, the term Craft can be defined as:

an activity, as in handicraft (esp. as a hobby)

an art, trade, or an occupation requiring a special skill.

The concept of software craftsmanship has been tossed around for many years now. I remember discussing this with colleagues as far back as the late 90's, however it's probably been taken a little more seriously since the first copy of the Pragmatic Programmer was first released - as noted in the comments listed under the OPs Question.

As far as a specific definition is concerned, I don't personally know of any single clear statement that says "this [insert stuff here] is what being a software craftsperson means".  The only document that I can think of off the top of my head that comes close, is the statement and 12 principles which define the Agile Manifesto.

The implication however is relatively clear, in that in order to provide software of the highest possible quality, it needs to:

Either meet the customer's requirements, or be fit for it's intended purpose

Have a clean and clear implementation

Be lean - as in not suffering from gold plating

Be scalable & extensible

Be clearly documented (and yes, I include "readable" code in this)

Be supported by tests

Have relatively few defects

Delivered in a timely fashion

Getting all of the above "right" requires a highly skilled professional - or a team - with the experience and dedication to achieve the best possible result.

The major difference between tradespeople today, and professional software developers really comes down to how they are educated, the body of knowledge they are expected to absorb, and how soon they are turned loose into the workforce. Another is how quickly current knowledge becomes old and requires new knowledge to keep up with industry trends and changes.  Software developers are required to continue their education for the entirety of their careers in order to remain relevantly skilled, whereas trades knowledge such as carpentry or bricklaying changes rarely, if at all during the career of the tradesperson.

As a craft, you can draw a number of parallels between software development and some of the crafts of old:

Interns, graduates and juniors are effectively the Apprentices. Yes, they have studied and have their degree's, yet they still have a lot to learn about creating software. No company would seriously hire them to manage a software project, or to work entirely on their own without some sort of a mentor to guide them, and the "apprentices" are expected to make mistakes and to learn.

Mid-level developers are effectively the Journeymen, who usually go out into the world to hire themselves to work under another highly skilled individual in order to receive guidance, yet are usually left to work with little supervision, and expected to hone their skills, and expand their experiences.

Seniors and Principals are effectively the Master-craftsmen, who are expected to have a broad knowledge-base, yet may also choose to become specialists in a particular area of their "craft".

As to the actual degree to which software development is a craft, that really comes down to the professionalism of the individual programmer, and the standard to which that programmer is willing to work in order to provide the highest possible quality in their work.  The failure of the craftsperson analogy is that there are many people in Mid-Senior-Management roles who have arrived at their position without actually learning how to achieve a high standard of quality in their work, and in some ways the industry as a whole has suffered as a result. This is probably why those of us who see software development as more of an art than a science seek to work with others who think about software development in a similar way.

As a little side note/anecdote, I recently interviewed a graduate and put the question to him: "Do you see software development as more of an Art, or a Science?". Without even a blink, nor taking the time to draw a breath, his immediate response was "Art". His reasoning was based around quality issues, and on that question alone I would have hired him on the spot if I hadn't been hard-pressed by management to find someone more senior. Needless to say I kept that guy's C.V., and will be keeping an eye on him over the next year or two.


答:
Best option is don't code, your first reason is one of the worst for doing the code - sit down with a developer and pass on you superior knowledge and skills - learn to let it go or you never will. The second reason is commendable, but I find it rare that a a PM coding will make the team go faster than the PM doing the stuff that is not coding, that stops the full time coders coding.

Your job is project manager, and as such is to maximize the teams productivity. Professional coding is a job that needs dedication and commitment, not something that you slot into your spare time. A PM needs to be able to be interrupted. Thats a bad way to program. The two jobs only mix well in teams of less than 2.

Rather than code, ask yourself what jobs your top developers do that you can do for them. Can you test, write up requirements technical or user manuals, Can you help with code reviews, make them coffee and order in pizza.... i.e. You do the stuff you are good at and let them focus on the stuff they are good at.

If you must code, I suggest work on non time-critical defect fixes and minor features. It's work that must be done but won't matter if it's "late". If it is important in any way - let the experts do it.


问:
At least one database view per database table-Is this good or bad design and why?
We are building a Windows Mobile based application to interface with a customer's existing web application. We are reading and writing data to the customer's SQL server 2008 database.

The customer wants all reads to happen through SQL views, and all writes to happen through stored procedures.

But taking a look at their database schema, they have a view of each and every table. And they have a view of each and every query that would be used to read data, instead of using the existing views on their tables. They have 348 tables and 655 views so far.

They want us to model our mobile application in a similar fashion i.e. create additional views for all queries that we use to retrieve data.

I know this is poor design, but I am unable to list out to the customer why their view based strategy is a poor design.

What is the consensus in the community on when to use views? How does having so many views affect performance of the SQL server?

答:
```<code>  > The customer wants all reads to happen through SQL views,
  > and all writes to happen through stored procedures.
</code>```

I agree that this is more difficult to handle from the maintanance point of view

Every change in the web-gui means there must be a corresponding change in the database.

This makes developping and rollout more complicated.

But from the security point of view this is good design:

The database views allow fine-grained permisions (i.e. which user-role can see which columns, relating data.)

The stored procedures protect the system from sql-injections.

From the performance  point of view this shouldn-t be an issue any more because modern databases (including mssql2008) allow inexes over databaseviews.

Body:
  > The customer wants all reads to happen through SQL views,
  > and all writes to happen through stored procedures.

I agree that this is more difficult to handle from the maintanance point of view

Every change in the web-gui means there must be a corresponding change in the database.

This makes developping and rollout more complicated.

But from the security point of view this is good design:

The database views allow fine-grained permisions (i.e. which user-role can see which columns, relating data.)

The stored procedures protect the system from sql-injections.

From the performance  point of view this shouldn-t be an issue any more because modern databases (including mssql2008) allow inexes over databaseviews.