答:
In addtion to the EAV table that @Oded describes, people use nosql datbase for this type of information. Remember there is no reason why your application can't use a relational database for the parts that make sense with the relational model and a nosql database for the information that doesn't.

A third possibility is to add several columns for the customer-added fields (Customerfield1, customerfield2, etc) and then have the customer define what they mean. This only works for the number of customer comnfiguarble fields you add though, so it is fine if you only expect they will need two or three but won't work at all if you will need hundreds.

Title: Design Patterns / Strategies For Custom Fields & Data Types

Body: Are there any common strategies or design patterns for designing applications that have either the ability to add custom fields to data objects, or for creating your own custom definition of objects. For example, I am thinking of products such as SalesForce, where you can have your own types of information,frameworks such as Expression Engine and the way it handles channels and channel field groups (Example), or How CMSes Like wordpress have the ability to add fields to custom post types.</p>


问:
Are comments considered a form of documentation?
When I am writing small scripts for myself, I stack my code high with comments (sometimes I comment more than I code). A lot of people I talk to say that I should be documenting these scripts, even though they are personal, so that if I ever do sell them, I would be ready. But aren't comments a form of documentation?

Wouldn't this:

```<code>$foo = "bar"; # this is a comment
print $foo; # this prints "bar"
</code>```

be considered documentation, especially if a developer is using my code? Or is documentation considered to be outside of the code itself?

答:
I find sticking to Bob Martin's approach to this, from Clean Code, usually solves the problem of whether you think you're over commenting or under commenting and leaving out documentation:

We are authors. And one thing about authors is that they have readers. Indeed, authors are responsible for communicating well with their readers. The next time you write a line of code, remember you are an author, writing for readers who will judge your effort.

...the ratio of time spent reading vs. writing is well over 10:1. We are constantly reading old code as part of the effort to write new code.

So in other words, is your code is self explanatory without the documentation? There's no set rule for it (unless you work for somebody like Microsoft whose documentation is publicly accessible), it's mostly down to helping the future reader of the code which is often you.

ContentLicense: CC BY-SA 3.0


问:
Would "Efficient C++" book be irrelevant now due to compiler improvements?
I am planning on purchasing this book to learn more about C++ programming with regards to fast code. However, the book was published in 1999 and I am worried most of it may be irrelevant now due to optimizations that compilers perform.

Could anyone please advise?

http://www.amazon.com/Efficient-C-Performance-Programming-Techniques/dp/0201379503/ref=cm_cr_pr_product_top

edit:

Found this book too, albeit also rather old:

http://www.amazon.com/Optimizing-C-Steve-Heller/dp/0139774300

答:
No, the book is not irrelevant at all.  It's somewhat old school in places, but a lot of coding companies are that way too.  Further, most of what it teaches will always be a part of C++.

That said, I personally think that Sutter's books are better.  They don't cover the same material though, so if what's in Meyers's books is new to you...get both.


问:
Design Patterns / Strategies For Custom Fields & Data Types
Are there any common strategies or design patterns for designing applications that have either the ability to add custom fields to data objects, or for creating your own custom definition of objects. For example, I am thinking of products such as SalesForce, where you can have your own types of information,frameworks such as Expression Engine and the way it handles channels and channel field groups (Example), or How CMSes Like wordpress have the ability to add fields to custom post types.</p>

答:
Martin Fowler gave a nice description how to model dynamic properties (which is essentially what you are asking for) in his book "Analysis patterns". Most of the content is available online for free as PDF articles, the one you are looking for is this one:

http://martinfowler.com/apsupp/properties.pdf


答:
You wouldn't have the first application that had a table with: UDF1, UDF2, UDF3... The other suggestions (EVA or NoSQL) are much better.

Depending on the RDBMS (SQL Server offers this), you could break out of normalization and have a field that holds the data in an XML format or just plain text. You'll have to rely on code to manage this.


问:
Two database fields for date and time - should they be merged?
In the following question, field and table names have been changed to protect their identities.

If I have two database columns:

```<code>MONKEY_DATE DATETIME NULL (with data e.g. 2012-05-14 00:00:00.000)
MONKEY_TIME DATETIME NULL (with data e.g. 1753-01-01 16:30:53.025)
</code>```

The date component of the time field is mostly set to 1st Jan 1753... but some data has 1st Jan 1899 and some has 1st Jan 1900.

I find that maintaining the code to query and report on these columns causes me (and our team) a headache that could easily be solved by merging the two columns.  However, experience (and Terry Goodkind) has taught me that nothing is ever easy.  See below some examples of why this is a headache.

My Approach

I'm thinking the following approach will have the desired effect of merging the two columns:

Use SQL to update the data, setting the value for the date field and the value for the time field both to the same value, which is a mix of the date component from the date field and the time component from the time field

Write any new code only using the MONKEY_DATE field

Eventually phase out the MONKEY_TIME field and any of the date/time component SQL (see examples)

Drop MONKEY_TIME

This will mean we don't immediately have to go and make retrospective changes to the whole system... all existing code will continue to work... and we can begin to do things The Right Way.

SQL for #1 might be (Oracle):

```<code>UPDATE MONKEY SET
    MONKEY_DATE = TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY ') ||
                      TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'),
                      'MM/DD/YYYY HH24:MI:SS')
    MONKEY_TIME = TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY ') ||
                      TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'),
                      'MM/DD/YYYY HH24:MI:SS')
</code>```

The Question

My questions to you are:

Should these fields be merged?

Is my approach reasonable to merge these two columns?

Do you think it would be better to skip steps two and three?

Do you have any other (constructive) comments or suggestions?

Examples

For example, to select all my monkey dates and times and order them by date and time, I need to do something like this (SQL Server):

```<code>SELECT
      CONVERT(DATETIME, CONVERT(VARCHAR, MONKEY_DATE, 101), 101) AS MONKEY_DATE
    , CONVERT(DATETIME, CONVERT(VARCHAR, MONKEY_TIME, 108), 108) AS MONKEY_TIME
FROM MONKEY
ORDER BY
      CONVERT(DATETIME, CONVERT(VARCHAR, MONKEY_DATE, 101), 101) DESC
    , CONVERT(DATETIME, CONVERT(VARCHAR, MONKEY_TIME, 108), 108) DESC
</code>```

or this (Oracle - slightly more explicit):

```<code>SELECT
      TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY'), 'MM/DD/YYYY') AS MONKEY_DATE
    , TO_DATE(TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'), 'HH24:MI:SS') AS MONKEY_TIME
FROM MONKEY
ORDER BY
      TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY'), 'MM/DD/YYYY') DESC
    , TO_DATE(TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'), 'HH24:MI:SS') DESC
</code>```

I also often find myself selecting a merged date/time column (Oracle):

```<code>SELECT
    TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY ') ||
            TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'),
        'MM/DD/YYYY HH24:MI:SS') AS MONKEY_DATE_TIME
FROM MONKEY
</code>```

Because, almost all the time, we want to know the date and time of the monkey.

The above SQL could be easily altered to:

```<code>SELECT MONKEY_DATE_TIME FROM MONKEY ORDER BY MONKEY_DATE_TIME
</code>```

... If only we had merged columns.

Background

I've inherited an old ASP system that stores dates and times in separate columns in the database.  I've been told this is probably because the application started out in an early version of Access, where it was not possible to store both date and time in the same column.  The whys and hows aren't really part of this question, but some people like to know.

P.S.

I really nearly posted this in SO.SE, so my apologies if I got the wrong site.

答:
I had a similar problem at a previous work term. We split date and time into two DB columns. This caused us plenty of headaches. >_< With that said, I would highly recommend that you switch to a single datetime column in your DB. This will keep a lot of bugs from creeping up.

As for your strategy, it sounds reasonable, but make sure you get the whole team involved in this decision and refactoring. You need actively to discourage anyone from using the old data schema.

If there's not a lot of code changes required(and you have some extra time!), you can consider make the change all at once and not having an "intermediate" step where you support both data schemas. However, this is usually unlikely so you will probably need to have some sort of migration plan like the one you mentioned in step 2/3


答:
Yes, I think they should be merged. I normally wouldn't bother with separating date and time fields unless there is good reason to do it. Legacy systems might have been a good reason but if the data had migrated to a system that can handle dates and times combined, then merging is a good idea.

As for your approach, it sounds reasonable. You might want to even run a small refactoring project to fix all the code at the same time to make sure that all of your queries are corrected together to get rid of the "Eventually phase out the MONKEY_TIME field", though it could take some time and it will probably require significant regression testing. Which shouldn't be a problem if you plan ahead for it.

Also investigate if there's any downstream systems (such as web services or external reporting systems) that are built from different code bases but still depend on separate date and time values. If such systems exist, they will also have to be a part of this plan.

Title: Two database fields for date and time - should they be merged?

Body:
In the following question, field and table names have been changed to protect their identities.

If I have two database columns:

```<code>MONKEY_DATE DATETIME NULL (with data e.g. 2012-05-14 00:00:00.000)
MONKEY_TIME DATETIME NULL (with data e.g. 1753-01-01 16:30:53.025)
</code>```

The date component of the time field is mostly set to 1st Jan 1753... but some data has 1st Jan 1899 and some has 1st Jan 1900.

I find that maintaining the code to query and report on these columns causes me (and our team) a headache that could easily be solved by merging the two columns.  However, experience (and Terry Goodkind) has taught me that nothing is ever easy.  See below some examples of why this is a headache.

My Approach

I'm thinking the following approach will have the desired effect of merging the two columns:

