问:
Object-Oriented Programming: Why "Oriented"?
I am most of the way through my games programming degree.  This is not a computer science degree, so a lot of the theory is eschewed in favour of practical portfolio building and what I see as JIT learning, which is apparently more important in the games industry.  The first subject was "Introduction to Object-Oriented Programming".

That phrase didn't bother me until I learned about the different programming paradigms (I'm getting this list from https://en.wikipedia.org/wiki/Comparison_of_programming_paradigms):

Imperative

Functional

Procedural

Structured

Event-Driven

Object-Oriented

Declarative

Automata-Based

I get that this is not an exhaustive list, and that not all of these concepts are equal, and most of them aren't even exclusive, but I don't understand why most of them get just one word - imperative; functional; declarative - but when we talk about programming with objects, we have to clarify that we are oriented around those objects.  Can't we just use objects?  Can't we just have objects?  Why must they orient us, as our guiding star?

Looking here (https://en.wikipedia.org/wiki/Object-oriented_programming), nowhere is the use of the term "oriented" addressed as its own term.  Only "object" is explained.

Also, I can see for practical reasons why Event-Driven is used, because Event Programming is already a thing that you do when you're running a conference, and Automata Programming makes it sound like you're setting up a robotic production line, so it helps to have additional clarifying words there.

What makes Object Programming, as a phrase, not enough to describe what we do when we use objects in our programming?

Obviously from my tone I'm not too fond of the word "oriented".  It reminds me of my time as a court reporter, listening to lawyer after lawyer use the phrase "in relation to" as a kind of verbal tick.  It didn't mean anything; it was just a term that they used to fill the air while they tried to think of what to say next.  However, I'm not trying to advocate a change of language, I'm just asking why it is the way it is.  If someone knows why it came to be known that way for purely historical, vestigial reasons, then that's the answer.  It will be ammunition if I ever decide to waste my time advocating for a change of language.

On the other hand, if there is actually a useful reason for why a language or piece of code must point towards objects, to the exclusion of all other directions, as opposed to merely having them in its toolbelt, as tools, I would really be interested to learn about it.  I like learning useful things.

答:
I believe you're reading way too much into a simple grammatical construct. Take a look at your list of paradigms, sorted differently for a reason we will get to shortly:

Imperative

Functional

Procedural

Structured

Declarative

Event-Driven

Automata-Based

Object-Oriented

What do the words all have in common? They're all adjectives because they're intended to modify the word "programming". Furthermore, with the exception of "imperative" they're all not "natural" adjectives, but "adjectified" nouns - nouns that actually describe the core of the paradigm: function, structure, automata, and object.

And there are two different ways in which the nouns are adjectified: through a suffix like -al or -ed, or through creating a composite word using a hyphen. Now, as Doc Brown has pointed out, the suffixes that could be used to adjectify "object" result in a different meaning. Which leaves composition.

And I submit that it is pure coincidence or taste that Alan Kay chose to use "oriented" for his composite adjective "object-oriented". It could just as well have been "object-driven", or "object-based", and you might read too much into those as well. Doesn't "driven" sound like some sort of unhealthy obsession?


问:
Is static typing worth the trade-offs?
I began coding in in Python primarily where there is no type safety, then moved to C# and Java where there is. I found that I could work a bit more quickly and with less headaches in Python, but then again, my C# and Java apps are at much higher level of complexity so I have never given Python a true stress test I suppose.

The Java and C# camps make it sound like without the type safety in place, most people would be running into all sorts of horrible bugs left an right and it would be more trouble than its worth.

This is not a language comparison, so please do not address issues like compiled vs interpreted. Is type safety worth the hit to speed of development and flexibilty? WHY?

to the people who wanted an example of the opinion that dynamic typing is faster:

"Use a dynamically typed language during development. It gives you faster feedback, turn-around time, and development speed." -
     http://blog.jayway.com/2010/04/14/static-typing-is-the-root-of-all-evil/

答:
Morgan, I got an interesting idea for you to try: static + dynamic typing. You mentioned Python, C# and Java. Were you aware that there are some pretty good ports of Python to both .NET and Java? In both cases, the ports let you use the libraries of those platforms and/or interoperate with existing code. This gives you several possibilities:

Keep legacy code in static, inflexible language. Use Python for new stuff.

Use Python to prototype new stuff on top of mature platforms. Re-code the components you want to keep in the more mature language.

Use the dynamic language for portions you change often.

Possibly use the dynamic language to play with ideas like modifying running code.

Do everything in the dynamic language except for the critical parts where you use the strongly typed language.

I used these approaches as far back as the late 90's to get around the pain of developing in C/C++. I needed the native libraries and sometimes performance. Yet, I wanted the better syntax, flexibility, safety, etc. So, the trick was carefully combining them to get the right tradeoffs. It was often better in practice than throwing the whole language and legacy code out for another language/platform.

(Note: An answer already said it, but I also want to re-emphasize that dynamic typing != no/weak typing. Many dynamic type systems use strong typing on the inside. The way I think about what makes a type dynamics is that a variables type is determined at runtime, doesn't need a type annotation, and/or might change at runtime.

ContentLicense: CC BY-SA 3.0

Title: Is static typing worth the trade-offs?


问:
Getting related foreign keys from parent entities
I'm thinking about a design issue which affects my project's data base. Supposing there are three diferent tables:

CLIENT

ORDER

PACKING_SLIP

Each order has its client and different packing slips. So there are some foreign keys which are compulsory, there would be clientId for the ORDER and orderId for the PACKING_SLIP table. That makes full sense.

Now suppose in my logic I want to have access to the client from the packing slip. As I'm using an ORM tool as Hibernate, that involves firstly accessing the order from the packing slip and after getting the client from it.

If I want to have access to the client directly, I should add the clientId foreign key also to the PACKING SLIP table.

My question is, is that a correct design if there's a possibility to get the client joining the ORDER table? Isn't it a bit redundant? I think it's a control problem and the data base part shouldn't take care about it...

答:
That's bad design.

Why? Not only it is redundant, but also allows for inconsistencies, i.e., insert, update or delete anomalies.

You could have a packing slip pointing to a client which is different to the one its order points to.

If that happens, a query that joins through ORDER will fetch a different customer that a query that doesn't.

That's because you are violating 2NF.

If you want to avoid having to join through ORDER every time, create a view and select that view. The view still have the join but you will not see it.

In non-transactional databases like data warehouses, you don't have to respect normal forms, but in an OLTP databases like yours seems to be, you will have a lot of headaches if you don't. Obviously there are exceptions, but that's not the case with CLIENT, ORDER and PACKING_SLIP.


问:
Is it necessary to follow the standard, take the C standard for that matter?
There are some very experienced folks on Stack Overflow who always talk about the C standard. People seem to not like non-portable solutions, even if they work for me. Ok, I understand that the standard needs to be followed, but doesn't it put shackles on programmer's creativity?

What are the concrete benefits that come from following a standard? Especially since compilers may implement the standard slightly differently.

答:
The standard is a sort of "contract" between you and your compiler that defines the meaning of your programs. As programmers, we often have a certain mental model of how the language works, and this mental model is often at odds with the standard. (For example, C programmers often think of a pointer as roughly "an integer that denotes a memory address", and therefore assume that it's safe to perform any arithmetic/conversions/manipulations on pointers that one might perform with an integer that denotes a memory address. This assumption does not agree with the standard; it actually imposes very strict restrictions on what you can do with pointers.)

So, what's the advantage of following the standard, rather than your own mental model?

Simply put, it's that the standard is correct, and your own mental model is wrong. Your mental model is typically a simplified view of how things work on your own system, in common cases, with all compiler optimizations disabled; compiler vendors do not generally make an effort to conform to it, especially when it comes to optimizations. (If you don't hold up your end of the contract, you can't expect any specific behavior from the compiler: garbage in, garbage out.)

People seem to not like non-portable solutions, even if they work for me.

It might be better to say, "even if they seem to work for me". Unless your compiler specifically documents that a given behavior will work (that is: unless you're using an enriched standard, consisting of the standard proper plus compiler documentation), you don't know that it really works, or that it's really reliable. For example, signed integer overflow typically results in wrapping on many systems (so, INT_MAX+1 is typically INT_MIN) — except that compilers "know" that signed integer arithmetic never overflows in a (correct) C program, and often perform very surprising optimizations based on this "knowledge".


问:
How to accurately predict release items?
We are having a disconnect between development and business needs.

Business is asking me to produce an accurate list of deliverables for a fixed date and development being difficult to predict is pushing back saying that can only produce a list 80 or 90% accurate.

So my question is, how do we solve this problem? How to provide an accurate list of deliverables weeks before they are completed and fully tested?

答:
Joel Spolsky wrote a good blog about making schedules - Evidence Based Scheduling

Software developers don’t really like to make schedules. Usually, they try to get away without one. “It’ll be done when it’s done!” they say, expecting that such a brave, funny zinger will reduce their boss to a fit of giggles, and in the ensuing joviality, the schedule will be forgotten...

The main ideas are -

Break down work into really small tasks which can be estimated in hours (he suggests maximum 16 hours).

Make sure all devs record their time against tasks and use the difference between recorded time and estimated time to correct future estimates.

Regularly recalculate your schedule based on the latest estimate/recorded time data, so you can see well in advance that your ship date is slipping and adjust your date/feature set accordingly.

It's the sort of process that would probably require a few releases before it became really accurate, so it might not help you right now. It may however be something to consider implementing and might help you push back on the demands for a definite release date for this release.

If nothing else it's an interesting read as is most of Joel's blog.


问:
Can I WTFPL/CC0 parts of a GPL code?
I know I should not expect a lawyer's notice here, but programmers advices would suit me well enough.

I want to publish a program which is derivated from a GPL-licensed program.  I understand from the GPL legal notice that the whole work is to be licensed under GPL as well.

Now, I'd rather publish my work under a more permissive license — namely, I don't care about attribution.  It seems to me that CC0 or WTFPL licenses, for instance, don't need the work to be considered as a whole, right ?  So as they are compatible with the GPL, in principle I could just say something like (in addition to the GPL notice) the following :

This work is GPL as a derivative work of foobar.  In addition, modifications with regards to the original foobar are WTFPL/CC0.

Would this be valid licensing ?

答:
The usual IANAL applies.

Yes, according to http://www.gnu.org/licenses/license-list.html both of these licenses are compatible with the GPL, so based on that it is possible to incorporate code using them in a GPL project.

See http://www.gnu.org/licenses/gpl-faq.html#WhatDoesCompatMean for the explicit declaration of that possibility:

It means that the other license and the GNU GPL are compatible; you can combine code released under the other license with code released under the GNU GPL in one larger program.

The practicalities of this are interesting.  The next bit is just opinion, but I personally wouldn't feel comfortable making something in the order of a one-line or two-line change to an otherwise GPL function, and declaring that one-line or two-line change to be under another license.  On the other hand, if I could split all of my code changes/additions off to a separate module, then I'd feel more comfortable with being able to license that separate module differently.

There are real-world examples of this kind of release.  E.g. in id Software's Quake III Arena source code release, the entire release is - of course - a GPL release, but certain modules are released under other licenses.

Here's tr_animation.c (GPL): https://github.com/id-Software/Quake-III-Arena/blob/master/code/renderer/tr_animation.c

And here's md4.c (RSA): https://github.com/id-Software/Quake-III-Arena/blob/master/code/qcommon/md4.c

It's worth reading the readme to see how the overall licensing of these items was handled: https://github.com/id-Software/Quake-III-Arena/blob/master/README.txt

And as always, consulting with a lawyer knowledgable about software licenses is utterly essential to ensure that you don't overstep the bounds of what you are permitted to do.

Title: Can I WTFPL/CC0 parts of a GPL code?


问:
Using scoped enums for bit flags in C++
An enum X : int (C#) or enum class X : int (C++11) is a type that has a hidden inner field of int that can hold any value. In addition, a number of predefined constants of X are defined on the enum. It is possible to cast the enum to its integer value and vice versa. This is all true in both C# and C++11.

In C# enums are not only used to hold individual values, but also to hold bitwise combinations of flags, as per Microsoft's recommendation. Such enums are (usually, but not necessarily) decorated with the [Flags] attribute. To make the lives of developers easier, the bitwise operators (OR, AND, etc...) are overloaded so that you can easily do something like this (C#):

void M(NumericType flags);

M(NumericType.Sign | NumericType.ZeroPadding);
```

<p>I am an experienced C# developer, but have been programming C++ only for a couple of days now, and I am not known with the C++ conventions. I intend to use a C++11 enum in the exact same way as I was used to do in C#. In C++11 the bitwise operators on scoped enums are not overloaded, so I wanted to overload them. </p>

<p>This solicited a debate, and opinions seem to vary between three options:</p>

<ol>
<li><p>A variable of the enum type is used to hold the bit field, similar to C#:</p>

<pre class="lang-cpp prettyprint-override"><code>void M(NumericType flags);

// With operator overloading:
M(NumericType::Sign | NumericType::ZeroPadding);

// Without operator overloading:
M(static_cast<NumericType>(static_cast<int>(NumericType::Sign) | static_cast<int>(NumericType::ZeroPadding)));
</code>```

But this would counter the strongly typed enum philosophy of C++11's scoped enums.

Use a plain integer if you want to store a bitwise combination of enums:

void M(int flags);

M(static_cast<int>(NumericType::Sign) | static_cast<int>(NumericType::ZeroPadding));
```

<p>But this would reduce everything to an <code>int</code>, leaving you with no clue as to which type you're supposed to put in the method.</p></li>
<li><p>Write a separate class that will overload operators and hold the bitwise flags in a hidden integer field:</p>

<pre class="lang-cpp prettyprint-override"><code>class NumericTypeFlags {
    unsigned flags_;
public:
    NumericTypeFlags () : flags_(0) {}
    NumericTypeFlags (NumericType t) : flags_(static_cast<unsigned>(t)) {}
    //...define BITWISE test/set operations
};

void M(NumericTypeFlags flags);

M(NumericType::Sign | NumericType::ZeroPadding);
</code>```

(full code by user315052)

But then you have no IntelliSense or whatever support to hint you at the possible values.

I know this is a subjective question, but: What approach should I use? What approach, if any, is the most widely recognized in C++? What approach do you use when dealing with bit fields and why?

Of course since all three approaches work, I'm looking for factual and technical reasons, generally accepted conventions, and not simply personal preference.

For example, because of my C# background I tend to go with approach 1 in C++. This has the added benefit that my development environment can hint me on the possible values, and with overloaded enum operators this is easy to write and understand, and quite clean. And the method signature shows clearly what kind of value it expects. But most people here disagree with me, probably for good reason.

答:
A short example of enum-flags below, looks pretty much like C#.

About the approach, in my opinion: less code, less bugs, better code.

```<code>#indlude "enum_flags.h"

ENUM_FLAGS(foo_t)
enum class foo_t
    {
     none           = 0x00
    ,a              = 0x01
    ,b              = 0x02
    };

ENUM_FLAGS(foo2_t)
enum class foo2_t
    {
     none           = 0x00
    ,d              = 0x01
    ,e              = 0x02
    };

int _tmain(int argc, _TCHAR* argv[])
    {
    if(flags(foo_t::a & foo_t::b)) {};
    // if(flags(foo2_t::d & foo_t::b)) {};  // Type safety test - won't compile if uncomment
    };
</code>```

ENUM_FLAGS(T) is a macro, defined in enum_flags.h (less then 100 lines, free to use with no restrictions).

Title: Using scoped enums for bit flags in C++

Body:
A short example of enum-flags below, looks pretty much like C#.

About the approach, in my opinion: less code, less bugs, better code.

#indlude "enum_flags.h"

ENUM_FLAGS(foo_t)
enum class foo_t
    {
     none           = 0x00
    ,a              = 0x01
    ,b              = 0x02
    };

ENUM_FLAGS(foo2_t)
enum class foo2_t
    {
     none           = 0x00
    ,d              = 0x01
    ,e              = 0x02
    };

int _tmain(int argc, _TCHAR* argv[])
    {
    if(flags(foo_t::a & foo_t::b)) {};
    // if(flags(foo2_t::d & foo_t::b)) {};  // Type safety test - won't compile if uncomment
    };

ENUM_FLAGS(T) is a macro, defined in enum_flags.h (less then 100 lines, free to use with no restrictions).


问:
Is Prolog professionally useful?
I learned Prolog many years ago in University. During my professional life, I have never needed to use Prolog. Have I missed something special?

As far as I remember Prolog requires completely different mindset comparing to prominent programming languages.

Is Prolog really ever used to implement something professionally useful?

答: The software that reads and sorts much of the mail in the US and several other countries is written in Prolog, using a highly optimized compiler. The syntax of mail addresses is written in definite clause grammars, which makes maintenance easy and simplifies adapting the reader to the conventions of various countries and industrial users. Postal services often have complicated sets of rules about things like forwarding addresses, post office boxes vs. street address, etc., and these rules are also formulated in Prolog for easy maintenance. </p>

ContentLicense: CC BY-SA 2.5

Title: Is Prolog professionally useful?


问:
Good logging technique for small projects on Java
When I'm coding small projects, I often use System.out.println to print valuable info. It's simple, easy and gets me info. The only drawback I found is that there is no simple way to disable parts of this output for finished application, except for commenting them out, which dirties my code. So, I d like to know, is there any logging techniques, which are as simple as System.out.println, but can be enabled/disabled somehow? Without additional xml configs and such. Because everything I've looked on, looked too much complex and just not worth effort for a small (1-2-3 screens size) application.

Thanks in advance.

答:
A small project might grow and the logging will become unwieldily if not properly taken care of. It will not be a hassle to setup a logger if you have a configuration that you preferred handy. Initially, it could take a bit of time to configure the logger to your whim but subsequently it is just copy the configuration into to the right project directory.

You can checkout these few popular logging tools out there, Log4j and Logback. You can use a logger abstractor like SLF4J where you can switch between different logger implementations. This will save time when comes a situation where only a specific logging library is provided or allowed. In that instance, you only configure the logger abstractors like SLF4J to use the available logger.


问:
Dependency injection ; good practices to reduce boilerplate code
I have a simple question, and I'm not even sure it has an answer but let's try.
I'm coding in C++, and using dependancy injection to avoid global state. This works quite well, and I don't run in unexpected/undefined behaviours very often.

However I realise that, as my project grows I'm writing a lot of code which I consider boilerplate. Worse : the fact there is more boilerplate code, than actual code makes it sometimes hard to understand.

Nothing beats a good example so let's go :

I have a class called TimeFactory which creates Time objects.

For more details (not sure it's relevant) : Time objects are quite complex because the Time can have different formats, and conversion between them is neither linear, nor straightforward. Each "Time" contains a Synchronizer to handle conversions, and to make sure they have the same, properly initialized, synchronizer, I use a TimeFactory. The TimeFactory has only one instance and is application wide, so it would qualify for singleton but, because it's mutable, I don't want to make it a singleton

In my app, a lot of classes need to create Time objects. Sometimes those classes are deeply nested.

Let's say I have a class A which contains instances of class B, and so on up to class D.  Class D need to create Time objects.

In my naive implementation, I pass the TimeFactory to the constructor of class A, which passes it to the constructor of class B and so on until class D.

Now, imagine I have a couple of classes like TimeFactory and a couple of class hierarchies like the one above : I loose all the flexibility and readability I'm suppose to get using dependancy injection .

I'm starting to wonder if there isn't a major design flaw in my app ...
Or is this a necessary evil of using dependancy injection ?

What do you think ?

答:
This aims to be a complementary answer to Doc Brown, and also to respond to unanswered comments of Dinaiz that are still related to the Question.

What you probably need is a framework for doing DI. Having complex hierarchies does not necessarily means bad design, but if you have to inject a TimeFactory bottom-up (from A to D) instead of injecting directly to D then probably there's something wrong with the way you are doing Dependency Injection.

A singleton? No thanks. If you need only one istance make it shared across your application context (Using a IoC container for DI like Infector++ requires just to bind TimeFactory as single istance), here's the example (C++11 by the way, but so C++. Maybe move to C++11 already? You get Leak-Free application for free):

```<code>Infector::Container ioc; //your app's context

ioc.bindSingleAsNothing<TimeFactory>(); //declare TimeFactory to be shared
ioc.wire<TimeFactory>(); //wire its constructor

// if you want to be sure TimeFactory is created at startup just request it
// (else it will be created lazily only when needed)
auto myTimeFactory = ioc.buildSingle<TimeFactory>();
</code>```

Now the good point of a IoC container is that you don't need to pass time factory up to D. if your class "D" need time factory, just put time factory as constructor parameter for class D.

```<code>ioc.bindAsNothing<A>(); //declare class A
ioc.bindAsNothing<B>(); //declare class B
ioc.bindAsNothing<D>(); //declare class D

//constructors setup
ioc.wire<D, TimeFactory>(); //time factory injected to class D
ioc.wire<B, D>(); //class D injected to class B
ioc.wire<A, B>(); //class B injected to class A
</code>```

as you see you inject TimeFactory only once. How to use "A"? Very simple, every class is injected, builded in the main or istantiated with a factory.

```<code>auto myA1 = ioc.build<A>(); //A is not "single" so many different istances
auto myA2 = ioc.build<A>(); //can live at same time
</code>```

every time you create class A it will be automatically (lazy istantiation) injected with all dependencies up to D and D will be injected with TimeFactory, so by calling only 1 method you have your complete hierarchy ready (and even complex hierachies are solved this way removing A LOT of boiler plate code): You don't have to call "new/delete" and that's very important because you can separate application logic from glue code.

D can create Time objects with informations that only D can have

That's easy, your TimeFactory have a "create" method, then just use a different signature "create(params)" and you are done. Parameters that are no dependencies are often resolved this way. This also remove the duty of injecting things like "strings" or "integers" because that just add extra boiler plate.

Who creates who? IoC container creates istances and factories, the factories creates the rest (factories can create different objects with arbitrary parameters, so you don't really need a state for factories). You can still use the factories as wrappers for the IoC Container: generally speaking Injectin the IoC Container is very bad and is the same of using a service locator. Some people solved the problem by wrapping the IoC Container with a factory (this is not strictly necessary, but has the advantage that the hierarchy is solved by the Container and all your factories becomes even easier to maintain).

```<code>//factory method
std::unique_ptr<myType> create(params){
    auto istance = ioc->build<myType>(); //this code's agnostic to "myType" hierarchy
    istance->setParams(params); //the customization you needed
    return std::move(istance);
}
</code>```

Also don't abuse dependency injection, simple types can just be class' members or local scoped variables. This seem obvious but I saw people injecting "std::vector" just because there was a DI framework that allowed that. Always remember Demeter's law: "Inject only what you really need to inject"

Body:
This aims to be a complementary answer to Doc Brown, and also to respond to unanswered comments of Dinaiz that are still related to the Question.

What you probably need is a framework for doing DI. Having complex hierarchies does not necessarily means bad design, but if you have to inject a TimeFactory bottom-up (from A to D) instead of injecting directly to D then probably there's something wrong with the way you are doing Dependency Injection.

A singleton? No thanks. If you need only one istance make it shared across your application context (Using a IoC container for DI like Infector++ requires just to bind TimeFactory as single istance), here's the example (C++11 by the way, but so C++. Maybe move to C++11 already? You get Leak-Free application for free):

Infector::Container ioc; //your app's context

ioc.bindSingleAsNothing<TimeFactory>(); //declare TimeFactory to be shared
ioc.wire<TimeFactory>(); //wire its constructor

// if you want to be sure TimeFactory is created at startup just request it
// (else it will be created lazily only when needed)
auto myTimeFactory = ioc.buildSingle<TimeFactory>();

Now the good point of a IoC container is that you don't need to pass time factory up to D. if your class "D" need time factory, just put time factory as constructor parameter for class D.

ioc.bindAsNothing<A>(); //declare class A
ioc.bindAsNothing<B>(); //declare class B
ioc.bindAsNothing<D>(); //declare class D

//constructors setup
ioc.wire<D, TimeFactory>(); //time factory injected to class D
ioc.wire<B, D>(); //class D injected to class B
ioc.wire<A, B>(); //class B injected to class A

as you see you inject TimeFactory only once. How to use "A"? Very simple, every class is injected, builded in the main or istantiated with a factory.

auto myA1 = ioc.build<A>(); //A is not "single" so many different istances
auto myA2 = ioc.build<A>(); //can live at same time

every time you create class A it will be automatically (lazy istantiation) injected with all dependencies up to D and D will be injected with TimeFactory, so by calling only 1 method you have your complete hierarchy ready (and even complex hierachies are solved this way removing A LOT of boiler plate code): You don't have to call "new/delete" and that's very important because you can separate application logic from glue code.

D can create Time objects with informations that only D can have

That's easy, your TimeFactory have a "create" method, then just use a different signature "create(params)" and you are done. Parameters that are no dependencies are often resolved this way. This also remove the duty of injecting things like "strings" or "integers" because that just add extra boiler plate.

Who creates who? IoC container creates istances and factories, the factories creates the rest (factories can create different objects with arbitrary parameters, so you don't really need a state for factories). You can still use the factories as wrappers for the IoC Container: generally speaking Injectin the IoC Container is very bad and is the same of using a service locator. Some people solved the problem by wrapping the IoC Container with a factory (this is not strictly necessary, but has the advantage that the hierarchy is solved by the Container and all your factories becomes even easier to maintain).

//factory method
std::unique_ptr<myType> create(params){
    auto istance = ioc->build<myType>(); //this code's agnostic to "myType" hierarchy
    istance->setParams(params); //the customization you needed
    return std::move(istance);
}

Also don't abuse dependency injection, simple types can just be class' members or local scoped variables. This seem obvious but I saw people injecting "std::vector" just because there was a DI framework that allowed that. Always remember Demeter's law: "Inject only what you really need to inject"


答:
There is middle ground between System.out.println and a logging library: write your own object that shields the details. This object can be configured with a simple system property:

```<code>class LogUtils {
    private boolean isEnabled = false;

    // TODO: constructor

    public static void log(String msg) {
        if (isEnabled) { System.out.println(msg); }
    }
}
</code>```

The danger here is that you may want to add features such as log levels (INFO, DEBUG, ERROR). If you add features, you're on the path of "reinventing the wheel" and should consider a proper logging library.

Title: Good logging technique for small projects on Java

Body:
When I'm coding small projects, I often use System.out.println to print valuable info. It's simple, easy and gets me info. The only drawback I found is that there is no simple way to disable parts of this output for finished application, except for commenting them out, which dirties my code. So, I d like to know, is there any logging techniques, which are as simple as System.out.println, but can be enabled/disabled somehow? Without additional xml configs and such. Because everything I've looked on, looked too much complex and just not worth effort for a small (1-2-3 screens size) application.

Thanks in advance.

Body:
There is middle ground between System.out.println and a logging library: write your own object that shields the details. This object can be configured with a simple system property:

class LogUtils {
    private boolean isEnabled = false;

    // TODO: constructor

    public static void log(String msg) {
        if (isEnabled) { System.out.println(msg); }
    }
}

The danger here is that you may want to add features such as log levels (INFO, DEBUG, ERROR). If you add features, you're on the path of "reinventing the wheel" and should consider a proper logging library.


问:
How should I store an old project?
As a freelancer, I come across many projects. Its almost impossible to store a backup of all of the projects on my laptop. What are some better options to store them?</p>

答:
There are two sensible options, depending on the likelihood you'll need to look at them again:

Burn the old projects to two DVDs, storing one "off site" somewhere

Storing them in the cloud on something like Dropbox

Title: How should I store an old project?


答: Don't follow rules IF your project is about special projects, for example a gov project or army one, but you need to follow rules IF you are talking about an open source or large project with a distributed team.</p>

Title: Is it necessary to follow the standard, take the C standard for that matter?

Body:
There are some very experienced folks on Stack Overflow who always talk about the C standard. People seem to not like non-portable solutions, even if they work for me. Ok, I understand that the standard needs to be followed, but doesn't it put shackles on programmer's creativity?

What are the concrete benefits that come from following a standard? Especially since compilers may implement the standard slightly differently.


答: I have mine stored on USB flash drives.  I keep a fireproof safe to store flash drives and 'must' have development CDs.</p>

Title: How should I store an old project?

Body: As a freelancer, I come across many projects. Its almost impossible to store a backup of all of the projects on my laptop. What are some better options to store them?</p>


问:
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.

答:
YAGNI

(You ain't gonna need it)

This approach has cost me hours and hours when I had to implement features on an existing codebase, where careful planning would have included these features beforehand.

Ideas of mine have often been rejected because of YAGNI, and most of the times someone had to pay for that decision later.

(Of course one could argue that a well-designed codebase would also allow features to be added later on, but reality is different)


答:
You can use the JDK's inbuilt logger

http://docs.oracle.com/javase/6/docs/api/java/util/logging/package-summary.html

It's very simple to use and configure, yet flexible (e.g. logging levels) when you want it to be. Also, you don't have to include any third party libraries.

This example shows two ways of using the log method

```<code>import java.util.logging.Level;
import java.util.logging.Logger;

..........

private static final Logger logger = Logger.getLogger(Test.class.getName());

    private void setup(String val1) {
        logger.info("Entering method with value [" + val1 + "]");
        //Do something here
        try {
        //Do something here
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Failed to prune the hedge", e);
        }
    }
</code>```

The logging levels are arranged according to a hierarchy - enabling logging for a specific Level implies logging will be done for that level and "higher" levels. E.g. enabling Level.INFO will log all messages logged with INFO, WARNING and SEVERE messages.

If you wish to turn off logging at a specific level, you can configure this in a properties file. E.g. a configuration file with only console output and logging enabled for Level.WARNING and above will look like this

```<code>handlers = java.util.logging.ConsoleHandler
.level = WARNING
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
</code>```

This file needs to be included with a system property when you run your program

```<code>   java -Djava.util.logging.config.file -cp <your classpath> <your main class>
</code>```

Body:
You can use the JDK's inbuilt logger

http://docs.oracle.com/javase/6/docs/api/java/util/logging/package-summary.html

It's very simple to use and configure, yet flexible (e.g. logging levels) when you want it to be. Also, you don't have to include any third party libraries.

This example shows two ways of using the log method

import java.util.logging.Level;
import java.util.logging.Logger;

..........

private static final Logger logger = Logger.getLogger(Test.class.getName());

    private void setup(String val1) {
        logger.info("Entering method with value [" + val1 + "]");
        //Do something here
        try {
        //Do something here
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Failed to prune the hedge", e);
        }
    }

The logging levels are arranged according to a hierarchy - enabling logging for a specific Level implies logging will be done for that level and "higher" levels. E.g. enabling Level.INFO will log all messages logged with INFO, WARNING and SEVERE messages.

If you wish to turn off logging at a specific level, you can configure this in a properties file. E.g. a configuration file with only console output and logging enabled for Level.WARNING and above will look like this

handlers = java.util.logging.ConsoleHandler
.level = WARNING
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

This file needs to be included with a system property when you run your program

   java -Djava.util.logging.config.file -cp <your classpath> <your main class>


问:
When to write tests for a new class using BDD?
I've been practicing behaviour driven development (BDD). I understand that you have to write tests that test the behaviour of the code, and this will allow the design of your code to evolve and take shape.

When doing BDD and I find I need to refactor my code into a better design, and that refactor happens to involve extracting some code into a new class, when do I start writing tests for that new class?

Or are tests not needed for that class at all since it's a implementation detail and the behaviour of it should already be tested with the existing test coverage?

答:
Part of the joy of BDD is moving away from that word, "test".

Instead, we have examples which illustrate how the code behaves, both at a system and a unit level.

Those examples let us question whether the behavior of the code is appropriate. For instance, we might have a "Shop" class which is responsible for recording stock, as well as for taking orders.

When we look at the examples, we can see the following behaviors illustrated:

```<code>should Record Stock
should Take Orders
</code>```

One of the things we can do when we stop thinking about "tests" is think, "should it? Should it really?"

We can see that these are two different aspects of behaviour, so we know that maybe the shop should delegate those aspects. We can start thinking about what a shop should really do.

What's the purpose of a shop? Well, it's to make money for the owner, and to provide goods for customers. Recording stock and taking orders are just part of that.

So maybe a shop:

```<code>should Make Money
should Provide Goods for Customers
</code>```

Wow. We've got the ability to take orders and to record stock, but we haven't actually got any way of finding out if we're making money or providing the correct goods. Maybe we should do that, too...

By using natural language, and talking about what a piece of code should do, we can have conversations with our business to see if we understand their requirements correctly, then carry the language they use into the code.

At that point, a lot of things become more obvious.

If our code isn't doing what it says it should, it might be the wrong code.

If our code is doing what it should, but doesn't say it's doing it, we need to refactor things like method and variable names, and maybe extract some methods too.

If something else should be doing what our code is doing, we need to move things into different classes.

If our application isn't doing what it should, we can have a chat with the business about what they really want it to do instead.

Using a shop is a pretty simple example, but I hope you can see that by thinking of code not in terms of "test" and "how to test", but in terms of "how it should behave", we end up using the Single Responsibility Principle... well, more responsibly. And we probably learn a lot about our domain, while creating readable and maintainable code, at the same time.

This is the heart of BDD. I find that experienced BDDers tend to need to refactor less, because they end up creating things that adhere to the SRP to begin with.

Body:
Part of the joy of BDD is moving away from that word, "test".

Instead, we have examples which illustrate how the code behaves, both at a system and a unit level.

Those examples let us question whether the behavior of the code is appropriate. For instance, we might have a "Shop" class which is responsible for recording stock, as well as for taking orders.

When we look at the examples, we can see the following behaviors illustrated:

should Record Stock
should Take Orders

One of the things we can do when we stop thinking about "tests" is think, "should it? Should it really?"

We can see that these are two different aspects of behaviour, so we know that maybe the shop should delegate those aspects. We can start thinking about what a shop should really do.

What's the purpose of a shop? Well, it's to make money for the owner, and to provide goods for customers. Recording stock and taking orders are just part of that.

So maybe a shop:

should Make Money
should Provide Goods for Customers

Wow. We've got the ability to take orders and to record stock, but we haven't actually got any way of finding out if we're making money or providing the correct goods. Maybe we should do that, too...

By using natural language, and talking about what a piece of code should do, we can have conversations with our business to see if we understand their requirements correctly, then carry the language they use into the code.

At that point, a lot of things become more obvious.

If our code isn't doing what it says it should, it might be the wrong code.

If our code is doing what it should, but doesn't say it's doing it, we need to refactor things like method and variable names, and maybe extract some methods too.

If something else should be doing what our code is doing, we need to move things into different classes.

If our application isn't doing what it should, we can have a chat with the business about what they really want it to do instead.

Using a shop is a pretty simple example, but I hope you can see that by thinking of code not in terms of "test" and "how to test", but in terms of "how it should behave", we end up using the Single Responsibility Principle... well, more responsibly. And we probably learn a lot about our domain, while creating readable and maintainable code, at the same time.

This is the heart of BDD. I find that experienced BDDers tend to need to refactor less, because they end up creating things that adhere to the SRP to begin with.


答:
Well there are many ways to store backups but because the backups are not going to change over time and you might want to store them for a long time (probably >20 years). I would suggest that you use multipliable technologies to make backups, you never know if a technology will be unable with the dates technology in the future. I would recommend that you use at least 3 or more of this option. Store them in different places, like one at home, one at the office and so on in case of a fire or something else that would destroy the device. Also use different file system technologies, preferable at least one that is open source.

CD

DVD

Blu-ray

Hard disk drive

USB flash drive

Solid-state drive

I would not recommend using online backup like dropbox or any thing like this, you never know if company that is holding your data will go bankruptcy in the future. Also if you use a service like this the company have access to your source code and can do what the hell they want with it. You can use this as a complement to what i have mention before but i would strong suggest you encrypt the file before uploading them.

Title: How should I store an old project?


答:
I'm a bit confused by your question:

Why are you storing backups on a laptop in a first place? Laptops are for work; backups are generally stored on dedicated servers or tapes or, for smaller companies, on external hard disks.

Why do you find it impossible? Because of the space it takes? What exactly is inside which takes so much place?

So, how should one store a backup of all projects? Here's some guidelines.

Have dedicated hardware dealing with backups.

Ideally and if you have enough money, you would have a machine in your datacenter which will make regular scheduled backups of your version control. Depending on the size of the changes and the risk you can take, it may be scheduled as well to one backup per hour as to one backup per week.

In a less expensive environment, you'll simply have an external hard drive you'll plug regularly to do the backups on it. Beware of everything which requires manual effort or any manual intervention: while an automated process done exclusively by machines is mostly flawless, people asked to do the same task again and again can potentially forget doing it, or make a mistake or simply stop doing it, because they consider that they have "more important things to do than a backup" in time pressure context.

Always keep at least one backup off-site

There is small benefit in making backups if all those backups are stored in the same room or building. In case of fire, flood or anything which can affect the entire building, your data can be lost altogether with every backup you made.

Test your backup strategy

A few weeks ago, I was about to make a RAID configuration change on a NAS. The operation could potentially result in losing all the files. I had a not so bad backup strategy and data replication, and was sure it works pretty well, but I still decided to check twice if everything is fine. It appeared that a configuration change done a few months ago made the backup tool switching several backup destination paths to directories the backup tool wasn't able to create. This meant that I could have lost more than three months of a part of important data.

Do incremental backups of version control

Version control can grow pretty fast if you work on large projects with lots of people involved. Dumping tens of thousands of revisions for several gigabytes of backup every hour or every day will be too expensive in terms of resources.

Most version control systems allow you to dump specific revisions. In my company, moving from daily entire dump to daily incremental dump allowed to considerably decrease the load on version control server, as well as waste more than 85% less space on backup machine (which also means wasting less network bandwidth for off-site backups).

Don't delete your work

Some small companies with no money to buy new hardware are often tempted to delete some of the files involved in the original projects.

For example, a photographer may be asked to delete RAW files which may waste 30 MB or more space when he finished to work on a photograph and has the final JPEG.

Another example is to wipe out older versions from a version control, for example older than one year.

In both cases, the idea is bad, and can have important implications. For example, it would be difficult for a photographer to prove that a stolen photo was belonging to him if the only thing he has is the same JPEG that the stolen one. Wiping out older versions from version control erases statistical data which can be used in business intelligence.

Check what's stored in your version control

Once, when I was auditing a company, I found that the version control was slow, fat, and totally unusable. Commits took forever, and desperate programmers preferred not doing any commit at all and share the source through the network directly. There were no backups, because it was practically impossible to do a dump, given the size of it.

After a bit of search, it appeared that every compiled file was in source control: every binary, every temp file, everything. This meant, if I remember well, that each commit was 30 MB in size. Indeed, this made it nearly impossible to do commits and increased the number of times programmers would go out to smoke or drink coffee.

Storing anything binary in an ordinary version control is an issue. This includes storing images or Word documents.

If your repository is fat, there may be something wrong in a way you use it. Check what's inside, and react in consequence.

Title: How should I store an old project?


问:
Best way to develop a php open source application
I started to create a php application I'd like to make open source in the near future. However I do not know, if it's needed to follow any kind of code/documentation convention, to make it more usable and acceptable when released.

Is there any model, to follow, to develop a good open source application?

Do you think it is necessary(or better) to develop it entirely, or for the most, object oriented?

答:
So you're looking for a commonly accepted, worldwide used standard?

For PHP, there is none. There is PSR, but I won't say it's commonly accepted.

This being said, depending on the place you want to publish your application to, there may be some hints about the preferred convention. You may look at some already published projects and see what are the standards they follow.


问:
Storing application users in SQL: create a new "Users" table or use built-in database user management?
I am specifically interested in SQL Server, but the same question applies in general.  When creating a new application, the way I see it, there are two options:

Create a table called "Users" and store the user name, password, etc.  Set up one database user called "application" (and possibly more users for various components of the system).

Set up each application user as the database user.  This may allow for easier single log on setup on Windows-based systems.

Which approach is generally preferred?  Why?  What are the drawbacks and benefits?

答:
Database user management is intended to provide a mechanism for the users to access the database itself. Using it to store, for example, the accounts of your customers, is a perversion: it was never designed for that. By reusing this mechanism for anything else, you're decreasing your database security level, especially if you don't have a DBA capable of configuring the security aspects flawlessly.

If you are using SQL Server in Mixed mode (i.e. you can authenticate using not only your Active Directory credentials, but also by providing a user name and a password), you shouldn't do it in the first place.

If you are wondering whether Active Directory accounts can replace User table (especially your point "This may allow for easier single log on setup on Windows-based systems"), then see the recent question: Using a Directory Service instead of a Database.


答:
The technology changes too fast, there are definitely NOT any "forever" solutions that don't involve you maintaining your backups.  Keep multiple copies in different places and media.  Today, flash drives and online backup look like good choices.  As those good choices become less good and eventually die, keep moving on to new good choices.  (My first set of archives were on paper tape.  Second on 7 track mag tape.. you get the idea)

Long term archives should be in sealed checksummed packages, so you can at least
be sure they're complete and uncorrupted.

Don't overlook the importance of storing your archives with context.  I guarantee that in 20 years, you won't have a clue what most of the crap you saved was for; and worse, that if there's some particular gem you're looking for you'll despair of locating it or using it once located.

Title: How should I store an old project?


问:
Implementing scrum-but for first time: how to deal with technical pre-requisites?
After working Scrum(ish) in a previous workplace, I am trying to implement it in my new place of work for a brand new project (I am no scrum expert). We have some pre-requisites to code before we can begin working on the stories (which are being groomed in the mean time). Things like database design, api design, etc. We plan to use two week iterations and it's just not clear to me how the first one (or two) can provide something useful to the customer and "potentially shippable" if we first have to "lay down some groundwork" ? Any ideas on how to treat this?

-----edit / rephrase-----

How do we incorporate initial non client-visible preliminary work (e.g., database design, api, etc) into the Scrum process?

答:
Treat it like any other story. Having stable design benefits the customer. Having schema design benefits the customer. Describe what you need to have done, and what the deliverables are. Prioritize them between technical staff and the product owners, then pull them off and complete them.

Another thing to consider is that these technical stories are similar to technical debt issues that likely have more commentary/research about them.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
Let's see:

Write programs in C++

without the use of version control,

no refactoring,

no Boost,

limited STL (I argued and won on this one),

use unverified subcontractor libraries,

without a memory profiler (to help fix subcontractor work),

no unit testing,

stick to 3 letter names for member function names,

no test environment (VM not allowed either) just push to production


问:
Accessing Repositories from Domain
Say we have a task logging system, when a task is logged, the user specifies a category and the task defaults to a status of 'Outstanding'. Assume in this instance that Category and Status have to be implemented as entities. Normally I would do this:

Application Layer:

```<code>public class TaskService
{
    //...

    public void Add(Guid categoryId, string description)
    {
        var category = _categoryRepository.GetById(categoryId);
        var status = _statusRepository.GetById(Constants.Status.OutstandingId);
        var task = Task.Create(category, status, description);
        _taskRepository.Save(task);
    }
}
</code>```

Entity:

```<code>public class Task
{
    //...

    public static void Create(Category category, Status status, string description)
    {
        return new Task
        {
            Category = category,
            Status = status,
            Description = descrtiption
        };
    }
}
</code>```

I do it like this because I am consistently told that entities should not access the repositories, but it would make much more sense to me if I did this:

Entity:

```<code>public class Task
{
    //...

    public static void Create(Category category, string description)
    {
        return new Task
        {
            Category = category,
            Status = _statusRepository.GetById(Constants.Status.OutstandingId),
            Description = descrtiption
        };
    }
}
</code>```

The status repository is dependecy injected anyway, so there is no real dependency, and this feels more to me thike it is the domain that is making thedecision that a task defaults to outstanding. The previous version feels like it is the application layeer making that decision. Any why are repository contracts often in the domain if this should not be a posibility?

Here is a more extreme example, here the domain decides urgency:

Entity:

```<code>public class Task
{
    //...

    public static void Create(Category category, string description)
    {
        var task = new Task
        {
            Category = category,
            Status = _statusRepository.GetById(Constants.Status.OutstandingId),
            Description = descrtiption
        };

        if(someCondition)
        {
            if(someValue > anotherValue)
            {
                task.Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.UrgentId);
            }
            else
            {
                task.Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.SemiUrgentId);
            }
        }
        else
        {
            task.Urgency = _urgencyRepository.GetById
                (Constants.Urgency.NotId);
        }

        return task;
    }
}
</code>```

There is no way you would want to pass in all possible versions of Urgency, and no way you would want to calculate this business logic in the application layer, so surely this would be the most appropriate way?

So is this a valid reason to access repositories from the domain?

EDIT: This could also be the case on non static methods:

```<code>public class Task
{
    //...

    public void Update(Category category, string description)
    {
        Category = category,
        Status = _statusRepository.GetById(Constants.Status.OutstandingId),
        Description = descrtiption

        if(someCondition)
        {
            if(someValue > anotherValue)
            {
                Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.UrgentId);
            }
            else
            {
                Urgency = _urgencyRepository.GetById
                    (Constants.Urgency.SemiUrgentId);
            }
        }
        else
        {
            Urgency = _urgencyRepository.GetById
                (Constants.Urgency.NotId);
        }

        return task;
    }
}
</code>```

答:
I have been trying to solve the same problem for sometime, I decided I want to be able to call Task.UpdateTask() like that, although I would rather it would be domain specific, in your case maybe I would call it Task.ChangeCategory(...) to indicate an action and not just CRUD.

anyways, I tried your problem and came up with this... have my cake and eat it too. The idea is that actions take place on the entity but without injection of all the dependencies. Instead work is done in static methods so they can access state of the entity. The factory puts its all together and normally will have everything it needs to do the work the entity needs to do. Client code now looks clean and clear and your entity is not dependent on any repository injection.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnitTestProject2
{
    public class ClientCode
    {
        public void Main()
        {
            TaskFactory factory = new TaskFactory();
            Task task = factory.Create();
            task.UpdateTask(new Category(), "some value");
        }

    }
    public class Category
    {
    }

    public class Task
    {
        public Action<Category, String> UpdateTask { get; set; }

        public static void UpdateTaskAction(Task task, Category category, string description)
        {
            // do the logic here, static can access private if needed
        }
    }

    public class TaskFactory
    {
        public Task Create()
        {
            Task task = new Task();
            task.UpdateTask = (category, description) =>
                {
                    Task.UpdateTaskAction(task, category, description);
                };

            return task;
        }

    }
}
</code>```

Title: Accessing Repositories from Domain

Body:
I have been trying to solve the same problem for sometime, I decided I want to be able to call Task.UpdateTask() like that, although I would rather it would be domain specific, in your case maybe I would call it Task.ChangeCategory(...) to indicate an action and not just CRUD.

anyways, I tried your problem and came up with this... have my cake and eat it too. The idea is that actions take place on the entity but without injection of all the dependencies. Instead work is done in static methods so they can access state of the entity. The factory puts its all together and normally will have everything it needs to do the work the entity needs to do. Client code now looks clean and clear and your entity is not dependent on any repository injection.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnitTestProject2
{
    public class ClientCode
    {
        public void Main()
        {
            TaskFactory factory = new TaskFactory();
            Task task = factory.Create();
            task.UpdateTask(new Category(), "some value");
        }

    }
    public class Category
    {
    }

    public class Task
    {
        public Action<Category, String> UpdateTask { get; set; }

        public static void UpdateTaskAction(Task task, Category category, string description)
        {
            // do the logic here, static can access private if needed
        }
    }

    public class TaskFactory
    {
        public Task Create()
        {
            Task task = new Task();
            task.UpdateTask = (category, description) =>
                {
                    Task.UpdateTaskAction(task, category, description);
                };

            return task;
        }

    }
}


问:
Source control and compilation tool chain
I am a single developer working on a large system.  I was recently informed that there may be an opportunity to recruit another developer or maybe two.  I have incorporated source control into my approach using Subverison and Tortoise SVN.

I was talking to another developer who I used to work with recently and he reminded me about the concept of a compilation tool chain and specifically nightly builds for unit testing.  I have two questions:

Is it good practice for all software development teams to use unit testing and nightly builds? Is there any criteria that identifies teams that are more suitable than others for nightly builds.

How do developers identify areas suitable for unit testing? I assume that you look at the use cases.  I assume that these use cases could include different processing methods e.g. users interacting with a web application or a batch processing job that runs via a scheduled task each night.

答:
Yes, continuous integration is a good practice for any project. For very small projects, the infrastructure required for continuous integration may be an overkill, but this doesn't apply to small projects done within a large company: a large company should already have the required infrastructure, and adding a small project to it shouldn't be too difficult.

As for unit testing, you have to take decision yourself:

Larger projects are better suited for unit testing than smaller ones,

Business-critical projects are better suited for unit testing than projects which don't do anything critical,

Projects which follow practices like code review of all new code, formal reviews, etc. need less unit testing than projects which are not.

Side note: the fact that you waited until other developers were added to your team before starting to use version control is disturbing. You're expected to use version control for any project, including the one where you work alone.


答:
Of course you need to have some technical prerequisites in place before you can start a project. For example, you need a solid working environment, a decision which technology to use (programming language, frameworks etc). Wrong decisions at the beginning of the project could slow down or even cause the project to fail, so one should be very smart about them. It is the responsibility of the team to make the best decision there.

Do not spend too much time on it though. The real job is to finish things for the customer. And this is only accomplished by creating customer-facing features, not by designing some detail of the application or creating the infrastructure the project needs to run at all.

You will always find something to tweak in the DB schema that just is not perfect, yet. Or there simply is not enough testing infrastructure, yet. This is not a particular "beginning of the project problem". The same goes for the architecture. Target on scaling the architecture rather than designing a lot up front. There is a great talk by Mich Lacey on exactly this topic which I would recommend to watch. It illustrates how you could approach this.

Create a mindset where you concentrate on finishing not on polishing things and think of every technical detail as exactly that what it is - a technical detail. It does not interest the customer (and should not interest the customer) a single bit.

Title: Implementing scrum-but for first time: how to deal with technical pre-requisites?

Body:
After working Scrum(ish) in a previous workplace, I am trying to implement it in my new place of work for a brand new project (I am no scrum expert). We have some pre-requisites to code before we can begin working on the stories (which are being groomed in the mean time). Things like database design, api design, etc. We plan to use two week iterations and it's just not clear to me how the first one (or two) can provide something useful to the customer and "potentially shippable" if we first have to "lay down some groundwork" ? Any ideas on how to treat this?

-----edit / rephrase-----

How do we incorporate initial non client-visible preliminary work (e.g., database design, api, etc) into the Scrum process?


问:
Java naming conventions vs. C++/C naming conventions
I am a Java developer who is starting to pick up more and more C++/C (yes I know they're different, bear with me).  One thing that struck me as odd was the different naming conventions used by these languages.  In Java, is is very common to see something like this:

```<code>int someVariable = someFunction(someParameterToPass);
</code>```

However, in C++/C, it would look a bit different:

```<code>int some_variable = some_function(some_parameter_to_pass);
</code>```

The reason I ask is because I (alone, no team) have just started a large project using C++, and right now am using Java naming conventions in my code (it's what I'm used to).  But then I add in some external libraries to my code and it mixes the naming conventions together.  I understand the code easily, and use the differences to tell my code apart from library code.

Should I switch my naming convention for the sake of readability to others (while the LOC is relatively low), or stick with what I'm doing now (since I am the only developer)?

Note - my code has been peer reviewed, however, the reviewers mainly focused on the function of the code. They didn't mention mixed conventions, and I did not specifically ask them about this. They also didn't have experience with switching naming conventions.

答:
The naming convention that you cite is from the standard library. The naming convention is practical rather than prescriptive. That is, the standard library must introduce symbols in order to use the library. The standard library wants to limit those symbols to a fixed set so that developers using the library are not surprised when there may be a name collision.

The standard library has chosen to use all lower case names with underscore separators.

Your choice as a developer is to use that convention or another convention determined by you and your team. Using the same convention may read nicer, but can also cause name collisions (which are often resolved using namespaces, which can add to the noise in the code.)

The common C++ (non-standard library) convention is quite close to Java.

From your example, a C++ naming convention would typically use a capitalized function name and a capitalized class name. To extend your example:

```<code>int someVariable = SomeClass.SomeMethod(someParameterToPass);
</code>```

Another difference is the JavaBeans convention of preceding method names with get, set, or is prefixes. Many C++ conventions use a similar convention. However, some groups prefer to use the ability of C++ to overload method names so that get and set have the same name but different signatures.

```<code>class Foo
{
public:
    Bar GetBar() const;
    void SetBar(const Bar& bar);
};
</code>```

vs

```<code>class Foo
{
public:
    Bar Bar() const;
    void Bar(const Bar& bar);
};
</code>```

Some groups prefer to not use overloading, preferring the former convention.

Body:
The naming convention that you cite is from the standard library. The naming convention is practical rather than prescriptive. That is, the standard library must introduce symbols in order to use the library. The standard library wants to limit those symbols to a fixed set so that developers using the library are not surprised when there may be a name collision.

The standard library has chosen to use all lower case names with underscore separators.

Your choice as a developer is to use that convention or another convention determined by you and your team. Using the same convention may read nicer, but can also cause name collisions (which are often resolved using namespaces, which can add to the noise in the code.)

The common C++ (non-standard library) convention is quite close to Java.

From your example, a C++ naming convention would typically use a capitalized function name and a capitalized class name. To extend your example:

int someVariable = SomeClass.SomeMethod(someParameterToPass);

Another difference is the JavaBeans convention of preceding method names with get, set, or is prefixes. Many C++ conventions use a similar convention. However, some groups prefer to use the ability of C++ to overload method names so that get and set have the same name but different signatures.

class Foo
{
public:
    Bar GetBar() const;
    void SetBar(const Bar& bar);
};

vs

class Foo
{
public:
    Bar Bar() const;
    void Bar(const Bar& bar);
};

Some groups prefer to not use overloading, preferring the former convention.


答:
In short: Yes, using builds generated by a build server as well as unit testing are good practice for every project.

Using a build server to generate your continuous and nightly builds will benefit you greatly. I would consider it good practice for every project among other continuous integration practices. Ideally, there is no difference between continuous and nightly builds, but this depends on the project size. You may think that your developer computer already acts as the integration environment, which is true and may be sufficient for small-scale projects. But imagine revisiting the project again in the future. It will always be helpful if you have your integration environment stored in some VM where it does not interfere with all the other projects that you have done. Your tool chain is configured correctly in that environment and nothing broke just because you had to update some tool. Just use it again, whenever you need it and be sure that the project works in the environment that it is targeted for. Also, you will always have your builds in once place not scattered over your personal machine. They are ready to be tested continuously as well. So this is somehow a prerequisite to testing every commit which in turn ensures that you catch errors early.

As for testing: A project so small that it does not have a good architecture might be hard to test, so size of the project influences the ability to test. However, most modern languages already come with a set of standard test tools and there are some principles that help you design your application in a way that it is easy to test. Unit testing might be easier than testing the entire system, however you should always have system tests covering your use cases.

Title: Source control and compilation tool chain

Body:
I am a single developer working on a large system.  I was recently informed that there may be an opportunity to recruit another developer or maybe two.  I have incorporated source control into my approach using Subverison and Tortoise SVN.

I was talking to another developer who I used to work with recently and he reminded me about the concept of a compilation tool chain and specifically nightly builds for unit testing.  I have two questions:

Is it good practice for all software development teams to use unit testing and nightly builds? Is there any criteria that identifies teams that are more suitable than others for nightly builds.

How do developers identify areas suitable for unit testing? I assume that you look at the use cases.  I assume that these use cases could include different processing methods e.g. users interacting with a web application or a batch processing job that runs via a scheduled task each night.


问:
Strategy for keeping secret info such as API keys out of source control?
I'm working on a website that will allow users to log in using OAuth credentials from the likes of Twitter, Google, etc.  To do this, I have to register with these various providers and get a super-secret API key that I have to protect with pledges against various body parts.  If my key gets ganked, the part gets yanked.

The API key has to travel with my source, as it is used at runtime to perform authentication requests.  In my case, the key must exist within the application in a configuration file or within the code itself.  That isn't a problem when I build and publish from a single machine.  However, when we throw source control into the mix, things get more complicated.

As I'm a cheap bastard, I'd much prefer to use free source control services such as TFS in the cloud or GitHub.  This leaves me with a slight conundrum:

How can I keep my body intact when my API keys are in my code, and my code is available in a public repository?

I can think of a number of ways to handle this, but none of them are that satisfying.

I could remove all private info from code, and edit it back in after deployment.  This would be a severe pain to implement (I won't detail the many ways), and isn't an option.

I could encrypt it.  But as I have to decrypt it, anyone with the source could figure out how to do so.  Pointless.

I could pay for private source control.  LOL j/k spend money?  Please.

I could use language features to segregate sensitive info from the rest of my source and therefore keep it from source control.  This is what I'm doing now, but it could easily be screwed up by mistakenly checking in the secret file.

I'm really looking for a guaranteed way to ensure I don't share my privates with the world (except on snapchat) that will work smoothly through development, debugging and deployment and be foolproof as well.  This is completely unrealistic.  So what realistically can I do?

Technical details:  VS2012, C# 4.5, source control is either going to be TF service or GitHub.  Currently using a partial class to split the sensitive keys off in a separate .cs file that won't be added to source control.  I think GitHub may have the advantage as .gitignore could be used to ensure that partial class file isn't checked in, but I've screwed that up before.  Am hoping for a "oh, common issue, this is how you do it" but I may have to settle for "that doesn't suck as much as it could have", :/

答:
Don't put your secret information in your code. Put it into a configuration file which is read by your code at startup. Configuration files shouldn't be put on version control, unless they are the "factory defaults", and then they shouldn't have any private information.

See also the question Version control and personal configuration file for how to do this well.


问:
Best data structure for representing English verb forms
I need to come up with a data structure to keep information about English verb forms. In most cases a verb can be in one of 4 forms: base, present participle, past participle and past simple, for example:

take

taking

taken

took

It's seemingly easy to define 4 types for each form and be over with it. However there are few exceptions that ruin this simple idea.

Present single third person form, which is in our example would be "takes".

Copular verb "to be" has multiple irregular forms in the present tense: "am", "is", "are" and "was" and "were" in the past tense

Verbs like "may" that don't inflect in the present single third person form: "she may".

What data structure would be efficient, accurate yet unambiguous for representing such information (with exceptional cases) given the following requirements have to be met:

for an arbitrary form answer the question what conjugations the form represents

for an arbitrary conjugation and a form answer the question whether the form represents the given conjugation or not?

答:
In the case where there are a lot of exceptions to the rules of how your data can be organized, you will have to relate them in a light and shallow way.  In this case, you can use a "tag"-like system.

Your objects could store two things: the base form (as a string), as well as a map of "tags."  This map would hold an enum value as its key and a word string as its value.  The enum would list all the types of forms that are possible.

Using this method, your object is required to have a base form, but can then have either 0 or 1 of each of the other types of forms.  If it doesn't have a certain form associated with it, you simply don't include it, and it would be your language's equivalent of null.


答:
You might model the base forms and then add any number of exceptions by coding the conjugation (an enumeration) and the form (a string).

E.g.

```<code>typedef struct {
    verb_t *verb;
    char    *base;
    char    *pres_part;
    char    *past_part;
    char    *past_simple;
    EXCEPT  **exception; // NULL-terminated
}
</code>```

and the exception would be

```<code>typedef struct tag_exception {
    conj_t  conjugation;           // Enum: CONJ_3S for third person singular
    char    *form;                 // "is"
}
</code>```

Then you should model some "rules" for the other cases. For example, say that our "rule" is that third person singular is made by adding a -s. Then not having an exception for take, 3S means that it is takes. A verb such as be would have an exception, is.

To answer the first question, you scan the base forms, scan the exceptions if any, and generate the remaining "rule" forms.

To answer the second question, you basically do the same, except that you check if the form ID matches.

Title: Best data structure for representing English verb forms

Body:
I need to come up with a data structure to keep information about English verb forms. In most cases a verb can be in one of 4 forms: base, present participle, past participle and past simple, for example:

take

taking

taken

took

It's seemingly easy to define 4 types for each form and be over with it. However there are few exceptions that ruin this simple idea.

Present single third person form, which is in our example would be "takes".

Copular verb "to be" has multiple irregular forms in the present tense: "am", "is", "are" and "was" and "were" in the past tense

Verbs like "may" that don't inflect in the present single third person form: "she may".

What data structure would be efficient, accurate yet unambiguous for representing such information (with exceptional cases) given the following requirements have to be met:

for an arbitrary form answer the question what conjugations the form represents

for an arbitrary conjugation and a form answer the question whether the form represents the given conjugation or not?

Body:
You might model the base forms and then add any number of exceptions by coding the conjugation (an enumeration) and the form (a string).

E.g.

typedef struct {
    verb_t *verb;
    char    *base;
    char    *pres_part;
    char    *past_part;
    char    *past_simple;
    EXCEPT  **exception; // NULL-terminated
}

and the exception would be

typedef struct tag_exception {
    conj_t  conjugation;           // Enum: CONJ_3S for third person singular
    char    *form;                 // "is"
}

Then you should model some "rules" for the other cases. For example, say that our "rule" is that third person singular is made by adding a -s. Then not having an exception for take, 3S means that it is takes. A verb such as be would have an exception, is.

To answer the first question, you scan the base forms, scan the exceptions if any, and generate the remaining "rule" forms.

To answer the second question, you basically do the same, except that you check if the form ID matches.


答:
Pure Git way

.gitignore included file with private data

Use a local branch, in which you replace TEMPLATE with DATA

Use smudge/clean filters, in which (local) filter's script perform bidirectional replacement TEMPLATE <-> DATA

Mercurial way

MQ-patch(es) on top of dummy code, which replace TEMPLATE with DATA (changesets are public, patch is private)

Keyword extension with specially designed keywords (expanded only in your working directory)

SCM-agnostic way

Have replacement of keywords as part of build/deploy process

Title: Strategy for keeping secret info such as API keys out of source control?

Body:
I'm working on a website that will allow users to log in using OAuth credentials from the likes of Twitter, Google, etc.  To do this, I have to register with these various providers and get a super-secret API key that I have to protect with pledges against various body parts.  If my key gets ganked, the part gets yanked.

The API key has to travel with my source, as it is used at runtime to perform authentication requests.  In my case, the key must exist within the application in a configuration file or within the code itself.  That isn't a problem when I build and publish from a single machine.  However, when we throw source control into the mix, things get more complicated.

As I'm a cheap bastard, I'd much prefer to use free source control services such as TFS in the cloud or GitHub.  This leaves me with a slight conundrum:

How can I keep my body intact when my API keys are in my code, and my code is available in a public repository?

I can think of a number of ways to handle this, but none of them are that satisfying.

I could remove all private info from code, and edit it back in after deployment.  This would be a severe pain to implement (I won't detail the many ways), and isn't an option.

I could encrypt it.  But as I have to decrypt it, anyone with the source could figure out how to do so.  Pointless.

I could pay for private source control.  LOL j/k spend money?  Please.

I could use language features to segregate sensitive info from the rest of my source and therefore keep it from source control.  This is what I'm doing now, but it could easily be screwed up by mistakenly checking in the secret file.

I'm really looking for a guaranteed way to ensure I don't share my privates with the world (except on snapchat) that will work smoothly through development, debugging and deployment and be foolproof as well.  This is completely unrealistic.  So what realistically can I do?

Technical details:  VS2012, C# 4.5, source control is either going to be TF service or GitHub.  Currently using a partial class to split the sensitive keys off in a separate .cs file that won't be added to source control.  I think GitHub may have the advantage as .gitignore could be used to ensure that partial class file isn't checked in, but I've screwed that up before.  Am hoping for a "oh, common issue, this is how you do it" but I may have to settle for "that doesn't suck as much as it could have", :/


答:
When developing desktop applications for a customer office, per user accounts can have a lot of advantages (integrated security etc)

But for web application with potentially 1000000’s of users, it is quite common to use a service account to the SQL server, and run a custom users table which makes account selfservice a viable option. Just make sure to use proper encryption (salt and hash) for your passwords!

Title: Storing application users in SQL: create a new "Users" table or use built-in database user management?

Body:
I am specifically interested in SQL Server, but the same question applies in general.  When creating a new application, the way I see it, there are two options:

Create a table called "Users" and store the user name, password, etc.  Set up one database user called "application" (and possibly more users for various components of the system).

Set up each application user as the database user.  This may allow for easier single log on setup on Windows-based systems.

Which approach is generally preferred?  Why?  What are the drawbacks and benefits?


答:
he reminded me about the concept of a compilation tool chain and specifically nightly builds for unit testing

Nightlies for unit-testing?! WTF?! It's totally unrelated things

Back to questions

Is it good practice for all software development teams to use unit testing

Yes

and nightly builds?

Irrelevant and conditional-specific. Unit-testing implies a) automatic b) full coverage c) in-house d) formal testing of the whole products (ideally, with CI - after each change in codebase), nightlies - a) manual checks b) with less frequently c) by external testers d) mostly only some - widely used or recently fixed - functionality of product

Is there any criteria that identifies teams that are more suitable than others for nightly builds.

Mass products, targeted on deeply different user's systems (which can't be easy reproduced in developer's environment), may be better tested by users in every-day usage

How do developers identify areas suitable for unit testing?

Nohow, Unit Testing must test all and any operations, performed by product by testing elementary blocks of product

I assume that you look at the use cases

No, it's Functional Testing, where you test how it work, in Unit Testing you perform more low-level test "Will it work?" "Will it work always?" "Does all rare-cases catched?" etc


问:
Data structure for accessing units of measure
TL;DR - I'm trying to design an optimal data structure to define units within a unit of measure.

A Unit of measure is essentially a value (or quantity) associated with a unit.  SI Units have seven bases or dimensions.  Namely: length, mass, time, electric current, temperature, amount of substance (moles), and luminous intensity.

This would be straightforward enough, but there are a number of derived units as well as rates that we frequently use.  An example combined unit would be the Newton: kg * m / s^2 and an example rate would be tons / hr.

We have an application that relies heavily upon implied units.  We'll embed the units within the variable or column name.  But this creates problems when we need to specify a unit of measure with different units.  Yes, we can convert the values at input and display but this generates a lot of overhead code that we'd like to encapsulate within its own class.

There are a number of solutions out on codeplex and other collaborative environments.  The licensing for the projects is agreeable but the project itself usually ends up being too lightweight or too heavy.  We're chasing our own unicorn of "just right."

Ideally, I could define a new unit of measure using something like this:

UOM myUom1 = new UOM(10, volts);

  UOM myUom2 = new UOM(43.2, Newtons);

Of course, we use a mix of Imperial and SI units based upon our clients' needs.

We also need to keep this structure of units synchronized with a future database table so we can provide the same degree of consistency within our data too.

What's the best way of defining the units, derived units, and rates that we need to use to create our unit of measure class?  I could see using one or more enums, but that could be frustrating for other developers.  A single enum would be huge with 200+ entries whereas multiple enums could be confusing based upon SI vs Imperial units and additional breakdown based upon categorization of the unit itself.

Enum examples showing some of my concerns:

myUnits.Volt

  myUnits.Newton

  myUnits.meter

SIUnit.meter

  ImpUnit.foot
  DrvdUnit.Newton

  DrvdUnitSI.Newton

  DrvdUnitImp.FtLbs

Our set of units in use is pretty well defined and it's a finite space.  We do need the ability to expand and add new derived units or rates when we have client demand for them.  The project is in C# although I think the broader design aspects are applicable to multiple languages.

One of the libraries I looked at allows for free-form input of units via string.  Their UOM class then parsed the string and slotted things accordingly.  The challenge with this approach is that it forces the developer to think and remember what the correct string formats are.  And I run the risk of a runtime error / exception if we don't add additional checks within the code to validate the strings being passed in the constructor.

Another library essentially created too many classes that the developer would have to work with.  Along with an equivalent UOM it provided a DerivedUnit and RateUnit and so on.  Essentially, the code was overly complex for the problems we're solving.  That library would essentially allow any:any combinations (which is legitimate in the units world) but we're happy to scope our issue (simplify our code) by not allowing every possible combination.

Other libraries were ridiculously simple and hadn't even considered operator overloading for example.

In addition, I'm not as worried about attempts at incorrect conversions (for example: volts to meters).  Devs are the only ones who will access at this level at this point and we don't necessarily need to protect against those types of mistakes.

答:
I just released Units.NET on Github and on NuGet.

It gives you all the common units and conversions. It is light-weight, unit tested and supports PCL.

Towards your question:

This is on the lighter end of the implementations. Focus is to aid in unambiguous representation, conversion and construction of units of measurement.

There is no equation solver, it does not automatically derive new units from calculations.

One big enum for defining units.

UnitConverter class for converting dynamically between units.

Immutable data structures for converting explicitly between units.

Overloaded operators for simple arithmetic.

Extending to new units and conversions is a matter of adding a new enum for dynamic conversion and adding a unit of measurement class, like Length, for defining explicit conversion properties and operator overloading.

I have yet to see the holy grail of solutions in this domain. As you state, it can easily become way too complex or too verbose to work with. Sometimes, it's best to keep things simple and for my needs this approach has proven sufficient.

Explicit conversion

```<code>Length meter = Length.FromMeters(1);
double cm = meter.Centimeters; // 100
double yards = meter.Yards; // 1.09361
double feet = meter.Feet; // 3.28084
double inches = meter.Inches; // 39.3701

Pressure p = Pressure.FromPascal(1);
double kpa = p.KiloPascals; // 1000
double bar = p.Bars; // 1 × 10-5
double atm = p.Atmosphere; // 9.86923267 × 10-6
double psi = p.Psi; // 1.45037738 × 10-4
</code>```

Dynamic conversion

```<code>// Explicitly
double m = UnitConverter.Convert(1, Unit.Kilometer, Unit.Meter); // 1000
double mi = UnitConverter.Convert(1, Unit.Kilometer, Unit.Mile); // 0.621371
double yds = UnitConverter.Convert(1, Unit.Meter, Unit.Yard); // 1.09361

// Or implicitly.
UnitValue val = GetUnknownValueAndUnit();

// Returns false if conversion was not possible.
double cm;
val.TryConvert(LengthUnit.Centimeter, out cm);
</code>```

Body:
I just released Units.NET on Github and on NuGet.

It gives you all the common units and conversions. It is light-weight, unit tested and supports PCL.

Towards your question:

This is on the lighter end of the implementations. Focus is to aid in unambiguous representation, conversion and construction of units of measurement.

There is no equation solver, it does not automatically derive new units from calculations.

One big enum for defining units.

UnitConverter class for converting dynamically between units.

Immutable data structures for converting explicitly between units.

Overloaded operators for simple arithmetic.

Extending to new units and conversions is a matter of adding a new enum for dynamic conversion and adding a unit of measurement class, like Length, for defining explicit conversion properties and operator overloading.

I have yet to see the holy grail of solutions in this domain. As you state, it can easily become way too complex or too verbose to work with. Sometimes, it's best to keep things simple and for my needs this approach has proven sufficient.

Explicit conversion

Length meter = Length.FromMeters(1);
double cm = meter.Centimeters; // 100
double yards = meter.Yards; // 1.09361
double feet = meter.Feet; // 3.28084
double inches = meter.Inches; // 39.3701

Pressure p = Pressure.FromPascal(1);
double kpa = p.KiloPascals; // 1000
double bar = p.Bars; // 1 × 10-5
double atm = p.Atmosphere; // 9.86923267 × 10-6
double psi = p.Psi; // 1.45037738 × 10-4

Dynamic conversion

// Explicitly
double m = UnitConverter.Convert(1, Unit.Kilometer, Unit.Meter); // 1000
double mi = UnitConverter.Convert(1, Unit.Kilometer, Unit.Mile); // 0.621371
double yds = UnitConverter.Convert(1, Unit.Meter, Unit.Yard); // 1.09361

// Or implicitly.
UnitValue val = GetUnknownValueAndUnit();

// Returns false if conversion was not possible.
double cm;
val.TryConvert(LengthUnit.Centimeter, out cm);


问:
Is R6RS backwards compatible with R5RS?
Is the new Scheme standard, R6RS which was published in 2007, backwards compatible with the older standard R5RS? If not, is there a compatibility mode in R6RS?</p>

答:
I'm afraid it's not backward compatible.
A R6RS file is expected to start with importing a library. If your files started with:

```<code>#!r6rs
(import (rnrs))
</code>```

Most of R6RS will be available. R5RS won't recognize those two lines so in an R5RS-version you need to skip those two or comment them out. It's possible to do this with standard command line tools so you can write one source file an generate for the other though. You won't be able to use load from R6RS so your code must reside (or end up) in one file.

Some implementations however, e.g. ikarus,  allows to run code without the #!r6rs and the initial import form even if it's a R6RS implementation, but the standard requires them in an top level R6RS program.

In appendix E of the R6RS standard you can see what have changed and you should avoid using new features. I.e. you should use the R5RS specification and write lower case since R6RS is case sensitive.

The newer R7RS draft specification is mainly based on R5RS and their import form is the same as R6RS. Their library implementation however, though similar, is incompatible with R6RS since they deliberately used different forms. Anyway, to be compatible with R5RS you cannot create libraries without having to do a lot of processing to create a compatible R5RS-version.

Title: Is R6RS backwards compatible with R5RS?

Body:
I'm afraid it's not backward compatible.
A R6RS file is expected to start with importing a library. If your files started with:

#!r6rs
(import (rnrs))

Most of R6RS will be available. R5RS won't recognize those two lines so in an R5RS-version you need to skip those two or comment them out. It's possible to do this with standard command line tools so you can write one source file an generate for the other though. You won't be able to use load from R6RS so your code must reside (or end up) in one file.

Some implementations however, e.g. ikarus,  allows to run code without the #!r6rs and the initial import form even if it's a R6RS implementation, but the standard requires them in an top level R6RS program.

In appendix E of the R6RS standard you can see what have changed and you should avoid using new features. I.e. you should use the R5RS specification and write lower case since R6RS is case sensitive.

The newer R7RS draft specification is mainly based on R5RS and their import form is the same as R6RS. Their library implementation however, though similar, is incompatible with R6RS since they deliberately used different forms. Anyway, to be compatible with R5RS you cannot create libraries without having to do a lot of processing to create a compatible R5RS-version.