Use SQL to update the data, setting the value for the date field and the value for the time field both to the same value, which is a mix of the date component from the date field and the time component from the time field

Write any new code only using the MONKEY_DATE field

Eventually phase out the MONKEY_TIME field and any of the date/time component SQL (see examples)

Drop MONKEY_TIME

This will mean we don't immediately have to go and make retrospective changes to the whole system... all existing code will continue to work... and we can begin to do things The Right Way.

SQL for #1 might be (Oracle):

```<code>UPDATE MONKEY SET
    MONKEY_DATE = TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY ') ||
                      TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'),
                      'MM/DD/YYYY HH24:MI:SS')
    MONKEY_TIME = TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY ') ||
                      TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'),
                      'MM/DD/YYYY HH24:MI:SS')
</code>```

The Question

My questions to you are:

Should these fields be merged?

Is my approach reasonable to merge these two columns?

Do you think it would be better to skip steps two and three?

Do you have any other (constructive) comments or suggestions?

Examples

For example, to select all my monkey dates and times and order them by date and time, I need to do something like this (SQL Server):

```<code>SELECT
      CONVERT(DATETIME, CONVERT(VARCHAR, MONKEY_DATE, 101), 101) AS MONKEY_DATE
    , CONVERT(DATETIME, CONVERT(VARCHAR, MONKEY_TIME, 108), 108) AS MONKEY_TIME
FROM MONKEY
ORDER BY
      CONVERT(DATETIME, CONVERT(VARCHAR, MONKEY_DATE, 101), 101) DESC
    , CONVERT(DATETIME, CONVERT(VARCHAR, MONKEY_TIME, 108), 108) DESC
</code>```

or this (Oracle - slightly more explicit):

```<code>SELECT
      TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY'), 'MM/DD/YYYY') AS MONKEY_DATE
    , TO_DATE(TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'), 'HH24:MI:SS') AS MONKEY_TIME
FROM MONKEY
ORDER BY
      TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY'), 'MM/DD/YYYY') DESC
    , TO_DATE(TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'), 'HH24:MI:SS') DESC
</code>```

I also often find myself selecting a merged date/time column (Oracle):

```<code>SELECT
    TO_DATE(TO_CHAR(MONKEY_DATE, 'MM/DD/YYYY ') ||
            TO_CHAR(MONKEY_TIME, 'HH24:MI:SS'),
        'MM/DD/YYYY HH24:MI:SS') AS MONKEY_DATE_TIME
FROM MONKEY
</code>```

Because, almost all the time, we want to know the date and time of the monkey.

The above SQL could be easily altered to:

```<code>SELECT MONKEY_DATE_TIME FROM MONKEY ORDER BY MONKEY_DATE_TIME
</code>```

... If only we had merged columns.

Background

I've inherited an old ASP system that stores dates and times in separate columns in the database.  I've been told this is probably because the application started out in an early version of Access, where it was not possible to store both date and time in the same column.  The whys and hows aren't really part of this question, but some people like to know.

P.S.

I really nearly posted this in SO.SE, so my apologies if I got the wrong site.


答: One minor point: WHEN you merge the two columns, you might want to do the merge into a new "MONKEY_DATE_2" column instead of overwriting the existing one. That leaves your current columns unchanged, and you can find all the code that hasn't been updated to work with the new structure with grep.</p>


答:
The compiler tries to optimize what it can, but you have to optimize what you can, and the book should help you with that (somewhat).

If you are going to write significantly large programs, it is very easy to put in slowness, without meaning to, that the compiler could never undo.

My favorite example is here. It consists of a realistically large program that was optimized. It was made faster by 50%. But that did not mean it could not be further optimized. The second attempt knocked out a healthy percent of what was left. But that still wasn't the end. This was done six times, and guess what the overall speedup ratio was?

730 times.

Toward the end, the optimizations being done were, out of the original program's time, so small as to be insignificant. But after a series of other problems were removed, small problems become larger, percentage-wise, so they become worth removing.
The individual speedup ratio that you get with each optimization may not be too surprising, but they multiply together like compound interest.

That's how you can really optimize code.
By all means, use the book, but don't limit yourself to what it says.

Title: Would "Efficient C++" book be irrelevant now due to compiler improvements?

Body:
I am planning on purchasing this book to learn more about C++ programming with regards to fast code. However, the book was published in 1999 and I am worried most of it may be irrelevant now due to optimizations that compilers perform.

Could anyone please advise?

http://www.amazon.com/Efficient-C-Performance-Programming-Techniques/dp/0201379503/ref=cm_cr_pr_product_top

edit:

Found this book too, albeit also rather old:

http://www.amazon.com/Optimizing-C-Steve-Heller/dp/0139774300


问:
Does MSDN follow documentation conventions for .NET, and if so is it publicly available?
While browsing the MSDN documentation for the .NET Framework Class Library (FCL) I've always been amazed by how consistent and fully documented it is. It's a constant companion when developing .NET applications. Most doubts that arise when using the APIs are covered. The contrast with e.g. the older Win32 documentation is striking.

Some examples:

Documentation for properties always starts out with either "Gets" or "Gets or sets" to specify accessors.

Type parameters start out with: "The type of ...".

Does Microsoft use a documentation convention which is followed for the FCL? If so, is this convention publicly available for me to use as well?

答:
Yes. There is a spec of sorts. That spec is built into StyleCop.

What it basically does is turn "style" errors (comments, code layout/formatting etc.) into build errors.

You can also include/exclude any rule that you like.


问:
Global Texture Container
For my first large-ish endevor in Open-GL I'm making a simulator of sorts.  I've got much of the basic functionality working, but recently ran into a problem.  As I've since realized, I originally designed the program so that each object in the simulator had its own class which stored its position, texture, draw code, etc.  This became a problem, however, when I began creating lots of objects of the same type, as I quickly realized that I wrote the classes to reload a new instance of the texture data for each instance of an object.  To fix this I considered making a simple texture database class of sorts which would contain a pointer to a single instance of each objects texture data that each instance of the object would copy upon its creation.

The problem here is that lots of different classes in the simulator create objects and I am hesitant to simply store the texture database class at the top of the program hierarchy and pass it down to every function that creates an object, as I feel that this will get very complex very fast.  Instead I feel it would be better to have a global container class that would keep track of the texture pointers, but I'm not sure how I could store the pointers without instantiating an instance of the container which would require passing it all over the place.  I'm hoping that there is a more elegant and simple solution that I'm overlooking, otherwise I'll try the way I've described.  Alternatively, if it seems some restructuring of the simulator would be best, that isn't out of the question, but I'd appreciate any advice.

答:
Edit: Removed singleton solution in favor of simpler static std::map using existing buildTex function. Note it is not thread safe as implemented.</p>

```<code>GLuint buildTex(string strFileName)
{
    static map<string, GLuint> s_Textures;

    if (s_Textures.find(strFileName) == s_Textures.end())
    {
        GLuint hTexture;
        // TODO: load hTexture from file

        s_Textures[strFileName] = hTexture;
    }

    return s_Textures[strFileName];
}

// Tree.cpp
void Tree::Draw()
{
    GLuint hTex = buildTex("Tree.tex");
    ...
}
</code>```

OwnerDisplayName: fedora

Title: Global Texture Container

Body:
Edit: Removed singleton solution in favor of simpler static std::map using existing buildTex function. Note it is not thread safe as implemented.

GLuint buildTex(string strFileName)
{
    static map<string, GLuint> s_Textures;

    if (s_Textures.find(strFileName) == s_Textures.end())
    {
        GLuint hTexture;
        // TODO: load hTexture from file

        s_Textures[strFileName] = hTexture;
    }

    return s_Textures[strFileName];
}

// Tree.cpp
void Tree::Draw()
{
    GLuint hTex = buildTex("Tree.tex");
    ...
}

OwnerDisplayName: Rollie


答:
How about a texture factory?

This approach might require some reorganization of your object hierarchy, but here's the gist in rough c++ish pseudocode :

```<code>class World
{
    void createVisibleObject(objProps) // objProps -> object properties
    {
        Texture myTex;

        if(textureCache.contains(objProps.textureName))
        {
            myTex = textureCache.find(objProps.textureName);
        }
        else
        {
            myTex = textureFactory.create(textureName);
            textureCache.add(objProps.textureName, myTex);
        }

        VisibleObject visObj(myTex);
        // add visObj to your visible object collection
    }

    TextureCache textureCache;
    TextureFactory textureFactory;
};
</code>```

Your individual visible objects don't (and shouldn't) need to know about how textures are loaded.  Just pass them a preconstructed texture.  Whatever is responsible for the creation of these objects is the one that worries about those details.  The TextureCache/Factory are held in the only place that needs to know about them.  The cache can be as fancy as you'd like with maps and smart pointers.

The benefits of this approach are varied:

Clear separation of concerns

The cache works 'globally', without being global

Resource creation happens in only one place

No reliance on singletons

Title: Global Texture Container

Body:
For my first large-ish endevor in Open-GL I'm making a simulator of sorts.  I've got much of the basic functionality working, but recently ran into a problem.  As I've since realized, I originally designed the program so that each object in the simulator had its own class which stored its position, texture, draw code, etc.  This became a problem, however, when I began creating lots of objects of the same type, as I quickly realized that I wrote the classes to reload a new instance of the texture data for each instance of an object.  To fix this I considered making a simple texture database class of sorts which would contain a pointer to a single instance of each objects texture data that each instance of the object would copy upon its creation.

The problem here is that lots of different classes in the simulator create objects and I am hesitant to simply store the texture database class at the top of the program hierarchy and pass it down to every function that creates an object, as I feel that this will get very complex very fast.  Instead I feel it would be better to have a global container class that would keep track of the texture pointers, but I'm not sure how I could store the pointers without instantiating an instance of the container which would require passing it all over the place.  I'm hoping that there is a more elegant and simple solution that I'm overlooking, otherwise I'll try the way I've described.  Alternatively, if it seems some restructuring of the simulator would be best, that isn't out of the question, but I'd appreciate any advice.

Body:
How about a texture factory?

This approach might require some reorganization of your object hierarchy, but here's the gist in rough c++ish pseudocode :

class World
{
    void createVisibleObject(objProps) // objProps -> object properties
    {
        Texture myTex;

        if(textureCache.contains(objProps.textureName))
        {
            myTex = textureCache.find(objProps.textureName);
        }
        else
        {
            myTex = textureFactory.create(textureName);
            textureCache.add(objProps.textureName, myTex);
        }

        VisibleObject visObj(myTex);
        // add visObj to your visible object collection
    }

    TextureCache textureCache;
    TextureFactory textureFactory;
};

Your individual visible objects don't (and shouldn't) need to know about how textures are loaded.  Just pass them a preconstructed texture.  Whatever is responsible for the creation of these objects is the one that worries about those details.  The TextureCache/Factory are held in the only place that needs to know about them.  The cache can be as fancy as you'd like with maps and smart pointers.

The benefits of this approach are varied:

Clear separation of concerns

The cache works 'globally', without being global

Resource creation happens in only one place

No reliance on singletons

OwnerDisplayName: luke


答:
What I did was create a Resource object, which then creates objects which need said resource- so in this case, std::shared_ptr<Texture> (where Texture is an interface and the implementation holds the actual texture data) and then you call tex_ptr->CreateSprite(); to create a sprite which uses that texture.

The problem here is that lots of different classes in the simulator create objects

There's your problem. Nothing to do with textures. Your code is a spaghetti mess. You need to centralize your dependencies. Create one class that deals with the sim, and one class that deals with OpenGL.

If "pass a reference" is too arduous for you, then refactor your code so it isn't. A simulator should know nothing about OpenGL or textures.

Title: Global Texture Container


问:
How to gain personal practice at heavyweight development methodologies?
I'm in a new job where the project needs to meet strict quality standards, be heavily documented, managed in great detail, UML diagrams, and all those things that are opposite of "cowboy coding" where most of my past work experience has been.  Think of the way large-scale aerospace or medical device software is developed.

I'm glad to leave the chaos of cowboy coding and am curious to see how well heavyweight engineering methods go.  But how can one rapidly gain experience  with the heavy methods?

Besides simply being in the job for some number of months/years, that is.

With a mere language, or new API, one can hack up a toy test program, read, deliberately make mistakes to see what happens, etc.   Like becoming good at bicycle riding or playing a musical instrument, practice is essential.  It is easy to pick up a flute and spend half an hour every day; no need to join an orchestra or be a full-time flute consultant.  But how to practice software engineering activities that are large, complex, involve teams, and much of which is all about communicating and planning, and avoiding miscommunications and exceeding schedule and budget limits?

This doesn't seem possible to do solo.  Is there a way a small number of people could simulate engineering a whole big project on a small scale in a short time (one day)?

答:
Start with a checklist.  (You knew that was the first step, right?)

Make sure the checklist lists all of the standard documentation for your current project.  ie. UML Diagram, functional spec, high-level and low-level designs, etc...  The systems engineer in me will suggest using an RTVM (requirements traceability verification matrix)

Pick a sample program to work on.  If you can't come up with one, google "code katas" or check out Google's codejam archive of challenges.  Or just build a calculator.  :-)

Build the functional spec for your sample program.  Then move into the high-level design, UML diagram, etc...  Build it to spec.  Test it.  Every time you find a significant flaw in your spec (as defined by your current work practices), then you need to step back to that stage of the SDLC and revise before moving forward again.

For your first round, go ahead and keep it small.  Cycling through the process is more important than overkill within any particular stage.  For subsequent rounds, add in the features that you left off.  Tracing, logging, performance analysis, test-scaffold, etc..  What you'll want to add will depend upon what your employer expects for your real work.

After you have iterated through the design / build / test / repeat cycle several times, you'll have built up skill and experience in the "heavyweight" components that are worrying you now.  The iterations will also show you the interconnection between the various stages and the documentation generated.  The valuable lesson there is showing how a 5 minute code change can have a multi-hour ripple effect elsewhere due to doc updates and testing requirements.


问:
Rule of thumb for field sizes
What VARCHAR sizes should be used for first and last names, phone numbers (preferably international), email adresses, urls, dictionary words and  file names?

Edit: Zapped the introductory phrase to form a concrete question.

答: The answer depends on the database you are using.  For Postgres, you may as well use TEXT for everything; no other type will be more efficient.  For Oracle you can use VARCHAR2(4000) for all fields where 4000 characters is sufficient; again no other character type will be more efficient.

Title: Rule of thumb for field sizes


答:
If you are phasing in this change over time (as opposed to preparing all the changes and then installing everything at once), you need to be careful that you don't read values the new way when it was written in the old way. So the transition would need to go:

All new writes both the new way and the old way (using a new column for the new way would help), and reads the old way. Existing code is modified to write both tne new way and the old way.

Once all code is writing both ways, convert existing data so it is available both ways.

All new code reads the new way (and still writes both ways). Existing code is modified to read the new way.

Once all code is reading the new way, new code can write only the new way, and existing code can be modified to only write the new way.

Once all code is reading and writing the new way, and no code references the old columns, they can be removed.

The new way (one column with both date and time) seems obviously better to me, you have to decide if it is enough of an improvement to go through the conversion process.


答:
If the date and time are always used together, then by all means, merge the columns and reap the benefits of fewer headaches.

Things to watch out for:

Use of the time column for calculating relative time across days (e.g., "select of the monkeys that went bananas on any day at a time within one hour of when this monkey went bananas").

Arithmetic on the date column that doesn't deal with fractional days in a sane way.

Use of the date column as a grouping mechanism.

If you have existing queries that are particularly sticky, create an updatable view that emulates the old behavior until you can get them straightened out.


答:
there are really two schools of thought for how to determine field size.

make everything as big as possible.

This makes it unlikely that it will ever be required to expand a field which can be very expensive to do, also with fields like varchar there is very little lost in terms of wasted space/performance.

Create fields with smallest possible limit.

This can help increase data integrity and also be very useful in special cases. For example if a field is commonly used in a report where space is an issue limiting it to X characters saves having to decide how to trim or truncate data. Limiting sizes can also be useful if you can guarantee a field will always have a specific length, this can help ensure your data has a minimum quality, for example storing state postal codes as a CHAR(2) ensures that longer entries won't happen, or storing numeric values as a numeric type ensures that what is stored is a number. It can be extremely hard to find numbers for field length for most fields though and the cost of having to change after implementing can be very expensive.

The best rule of thumb is do what makes your DBA happy.

Title: Rule of thumb for field sizes

Body:
What VARCHAR sizes should be used for first and last names, phone numbers (preferably international), email adresses, urls, dictionary words and  file names?

Edit: Zapped the introductory phrase to form a concrete question.


问:
A defense for boilerplate?
To me, boilerplate code is obviously bad.  However I've met a developer who displays resistance in any attempt to reduce boilerplate.  I realized I didn't have a readily formed, well thought out argument past the abhorrence I have developed for it over time.

So that I can form a convincing argument for favoring less boilerplate, what are some counterarguments? In other words what are the arguments (if any) in favor of boilerplate?

(I mean what I think is generally meant by boilerplate, but a good example is getters and setters in Java.)

答:
One important thing to remember is that code is generally made smaller by removing unnecessary context.  If the compiler can figure something out, the argument goes, there's no need to write it out explicitly.

And that would be great if only the compiler was ever intended to read it.  But remember that "programs should be written for people to read, and only incidentally for machines to execute."  (Ironically, this quote comes from a textbook dedicated to one of the hardest of all languages for ordinary human beings to read, due in large part to its excessive terseness.)

What may look like boring, repetitive boilerplate to you as you're writing it can be valuable context to someone else who comes along a year (or five) later and has to maintain your code.

WRT the Java example specifically, I'll agree that that's a good example of bad boilerplate, since it can be replaced by something that's both shorter and easier to read, and also more flexible: Properties.  But that doesn't mean that all boilerplate syntactic elements from all languages are as wasteful as the getters and setters from Java and C++.

Title: A defense for boilerplate?

ContentLicense: CC BY-SA 4.0


答:
The problem with boilerplate is that it violates DRY. In essence, when you write boilerplate, you're repeating the same code (or very similar code) across a number of classes. When that code needs to get changed, it's not at all certain that the developer will remember all of the places that code was repeated. This leads to bugs where old APIs or old methods are used.

If you refactor out the boilerplate into a common library or parent class, then you only need to change code in one place when your API changes. More importantly, when unexpected changes happen, the code breaks in one place, and lets you know exactly what you have to fix in order to get everything working again. This is far preferable to a scenario where one change causes failures in dozens, or even hundreds of classes.

Title: A defense for boilerplate?

Body:
To me, boilerplate code is obviously bad.  However I've met a developer who displays resistance in any attempt to reduce boilerplate.  I realized I didn't have a readily formed, well thought out argument past the abhorrence I have developed for it over time.

So that I can form a convincing argument for favoring less boilerplate, what are some counterarguments? In other words what are the arguments (if any) in favor of boilerplate?

(I mean what I think is generally meant by boilerplate, but a good example is getters and setters in Java.)


问:
What is the appeal of Systems Hungarian?
In a now deleted question titled "What naming guidelines do you follow?", the author says:

Also I prefer to code using hungarian notation from Charles Simonyi.

I've run in to several programmers who still prefer to use Hungarian, mostly of the Petzold/Systems Hungarian flavor.  Think dwLength = strlen(lpszName).

I've read Making Wrong Code Look Wrong, and I understand the rationale for Apps Hungarian, where domain-type information is included in the variable names.  But I don't understand the value in attatching the compiler type to the name.

Why do programmers still persist on using this style of notation?  Is it just inertia?  Are there any benefits that outweigh the decreased readability?  Do people just learn to ignore the decorators when reading the code, and if so, how do they continue to add value?

EDIT:
A lot of answers are explaining the history, or why it is no longer relevant, both of which are covered in the article I cited.

I'd really like to hear from anyone out there who still uses it.  Why do you use it?  Is it in your standard?  Would you use it if it wasn't required?  Would you use it on a new project?  What do you see as the advantages?

答:
Apps Hungarian (tags to denote semantic properties of objects that can't be expressed through the type system) was a reasonable way to deal with some common errors when using the weakly-typed languages of the early 1980s. They serve little purpose in today's strongly-typed languages.

Systems Hungarian (tags to redundantly denote an object's declared type) has never served any purpose except to impose a superficially uniform appearance on a code base. It was created and propagated by non-technical managers, and inexperienced programmers, who misunderstood the intent of Apps Hungarian, and believed that code quality could be enhanced by complex coding guidelines.

Both styles originated within Microsoft. These days, Microsoft's naming conventions categorically say "Do not use Hungarian notation."

ContentLicense: CC BY-SA 2.5


问:
Alternative to Perl's POD Documentation in Other Languages?
Perl has this really cool documentation method that makes documenting really easy. It's called POD (Plain Old Documentation). Here is an example:

```<code>=head1 NAME

Example::Module - an example

=head1 SYNOPSIS

    use Example::Module;
    my $object = Example::Module->new();
    print $object->as_string;

=head1 DESCRIPTION

Just an example.

=head2 Methods

=over 12

=item C<new>

Returns a new My::Module object.

=item C<as_string>

Returns a stringified representation of
the object. This is mainly for debugging
purposes.

=back

=head1 LICENSE

This is released under the Artistic
License. See L<perlartistic>.

=head1 AUTHOR

Dynamic

=head1 SEE ALSO

L<perlpod>

=cut
</code>```

The output of this would be in HTML, like this example on CPAN (not what I wrote). Cool right!

So is there a method similar to POD in which a developer can put there documentation inside of the code itself, without it being a comment?

答:
JavaDocs are very similar to this. They are comments but they are a special form of comment that are then compiled to produce documents that look like the official Java documentation.

Both JavaDoc and POD are examples of "Documentation Generators" of which there are many. Wikipedia has a good sized list for a variety of platforms and languages.


答:
I despise boilerplate code, but being able to remove boilerplate code doesn't always mean that's the best way to go.

The WPF framework has dependency properties, which involves an insane amount of boilerplate code. During my spare time I investigated a solution which greatly reduces the amount of code that needs to be written. Over one year later I am still improving on this solution, and still need to extend on its functionality or fix bugs.

What is the problem? This is great in order to learn new stuff, and explore alternative solutions, but it's probably not the best commercial decision.

The WPF framework is well documented. It properly documents how to write your boilerplate code. Attempting to remove this boilerplate code is a nice exercise, and something which is definitely worth exploring, but achieving the same level of 'polish' as msdn offers takes a long time, which we don't always have.

Title: A defense for boilerplate?


答:
One argument in favour of boilerplate code is that if you change it in one place, it only affects one flow of the code. This has to be balanced against the fact that more-often-than-not, you actually want a change to affect every piece of code that uses it. But I have seen rare examples that support the argument.

Let's say you have a piece of code that says

```<code>public ForTheBar(Foo foo)
{
    Bar bar = foo.bar();
    return bar.BeFooed();
}
</code>```

This is used in about 2 places in your code.

One day someone comes along and says "ok, in this path only, we want you to Grommit the bar before Fooing it."

And you think "well this is simple."

```<code>public ForTheBar(Foo foo, bool shouldIGrommit)
{
    Bar bar = foo.bar();

    if (shouldIGrommit)
    {
        bar.BeGrommitted();
    }

    return bar.BeFooed();
}
</code>```

Then your user adds some new functionality and you reckon it fits in well with FooTheBar. And you dutifully ask them if you should Grommit that bar before you Foo it and they say "no, not this time".

So you just call the method above.

But then your user says "ok, wait, in the third case, we want you to Doodle the Bar before calling BeFooed."

No problem, you think, I can do that.

```<code>public ForTheBar(Foo foo, bool shouldIGrommit, bool shouldIDoodle)
{
    Bar bar = foo.bar();

    if (shouldIGrommit)
    {
        bar.BeGrommitted();
    }

    if (shouldIDoodle)
    {
        bar.BeDoodled();
    }

    return bar.BeFooed();
}
</code>```

Suddenly your code is becoming less boilerplate. Perhaps you should have accepted the repeated two lines of code. By now you would have three pieces of code, each 2-3 lines long and not looking very repeated any more.

All this said, I would counter that with "this is not a common case, and when it happens, you can refactor."

Another argument I have recently heard is that boilerplate code can sometimes help you navigate code. The example we were discussing was where we'd removed tons of boilerplate mapping code and replaced it with AutoMapper. Now, it was argued, because everything is convention-based, you cannot say "Where is this property set," to the IDE and expect it to know.

I've seen people argue similar things about IoC containers.

Not to say that I agree with them, but it's a fair argument nonetheless.

Title: A defense for boilerplate?

Body:
One argument in favour of boilerplate code is that if you change it in one place, it only affects one flow of the code. This has to be balanced against the fact that more-often-than-not, you actually want a change to affect every piece of code that uses it. But I have seen rare examples that support the argument.

Let's say you have a piece of code that says

public ForTheBar(Foo foo)
{
    Bar bar = foo.bar();
    return bar.BeFooed();
}

This is used in about 2 places in your code.

One day someone comes along and says "ok, in this path only, we want you to Grommit the bar before Fooing it."

And you think "well this is simple."

public ForTheBar(Foo foo, bool shouldIGrommit)
{
    Bar bar = foo.bar();

    if (shouldIGrommit)
    {
        bar.BeGrommitted();
    }

    return bar.BeFooed();
}

Then your user adds some new functionality and you reckon it fits in well with FooTheBar. And you dutifully ask them if you should Grommit that bar before you Foo it and they say "no, not this time".

So you just call the method above.

But then your user says "ok, wait, in the third case, we want you to Doodle the Bar before calling BeFooed."

No problem, you think, I can do that.

public ForTheBar(Foo foo, bool shouldIGrommit, bool shouldIDoodle)
{
    Bar bar = foo.bar();

    if (shouldIGrommit)
    {
        bar.BeGrommitted();
    }

    if (shouldIDoodle)
    {
        bar.BeDoodled();
    }

    return bar.BeFooed();
}

Suddenly your code is becoming less boilerplate. Perhaps you should have accepted the repeated two lines of code. By now you would have three pieces of code, each 2-3 lines long and not looking very repeated any more.

All this said, I would counter that with "this is not a common case, and when it happens, you can refactor."

Another argument I have recently heard is that boilerplate code can sometimes help you navigate code. The example we were discussing was where we'd removed tons of boilerplate mapping code and replaced it with AutoMapper. Now, it was argued, because everything is convention-based, you cannot say "Where is this property set," to the IDE and expect it to know.

I've seen people argue similar things about IoC containers.

Not to say that I agree with them, but it's a fair argument nonetheless.


问:
What is upcasting/downcasting?
When learning about polymorphism you commonly see something like this

```<code>class Base { int prv_member; virtual void fn(){} }
class Derived : Base { int more_data;  virtual void fn(){} }
</code>```

What is upcasting or downcasting? Is (Derived*)base_ptr; an upcast or downcast?

I call it upcast because you are going away from the base into something more specific. Other people told me it is a downcast because you are going down a hierarchy into something specific with the top being the root. But other people seem to call it what i call it.

When converting a base ptr to a derived ptr is it called upcasting or downcasting? and if someone can link to an official source or explain why its called that than great.

答:
```<code>Is (Derived*)base_ptr; an upcast or downcast?
</code>```

It is a downcast: see Wikipedia's article on it.

In object-oriented programming, downcasting or type refinement is the act of casting a reference of a base class to one of its derived classes.

In many programming languages, it is possible to check through RTTI whether the type of the referenced object is indeed the one being cast to or a derived type of it, and thus issue an error if it is not the case.

In other words, when a variable of the base class (parent class) has a value of the derived class (child class), downcasting is possible...

Title: What is upcasting/downcasting?

Body:
Is (Derived*)base_ptr; an upcast or downcast?

It is a downcast: see Wikipedia's article on it.

In object-oriented programming, downcasting or type refinement is the act of casting a reference of a base class to one of its derived classes.

In many programming languages, it is possible to check through RTTI whether the type of the referenced object is indeed the one being cast to or a derived type of it, and thus issue an error if it is not the case.

In other words, when a variable of the base class (parent class) has a value of the derived class (child class), downcasting is possible...


答:
In most languages (as far as I know) generalizing casts are performed automatically. So, usually if you speak about a cast within a hierarchy you are referring to a specializing cast. IMHO most people with the desire to separate the two types call the specializing cast downcast because they think of the inheritance hierarchy as a tree. And in computer science the root is pictured to be on the top. The reason behind this is either a convention, or, more probably, a deep rooted hatred for biologists among computer scientists. (All puns intended.)

EDIT: Maybe it is a top rooted hatred.

Title: What is upcasting/downcasting?

Body:
When learning about polymorphism you commonly see something like this

```<code>class Base { int prv_member; virtual void fn(){} }
class Derived : Base { int more_data;  virtual void fn(){} }
</code>```

What is upcasting or downcasting? Is (Derived*)base_ptr; an upcast or downcast?

I call it upcast because you are going away from the base into something more specific. Other people told me it is a downcast because you are going down a hierarchy into something specific with the top being the root. But other people seem to call it what i call it.

When converting a base ptr to a derived ptr is it called upcasting or downcasting? and if someone can link to an official source or explain why its called that than great.


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
Writing function names as if they were English sentences:

```<code>Draw_Foo()
Write_Foo()
Create_Foo()
</code>```

etc. This might look great, but it's a pain when you're learning an API. How much easier is it to search an index for "Everything that starts with Foo"?

```<code>Foo_Draw()
Foo_Write()
Foo_Create()
</code>```

etc.

Body:
Writing function names as if they were English sentences:

Draw_Foo()
Write_Foo()
Create_Foo()

etc. This might look great, but it's a pain when you're learning an API. How much easier is it to search an index for "Everything that starts with Foo"?

Foo_Draw()
Foo_Write()
Foo_Create()

etc.


答: Think of the normal way of drawing a tree with the "base" at the top of the page and the leaves at the bottom. If you represent your class hierarchy this way, with the base class at the top and the leaves somewhere below, then up-casting and down-casting become literal -- something that moves up the page from a leaf toward the base is an up-cast and something that moves down the page from the base toward a leaf is a down-cast.</p>

Title: What is upcasting/downcasting?


答:
Experience with "heavyweight" practices only comes from doing the real thing. There's no way to effectively practice it in isolation. You can, however, study it. There are many case studies and sources you can study and ponder.

Not all the practices you see or study are necessarily positive, however. Software development is a fluid thing, and what seems hardcore and strict today may seem silly and redundant tomorrow. This happens both through new tools and experimental experience bubbling up from startups to the more conservative organizations.

Basically, change and risk management seems to have a unique shape for each organization. Your best bet is to keep an open mind, but don't carry too many assumptions from team to team.

Title: How to gain personal practice at heavyweight development methodologies?

Body:
I'm in a new job where the project needs to meet strict quality standards, be heavily documented, managed in great detail, UML diagrams, and all those things that are opposite of "cowboy coding" where most of my past work experience has been.  Think of the way large-scale aerospace or medical device software is developed.

I'm glad to leave the chaos of cowboy coding and am curious to see how well heavyweight engineering methods go.  But how can one rapidly gain experience  with the heavy methods?

Besides simply being in the job for some number of months/years, that is.

With a mere language, or new API, one can hack up a toy test program, read, deliberately make mistakes to see what happens, etc.   Like becoming good at bicycle riding or playing a musical instrument, practice is essential.  It is easy to pick up a flute and spend half an hour every day; no need to join an orchestra or be a full-time flute consultant.  But how to practice software engineering activities that are large, complex, involve teams, and much of which is all about communicating and planning, and avoiding miscommunications and exceeding schedule and budget limits?

This doesn't seem possible to do solo.  Is there a way a small number of people could simulate engineering a whole big project on a small scale in a short time (one day)?


答: The only real problem with boilerplate code is that when you find a bug in it you have to fix everywhere that you used it rather than the one place that you reused.

Title: A defense for boilerplate?


问:
How safe is it if I store passwords in app.config in C# .net 4
I am storing database passwords in app.config as plain text. I am also publishing the application.

How safe is that password stored in app.config? Can I use a disassembler and find it?

答:
No, you cannot find the password with a disassembler. But you can read it plain as day if someone compromises your web server. At the very least, check these links:

https://web.archive.org/web/20211020203213/https://www.4guysfromrolla.com/articles/021506-1.aspx

https://web.archive.org/web/20130501053227/http://aspnettutorials.com/tutorials/advanced/encrypt-conn-str-asp4-cs.aspx

https://web.archive.org/web/20220722120853/https://www.beansoftware.com/ASP.NET-Tutorials/Encrypting-Connection-String.aspx

Better yet, do not use SQL Server Security and instead use Integrated Security and only allow the account your web app (pool) runs under to access the DB.


问:
The relation between Business Rules Engines and Constraint Programming languages
If one looks at (perhaps older) manuals of Drools or some other rule engines,
one of the illustrations of their added value is solving puzzles such
as the Miss Manners puzzle (listed in the Drools Documentation). Now, such puzzles are naturally formulated
and solved using Prolog or the more recent Constraint Programming languages, and
one wonders why would anyone use Drools for this purpose. The added value
which Prolog and CPL give in this case is their ability to naturally
formulate the puzzle as a set of logical predicates and to automatically
search the space of solutions (with CPL being more efficient in this respect).
But what is the added value of product such as Drools (I mean besides of
the bells and whistles of taking, for example, an Excel file and translating
it into a set of rules)?

More specifically, Prolog implements backtrack search, CLP implements backtrack search
with constraint propagation, and therefore instead of searching, so to speak, the
whole Cartesian product of spaces for individual variables, they prune away large portions
of this product space. This is what makes them effective and useful. Both Prolog and
CLP are discussed amply in the literature.

On the other hand, while it is clear that Rete algorithm caches the set of rules
in the form of some data structure(s), thus (to my understanding) making it more
effective to evaluate the output if some of the inputs have changed, and giving
means to effectively update this data structure for incremental changes, it is
difficult (for me) to understand the basic idea, and even more so, its effectiveness (compared to what? to Prolog? to CLP)? Unfortunately, it is hard to find good
references that view Rete algorithm in this wider context.

The documentation of Drools is unfortunately not very informative in this respect.
The most I could find was "The Rete algorithm, Leaps algorithm, and its descendants such as Drools' Reteoo (and Leaps), provide very efficient ways of matching rule patterns to your domain object data. These are especially efficient when you have datasets that do not change entirely (as the rule engine can remember past matches). These algorithms are battle-proven". Very efficient - compared to what? Battle proven - could one point to real-world
applications?

I would appreciate it if one could throw some more light on this subject or give a valid
reference.

答:
Drools recently adding backward chaining, seamlessly into the drl language. So now you get the benefits of both words.

It doesn't yet quite have all the features of prolog, for instance no 'cut'. But it's unification and deriviation tree results will work as prolog people expect, i.e. full support for transititive closures. And features will continue to grow, such as support for tabling, cut, unification on expressions.

You can use forward "reactive" or backward "query" rules separately, or use them together; where the reactive rule can join with the results of a query.

One thing we added is our queries can be fully materialised as a reactive view. So you can call a transititve closure query and it'll stay open in a reactive manner and respond to change in the underly ground data - without having to re-poll the query.

See New & Noteworth sections for when "backward chaining" was added:
http://blog.athico.com/2012/05/drools-540final-released.html

So I think your question would be better worded, why would you want to use anything else, when you have  Hybrid Reasoning System like Drools?
http://blog.athico.com/2012/05/drools-54-artificial-intelligence.html

OwnerDisplayName: John Donn


问:
designing large scale applications in a low level language
I have been learning C for a while but still get confused about designing large programs within C (a large application such as the Linux kernel).

Moving from Java where you have classes it's difficult to understand how to design a large application in C.

What advice/links can people advise from moving from a high level language to designing applications in a low level language such as C?

答:
You wind up implementing objects more directly, without the syntactic sugar.  Essentially, structs with function pointers.

You mention the Linux Kernel; you might consider reading its source looking for that pattern.


答:
The evolution of efficiency

You start with this:

```<code><p>
    <label for="field">My field</label>
    <input type="text" id="field">
</p>
</code>```

then you get rid of all that annoying boilerplate and put it in a function:

createFieldHtml( id, label )

this is good, I'm saving myself so many lines!

createFieldHtml( id, label, defaultValue )

yea, I need a default value too, that was easy to add.

createFieldHtml( id, label, defaultValue, type )

cool, I can use it for checkboxes now too

createFieldHtml( id, label, defaultValue, type, labelFirst )

UX designer said label has to be after checkbox.

createFieldHtml( id, label, defaultValue, type, labelFirst, isDate )

it now renders a date picker when needed. Hm.. params are getting a bit out of hand

createFieldHtml( id, label, defaultValue, type, labelFirst, isDate, containerCssClasses )

there was this one case where I need to add CSS classes

createFieldHtml( id, label, defaultValue, type, labelFirst, isDate, containerCssClasses, fieldCssClasses, disabled, clearAfter, helpText, uploadPath )

aaaaaaaaaaaaaaaaaaaaa

In defense of boilerplate

I have a hard time putting this into words because it's really something I've been noticing just recently, so I'll make a list:

It seems to me that there is a certain fear of having duplicate lines that stretch out a bit. If it's just a few lines it might be no problem at all. some things are inherently "almost repetitive" (like the example above). I see little chance in optimizing there in the long run.

People love to encapsulate functionality somewhere; if you look at objectively and it seems like it's just "hiding the mess" -- be suspicious! it might be the time for some good old boilerplate

When you have a function that becomes more and more powerful; that takes many different execution paths depending on the input and ultimately does very little -- it might be boilerplate time!

When you add a layer of abstraction on top of another layer of abstraction, but just to make your code shorter (the underlying layer is not meant to be changed) -- boilerplate time!

When you have a function that takes so many parameters that you really need to have named parameters -- maybe it's boilerplate time.

One thing I recently always ask myself is this:

Can I copy&paste into another project without changing anything? if yes, it's okay to encapsulate or put into a library, if no: it's boilerplate time.

This is very much opposed to the general perception that boilerplate is copy&paste code. To me boilerplate is about copy&pasting, but always having to tweak it a tiny bit.

Update: i've just come across an article giving my example above an actual name: "too DRY anti-pattern".

The function gets more parameters and has increasingly complex
  internal logic to control its behavior in different cases. Too DRY
  functions are easy to spot. They have lots of intricate if-then logic
  that try to address a wide diversity of usage. [...] Also, repeating
  code isn’t always a bad thing if the code is small and performs a
  discrete function.

It's a short and interesting read, you can find the article here: Too Dry Anti-Pattern

Title: A defense for boilerplate?

Body:
The evolution of efficiency

You start with this:

<p>
    <label for="field">My field</label>
    <input type="text" id="field">
</p>

then you get rid of all that annoying boilerplate and put it in a function:

createFieldHtml( id, label )

this is good, I'm saving myself so many lines!

createFieldHtml( id, label, defaultValue )

yea, I need a default value too, that was easy to add.

createFieldHtml( id, label, defaultValue, type )

cool, I can use it for checkboxes now too

createFieldHtml( id, label, defaultValue, type, labelFirst )

UX designer said label has to be after checkbox.

createFieldHtml( id, label, defaultValue, type, labelFirst, isDate )

it now renders a date picker when needed. Hm.. params are getting a bit out of hand

createFieldHtml( id, label, defaultValue, type, labelFirst, isDate, containerCssClasses )

there was this one case where I need to add CSS classes

createFieldHtml( id, label, defaultValue, type, labelFirst, isDate, containerCssClasses, fieldCssClasses, disabled, clearAfter, helpText, uploadPath )

aaaaaaaaaaaaaaaaaaaaa

In defense of boilerplate

I have a hard time putting this into words because it's really something I've been noticing just recently, so I'll make a list:

It seems to me that there is a certain fear of having duplicate lines that stretch out a bit. If it's just a few lines it might be no problem at all. some things are inherently "almost repetitive" (like the example above). I see little chance in optimizing there in the long run.

People love to encapsulate functionality somewhere; if you look at objectively and it seems like it's just "hiding the mess" -- be suspicious! it might be the time for some good old boilerplate

When you have a function that becomes more and more powerful; that takes many different execution paths depending on the input and ultimately does very little -- it might be boilerplate time!

When you add a layer of abstraction on top of another layer of abstraction, but just to make your code shorter (the underlying layer is not meant to be changed) -- boilerplate time!

When you have a function that takes so many parameters that you really need to have named parameters -- maybe it's boilerplate time.

One thing I recently always ask myself is this:

Can I copy&paste into another project without changing anything? if yes, it's okay to encapsulate or put into a library, if no: it's boilerplate time.

This is very much opposed to the general perception that boilerplate is copy&paste code. To me boilerplate is about copy&pasting, but always having to tweak it a tiny bit.

Update: i've just come across an article giving my example above an actual name: "too DRY anti-pattern".

The function gets more parameters and has increasingly complex
  internal logic to control its behavior in different cases. Too DRY
  functions are easy to spot. They have lots of intricate if-then logic
  that try to address a wide diversity of usage. [...] Also, repeating
  code isn’t always a bad thing if the code is small and performs a
  discrete function.

It's a short and interesting read, you can find the article here: Too Dry Anti-Pattern


问:
Testing a file that relies heavily on a static array
I have a .c file that basically manages its own little database of people. There are add, remove, edit and search functions among some others. It has a static array which it uses to store the data.

What is a good way to go about unit testing a file like this? Because the array is static I can't put in my own data.

Should I employ some trickery and make a function that passes out a pointer to the array that gets compiled out in the production version? Should I just test the functions as is and make the data they way I want it via a series of adds and removes? What is the best way to test a file like this?

答:
The best thing you can do is to refactor the code to make it more testable. Not only does this yield immediate benefits in testablity, it has long-term benefits like improved code readability.

If for some reason you can't refactor this code, you add some test-specific code that improves testablity. Namely, something that lets you set the content of the array. You can use #define in C to filter this code out of non-test mode execution.


问:
chat/game server best way to implement, is WCF the way to go?
I'm creating a game on wp7 and it will be an online game played between a max of 4 players. The game will be a turn based game. My question really is what is the best way to do this server wise? is WCF the way to go?

The following is information transferred to and from the server from each player.

Player Chat message

Chat message from other players.

Players points from game.

Picture sent to each player for start of game

答:
SignalR is a .net library that can do what you want. It bills itself as an "Async library for .NET to help build real-time, multi-user interactive web applications." In fact, one of its most compelling demos is a chat site, which I believe is open source.  You can find the source code for JabbR at GitHub.

Scott Hanselman wrote a blog post about SignalR that I feel wrapped up the important parts nicely.


答:
In general, the lower level the language, the more rigorous you have to be about style.  Many of the same style rules to any language are important.  Keep functions short.  Keep like methods together.  Generalize repeated code.  Also, lower level code demands more comments as the code is itself less readable.

In most cases, the methods you'd use to keep things organized are more verbose and more manual.  Basically, in C, you get something like encapsulation by keeping related functions in a single source file and using static globals for any data they need to share.  You can use this to simulate private data in a class.  Or more correctly, this creates something like a "Module", which was the structured programming world's answer to large scale program development before OO came along.

In a similar manner, you can use the same handle method used by system libraries like fopen to create something like a class.  Internally you have a table that maps handles to the "instance data".  Or you can also pass a raw pointer back and forth.

In general, try to be as "functional" as you can.  Avoid globals and side effects and do as much communication as you can with parameter passing.

One big problem is that you have no help with memory management, so you need to be very rigorous about when you allocate and free memory.  Allocated data that goes together should be tied together somehow so that it can all be freed in a single destroy function.  Try to have a general structure to when things are allocated and freed.  Also, allocate on the stack whenever you possibly can.  One big help is the new dynamic arrays in C99.

The other big problem is the complete lack of collection classes.  Best way to solve this is to go looking for third party solutions.  You don't want to spend all of your time debugging custom hash table implementations.

You can go all out and fully implement OO by doing by hand what C++ compilers do for you.  Make classes by creating structs with function pointers for virtual methods.  You can use the same hack C++ does to derive classes by having the "child" class have function pointers to the base class methods in the same order in memory.  This is a bad idea for a real program, but can be an interesting learning exercise.

Title: designing large scale applications in a low level language

Body:
I have been learning C for a while but still get confused about designing large programs within C (a large application such as the Linux kernel).

Moving from Java where you have classes it's difficult to understand how to design a large application in C.

What advice/links can people advise from moving from a high level language to designing applications in a low level language such as C?


问:
Heavy use of static methods in a Java EE web application?
Generally I am asking if this is a norm. The application architecture includes spring and the zk framework. I personally can't help but think this introduces a number of problems. I mean...this is a lot of non synchronized functionality. On top of that we are using an Apache project that, through my browsing of source, appears to use a singleton which has methods that are not thread safe. Changed in a newer version however we are not free to migrate the library at this time.

My real question is, is there a justifiable reason for using a large quantity of static methods in a JavaEE application? I was an ASP.NET dev before this and never encountered this. Instincts dictate this is bad architecture but I am unfamiliar with the stack. There are other warning signs such as a lack of conventional generic convention use. Is this the norm?

What is foreign in one platform may not be in another.

答:
I would say that just by reading your analysis, you're saying there are alot of static methods and singletons.  Static methods shouldn't be an issue by themselves, but if they're being used to proxy calls to the singleton objects, I would work on making those either rock solid, or replacing them with a more sane object model.

Static methods are useful for purely functional purposes, and you'll find both the Scala and Clojure programming languages to use them alot, mostly because they don't need to worry about mutable state.

Reading from this blog post on Java Static/Class methods(I've highlighted a relevant bit):

Static methods use no instance variables of any object of the class
  they are defined in. If you define a method to be static, you will be
  given a rude message by the compiler if you try to access any instance
  variables. You can access static variables, but except for constants,
  this is unusual. Static methods typically take all they data from
  parameters and compute something from those parameters, with no
  reference to variables. This is typical of methods which do some kind
  of generic calculation. A good example of this are the many utility
  methods in the predefined Math class. (See Math and java.util.Random).


问:
How to roll out a feature to only a select few users
A good example of what I'm trying to ask about would be Facebook's new Timeline feature. In the beginning, only a select few were allowed access to timeline. As the feature became more solidified in how it was working and bugs were fixed in it, additional users were allowed access to the feature. At a later date, a large group of users were allowed access to the feature and now, its a general feature to all users. How does a development team manage this type of feature roll out?

I've played with the idea of using configuration settings to selectively control access if something is in testing or in production via a configuration file and conditional if statements in the code. Now while this okay for simple features, I believe that if we tried to implement this in a larger feature set it would become unmanageable.

What would be the best way of managing feature roll outs in this manner?

答:
... and conditional if statements in the code.

Yeah, that's the wrong way to do it.  Whatever feature X is if it's configurable then it must extend or replace something.  Do THAT in the code.  For instance, the FB thing might have something like so:

```<code>class UserPageView;
class HatedTimelineView : UserPageView;
class OldViewEveryoneLikes : UserPageView;
</code>```

Then you'd build a factory that makes UserPageView objects when visiting a user page based on the configuration.  You'd activate that view.  No silly branches.

You want to do it this way because if someone is asking you to change it once, they'll ask for it again.  Further they'll ask to change another thing.  Riddle your architecture with special cases and if's all over the place and you'll have a giant bowl of unmantainable, moldy spaghetti rather than a feature rich, mature product.

Body:
... and conditional if statements in the code.

Yeah, that's the wrong way to do it.  Whatever feature X is if it's configurable then it must extend or replace something.  Do THAT in the code.  For instance, the FB thing might have something like so:

class UserPageView;
class HatedTimelineView : UserPageView;
class OldViewEveryoneLikes : UserPageView;

Then you'd build a factory that makes UserPageView objects when visiting a user page based on the configuration.  You'd activate that view.  No silly branches.

You want to do it this way because if someone is asking you to change it once, they'll ask for it again.  Further they'll ask to change another thing.  Riddle your architecture with special cases and if's all over the place and you'll have a giant bowl of unmantainable, moldy spaghetti rather than a feature rich, mature product.


问:
I'm the .1x programmer at my company. How can I best contribute?
I work at a newly-minted startup of five people.  We have a Ph. D in machine learning, a former member of the RSpec core team, and the guy who compiles the Git binary for OS X.  That's just the employees; the founder has a Ph. D and was CTO for a multi-billion-dollar corporation before leaving to start a (successful) startup, and has now left that to start this one.  We also might get a guy with a Ph. D in math.

Aaaaaaaaand then there's me, college-dropout intern.  I think I'm pretty smart and I'm reading non-stop, but the delta of experience, skill, and knowledge between me and my co-workers is just breathtaking.

So put yourself in their shoes: you've got a bright young intern who has a lot to learn but is at least energetic.  What would be annoying?  What use would you hope to get out of him in the here and now?  What would be pleasantly surprising if it happened?

答:
There is already a lot presented here, so I won't repeat what has been said.

At a quick glance it seems to me that you have experts and a leader with management skills/ideas. That is good, but it is incomplete.

You are the pragmatic one: make their lives easier.

There are at least two areas you can cover:

delving deep into the technical details of the language the startup elected

improve the quality of the code, and smooth the rough corners of working with it

Technical

Those guys are experts in their fields, and this is good, but it does not mean that they know how to code their way out of a paper bag. Honestly, I have seen very bright people writing horrid unmaintenable code.

You have the opportunity to become the technical lead here. Learn the language inside/out, until you know all its subtleties. Learn the idioms the community use. Research the useful libraries that exist out there.

Quality

There are ungrateful, but useful tasks:

who maintains the code source repository ?

who writes/maintains the tests ?

who monitors that the test-suite pass ? and identifies the guilty commits ? and ping the offenders relentlessly ?

There are some steps that help, whether very formal or not:

how do you review the commits ? (is there an ownership associated with some areas of the code ?)

how do you plan the work/tasks ?

There is a lot of peripheral activities around having ideas and writing code.

You have the opportunity to become the quality lead here. Learn the industry best practices (bit of "Agile", bit of scrum, bit of TDD, ...), and compose a process that fit your company. Learn build systems (make, cmake, ninja, whatever), and write the scripts that make building/deploying easy. Check on Jenkins (or whatever) and build a continuous integration server.

They are impressive in their respective domains and that is great. Since at the moment you are non-specialized, I would say it's time for you to identify the weaknesses (you may ask for their opinions too) and fill a(the) gap(s)!


问:
Monopoly game 3D graphical interface
I have created a Monopoly game with a 2D Graphics in Java for my final exam at college.

I feel that the game doesn't look very good and I want to add a 3D Graphics. My problem is that I have never done 3D programming and I don't know how to create 3D objects.

Can someone tell me where can I create 3D objects and what library to use for 3D programming that will allow me to create a 3D graphic interface fast? I have only two more weeks to do this. Can this be done?

答:
Learning both creating 3D graphics and programming 3D rendering in just two weeks will be hard.

3D Graphics programming involve many non trivial concepts to understand, among others matrices and quaternions. If on top of this you want to learn a 3D software like Maya or Blender, this is almost impossible.

As a starter, you should take a look at some OpenGL tutorials.

Now, if I may give my opinion, I would suggest you spend your 2 weeks enhancing the user experience in your game in 2d. A monopoly game doesn't need 3d graphics to be good looking. Instead you could try adding 2d animations or effects, or sound, or game modes.

Edit

Other answers suggest to use higher level engines. Although this can be done, I don't think it falls into the scope of an exam (I assume the author is asked to develop the game by himself).

And I also would recommend understanding the basics of 3D graphics before using a higher level engine (but that's my opinion).

Title: Monopoly game 3D graphical interface


答:
I would suggest working at a higher level. Check out Unity 3D (unity3d.com). It's an order of magnitude easier to work with than coding something directly in OpenGL, and it integrates with many tools. Even when you get past the challenges of getting your first spinning cube on the screen, the next question will be how to display a model. And then, how do you animate it. Those are really complicated and you're going to want to use a framework that makes it easier (e.g. Unity 3D).

Finally, you're going to also want to check out Blender (www.blender.org). It's free, and pretty much the go-to tool when you want to do 3D modeling without spending hundreds or thousands of dollars. It also happens to integrate great with the aforementioned tool.

Title: Monopoly game 3D graphical interface

Body:
I have created a Monopoly game with a 2D Graphics in Java for my final exam at college.

I feel that the game doesn't look very good and I want to add a 3D Graphics. My problem is that I have never done 3D programming and I don't know how to create 3D objects.

Can someone tell me where can I create 3D objects and what library to use for 3D programming that will allow me to create a 3D graphic interface fast? I have only two more weeks to do this. Can this be done?


问:
websites that show real world scenarios for OOP beginners so that they can implement them
Since programmers learn more by implementing the real world scenarios rather then by gaining theoretical knowledge and concepts about programming, I wanted to know that is there any website that tells about real world scenarios for OOP learners so that they can practice their designing skills and implement these scenarios using c#?

Like which can help them making designing decisions for a problem for e.g in which scenario one should use abstract classes, interfaces, virtual overriding etc.

答:
A quick Google search for "OOP use cases" results in many links.  There are also online classes from universities such as Yale, Stanford, and MIT which may prove helpful.

Additionally, there are tons of real-world open-source software available for your examination.  You can write your own version of specific components and then compare your code with theirs.  The differences may reveal some wisdom.


答:
WCF is definitely a good way to go. I'm currently on a project with a mobile component, which uses live, remote data. I'm using WCF and exposing a JSON endpoint, which works very nice.

Problem with WCF is that it might be just a bit to slow for a live game.

Try taking a look at RabbitMQ  as well.

:)

Title: chat/game server best way to implement, is WCF the way to go?

Body:
I'm creating a game on wp7 and it will be an online game played between a max of 4 players. The game will be a turn based game. My question really is what is the best way to do this server wise? is WCF the way to go?

The following is information transferred to and from the server from each player.

Player Chat message

Chat message from other players.

Players points from game.

Picture sent to each player for start of game


问:
What is the significance of 10 characters in this Uncle Bob post?
In this blog posting by Uncle Bob

http://blog.8thlight.com/uncle-bob/2012/04/20/Why-Is-Estimating-So-Hard.html

Author states a possible solution to the problem at hand. He writes "Try this. Break some long string of text up into columns that are 10 characters long. Each time you break a line, record the position of the break, and why you decided to use that position."

The problem is about breaking the Address into 13 character columns, so where does 10 come into play? Or is he using that as another example unrelated to the Gettysburg one?

I'd like to present this to my team in a presentation I have to do soon. I plan to describe the posting, describe the problem and ask my team members for their estimates. After I would go on to explain the rest of the postings premise about why estimations are often blown.

Feel free to offer suggestion on how I can make this a good presentation. I can visualize most of it but towards the end it feels light. After the quick survey, I focus on the problem of estimating the wrong thing and then offer the solution.

答:
Just over five minutes -- bless you python:-

```<code>ss = """Four score and seven years ago our fathers brought forth upon this continent a new nation, conceived in liberty and dedicated to the proposition that all men are created equal…"""
wrds = ss.split()
lo = "";
lt = "";
print "-------------"
for wrd in wrds :
    lo = lt
    lt = lt + " " + wrd
    if len(lt) > 13 :
        print lo;
        lt = wrd;
    next;
print lt;
print "-------------"
</code>```

The algorithm is the nearest I could come up with what you actually do as a human, count past 13 then backtrack to the last space.

Body:
Just over five minutes -- bless you python:-

ss = """Four score and seven years ago our fathers brought forth upon this continent a new nation, conceived in liberty and dedicated to the proposition that all men are created equal…"""
wrds = ss.split()
lo = "";
lt = "";
print "-------------"
for wrd in wrds :
    lo = lt
    lt = lt + " " + wrd
    if len(lt) > 13 :
        print lo;
        lt = wrd;
    next;
print lt;
print "-------------"

The algorithm is the nearest I could come up with what you actually do as a human, count past 13 then backtrack to the last space.


答:
How does a development team manage this type of feature roll out?

It's an easy guess that a system like Facebook is driven largely by databases. All user data is obviously stored in databases, and that likely includes information about how to render the user's data. It's impossible to know exactly how Facebook's database is set up, but it must be the case that a feature like Timeline is rolled out to users in a gradual way by periodically selecting users in the database, based on some criteria, and changing the value(s) of some field(s).

For example, perhaps they have a field in the user table like timeline_status that has values such as not offered, offered, preview, and public. Based on that alone, Facebook's system could decide how to render the user's info page. The FB team could then try out the Timeline feature by selecting some group of users and changing the value of that field.

In practice, I'm sure it's a little more complicated than that, but the core idea is that a user account is just data, and some of that data can determine which features are available. Rolling out a new feature is then just a matter of updating user records in the database.

Title: How to roll out a feature to only a select few users

Body:
A good example of what I'm trying to ask about would be Facebook's new Timeline feature. In the beginning, only a select few were allowed access to timeline. As the feature became more solidified in how it was working and bugs were fixed in it, additional users were allowed access to the feature. At a later date, a large group of users were allowed access to the feature and now, its a general feature to all users. How does a development team manage this type of feature roll out?

I've played with the idea of using configuration settings to selectively control access if something is in testing or in production via a configuration file and conditional if statements in the code. Now while this okay for simple features, I believe that if we tried to implement this in a larger feature set it would become unmanageable.

What would be the best way of managing feature roll outs in this manner?


答:
If you have a public interface for manipulating and querying the data, use it to verify that the behavior is as expected. It's only better not to access the static array directly; the static array is an implementation detail and manipulating it directly will only make it harder to refactor the module in the future.

What might be a problem is if the module internally interacts with the filesystem for e.g. loading and storing data without being explicitly told so; i.e. there is no public load/save API. That's hopefully out of scope for you, because that requires some more work to get testable.

Title: Testing a file that relies heavily on a static array

Body:
I have a .c file that basically manages its own little database of people. There are add, remove, edit and search functions among some others. It has a static array which it uses to store the data.

What is a good way to go about unit testing a file like this? Because the array is static I can't put in my own data.

Should I employ some trickery and make a function that passes out a pointer to the array that gets compiled out in the production version? Should I just test the functions as is and make the data they way I want it via a series of adds and removes? What is the best way to test a file like this?


答:
Think of the feature the same way you would think of a administration feature on a wedsite.

When a page is loading check if the user has the right privileges for the feature if so load it.

Facebook seems to use a location based approach when rolling out new features. This might be as simple as looking at the users ip address to find their location.


答: I also suggest working at a higher level, but Unity is not the right tool for Java. I don't know much about 3D libs in Java, but this http://sourceforge.net/projects/jirr/ might be a start (maybe others know better/easier ones). What XGouchet said is true, also. Learning these libraries is still hard and creating good 3D art for the average programmer even more.</p>

Title: Monopoly game 3D graphical interface


问:
How to gain experience?
This is a problem that I think many people will find very common and some guidance from the expert users around here will be appreciated.

Background

Basically I'm a junior web developer in a team of 6 (all juniors too). 6 months ago our team leader and project manager left the company. Currently we are being managed by a non technical person.

The new manager chose me to act as a technical leader for the rest of the team till the company hires a someone more experienced.

Problem

Although I'm a good developer my experience in providing solution to the company's needs is somewhat lacking. I mean I have no problem implementing solutions or adding new modules to the system as I have been working for 2 years already in PHP and MySql.

The problem is when we are designing a new heavy feature or building a critical module that can't tolerate trial and error.

Check this link for a design issue that I recently had to implement:
https://stackoverflow.com/questions/10529459/building-a-cron-job-scheduler

I can easily build all solutions that were mentioned in the post. The only problem is that I don't have enough experience to choose one of them. My ex-Team leader used to make the hard decisions and I really used to learn a lot from him. However, now he's gone and I'm left out all alone.

Solution

Now There is 2 solutions that I figured would be best for me:

Leave the company ASAP :D and find a better company that can provide me with good experience and increase my knowledge (Although I can't leave the company any time soon due to various reasons).

Find books, references or any available materials for large scale projects or pro web developers techniques. Basically anything beyond simple applications. This is the only option I have right now.

Notes:

I am not looking for resources to learn PHP, MySql, frameworks, ORMs or design patterns. I want knowledge transfer from experienced programmers.

答:
What you are asking for can only be gained with experience. Right now you are in a tough situation, but it is an opportunity for you to learn. I'll be honest: a software company without an experienced technical leader is in trouble.

The problem is when we are designing a new heavy feature or building a
  critical module that can't tolerate trial and error.

When you build a critical feature, you have to perform trials and errors. You have to implement proof of concepts of some solutions and see which one is the best. People who truly know what works and what doesn't are the ones that have tried things, not the one who have read an article on framework X vs framework Y.

Sure, books will help you. But in the end when you are facing a critical choice you have to "loose" some time with prototypes that you will throw away. Try to find what is adapted to your workflow. Advices from blogs and websites like Stack Overflow are great, but sometimes they are not valid because you have specific needs.

So I would suggest to be transparent about this: Say that you lack experience, and make long estimations to take prototyping into account. Say that the alternative is that your company recruit someone more experienced programmer, or that a non-technical person take responsibility for the technical decisions.

Title: How to gain experience?


问:
Why is 80 characters the 'standard' limit for code width?
Why is 80 characters the "standard" limit for code width? Why 80 and not 79, 81 or 100? What is the origin of this particular value? </p>

答: You can thank the IBM punch card for this limit - it had 80 columns:


问:
Should a website use its own public API?
I am starting to write a webservice, and I've built with nodeJS and a RESTfulish approach.

From what I gather:

The advantage is that you don't have to duplicate code.

The disadvantages are that you:

will update the public API frequently, but should be solved with versioning

can't really make service specific caching and optimizations

What is considered best practice? Do sites such as Stack Exchange, Github, Twitter, etc use their own APIs for their clients?

答:
for some reason it won't let me log in as the poster of the question, but it was me. I can't accept your answer, wish I could, it makes a lot of sense.

However, how can you not want to update your API? What about adding new features, removing unpopular ones, refactoring, etc?

OwnerDisplayName: czzarr


问:
When should I backup files?
At our company we are not using a source control so we do backup manually.

My habit is like this: I backup only scripts where I removed code snippets, and those scripts where I only added code snippets I don't backup.

Is it reasonable to backup each time when you change something, or there are some conditions for file subversion? And when we backup changed files, should we only backup that file or all the project?

答: When you start asking questions like "should I backup everything or only parts", then it is time to introduce source control (heck, you should introduce source control before such questions arise). Now. No excuses. Checkin whenever you have finished a small feature slice, and backup the repo daily. </p>

Title: When should I backup files?


答:
you should back up everything, experiencing data loss shouldn't cost you more than a day of lost work.

Get source control and use it, there are good free solutions, and after having used it I can't imagine not having it.

Title: When should I backup files?

Body:
At our company we are not using a source control so we do backup manually.

My habit is like this: I backup only scripts where I removed code snippets, and those scripts where I only added code snippets I don't backup.

Is it reasonable to backup each time when you change something, or there are some conditions for file subversion? And when we backup changed files, should we only backup that file or all the project?


答: Of course using source control does not immediately mean backing up, especially with DVCS such as git or mercurial. I would REALLY (!!!!) recommend you start using it. The next step would be to sync your local git/mercurial repository with a central server for effective backup. But seriously, in professional software development source control is mandatory. In addition, it takes minimal effort to learn, and it yields big returns.</p>

Title: When should I backup files?


答:
Use SVN for sure. Makes life super easy.

I usually commit my work twice a day.

Very very important that you get a source control in place...

Title: When should I backup files?


问:
Generators in Javascript into the new ECMA standard
Generators are being introduced in the new version of the ECMA standards.
Could any one suggest the importance and the usage of generators in the present Javascript world?
Examples of generators in real world problems will be helpful.</p>

答:
I think Generators are best explained in the following article:
https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators

This might be also useful: http://ejohn.org/blog/javascript-18-progress/


答:
As with everything that has been said here -> introduce source control.

If I had a penny for every time that I've read about (or heard from friend's about personal) projects that have either had to be scrapped or started over because they didn't have source control... you know the rest.

Seriously, you/your company might feel like you don't need source control right now, but as when (and I hope this doesn't happen) someone deletes the wrong file, or makes a mistake, or bit-rot takes a crucial file you'll know why we use source control.

If it's a problem with management (as in they don't want to fork out for it), then inform them that there are free solutions. If they don't want a free solution, do a cost analysis of how much money it would cost to start a given project (or all of them) from scratch vs how much a licence will cost them.

If it isn't a management decision, then get on to who ever makes that decision and inform them that they should be considering source control.

I even use source control in my personal projects. One of my big projects was destroyed due to bit-rot, and once was enough to convince me that I needed some form of remote source control (for the record, I use GitHub for me personal stuff and we use Team Cohesion where I work)

EDIT: I came across a related video, just now. It's about how Pixar nearly lost the entirety of Toy Story 2 when someone keyed in the wrong command - http://www.tested.com/videos/44220-how-pixar-almost-lost-toy-story-2-to-a-bad-backup/

Title: When should I backup files?


答:
I back up everything every night onto a series of USB hard disks. The habit helps prevent accidents. I keep one of the disks (taken on a friday) in a different location.

As the others I would also strongly recommend source control.

Title: When should I backup files?


答:
This is like triage, let's fix the obvious things first. So first and foremost, here's 4 of the more well known version control servers, click a link and get installing.

Git

Subversion

Mercurial

TFS Express

Then, if you go for a centralized VCS, backup your repository once a day.

There's no reason not to, and every reason to do it. It really is step #1 to having a reasonable development environment.

Title: When should I backup files?