答:
You will be able to go a long way in Physics without knowing anything about "professional" style (speaking from experience). But I have seen many people waste endless time because they lost track of what they where doing or after having grown their code for a couple of years just got lost in it's complexity (even in academia there is no "throw away" code, but things stick around much longer than you think initially).

I would suggest you get a head start into algorithms and data structures, e.g. with this course. After that you should be able to think about performance on a more productive level and be able to follow up with e.g. articles on Wikipedia.

After that get used to what is available in the core of your language, e.g. for C++ cppreference.com. I would also strongly recommend you to read the Effective C++ series by Scott Meyers and Accelerated C++ by Koenig & Moe. At least for C++ this will give you a solid foundation on the language side.

In parallel you should try to get to know your tools well. It isn't unlikely that you will develop your code under Linux, so try to learn how to get more diagnostics (warnings) from your compilers (at least gcc and clang). Also learn about static analysis tools like cppcheck or clang's scan-build. Learn how to make these tools an integral part of your development process, e.g. by integrating them into your build setup (yes, you should use at least GNU make, or even better something like GNU autotools/cmake/...). You should also add profiling tools to your toolset. For C++ I would strongly recommend you to learn everything you can about valgrind which can profile on a very low level (it also can help you find resource leaks).

All this will help you focus on what you care most about (your research) instead of wasting time finding bugs or doing useless optimizations. Of course this is almost impossible to sell to an advisor, but they (and you) will be impressed but the speed with which you be able to get reliable results.

You mentioned C and C++, but for numeric calculations I cannot recommend Python with numpy and scipy enough. It allows you to write in a clean pretty clean language on a very high level (you can even work interactively), while still taking advantage of extremely optimized routines implemented in C, C++ and FORTRAN. Also, interfacing your own C or C++ code with Python is almost trivial.

ContentLicense: CC BY-SA 4.0


问:
Teaching myself, as a physicist, to become a better programmer
I've always liked physics, and I've always liked coding, so when I got the offer for a PhD position doing numerical physics (details are not relevant, it's mostly parallel programming for a cluster) at a university, it was a no-brainer for me.

However, as most physicists, I'm self taught. I don't have broad background knowledge about how to code in an object oriented way, or the name of that specific algorithm that optimizes the search in some kD tree.

Since all my work so far has been more concerned about the physics and the scientific results, I undoubtedly have some bad habits - more so because my coding is my own, and not really teamwork. I have mostly used C since it is very straightforward and "what you write is what you get" - no need for fancy abstractions. However, I have recently switched to C++ since I'd like to learn more about the power that comes with abstraction, and it's pretty C-like (syntax-wise at least).

How do I teach myself to code in a good, abstract way like a graduate in computer science?

I know my code is efficient, but I want it to be elegant as well, and readable. Keep in mind that I don't have time to read several 1000-page tomes about abstract programming. I need to spend time on actual, physics related research (my supervisor would laugh at me if he knew I spent time thinking about how to program elegantly). How do I assess if my work is also good from a programmer's perspective?

答:
My background is a little similar to yours-I was a physics graduate who was self taught programming. After I graduated though I took on a few IT jobs and ultimately became a software engineer; including a bit of time working on OpenGDA (software used to run experiments at various synchrotron sites).

The main thing I learned about the questions you have while I was getting here is that it's much easier to get these skills from other people than to try to pick them up yourself. An experienced mentor can easily help you identify where your code is weak or where common patterns and practices can help you. While I learned how to write C and Objective-C by myself, I didn't know exactly what I didn't know (if you see what I mean) until I was working with other people on the same code. The fact you're asking here for advice means you're doing better than I did already :-).

Now, where do you find a tame professional software engineer? I recently joined MentorNet, a system that partners experienced programmers with protégés.

But you don't have to go for a formal system like that. Finding a local programmer meet-up group (or where your university's software engineering department goes after work on Friday) is a great place to start.

ContentLicense: CC BY-SA 3.0


答:
How do I assess if my work is also good from a programmer's perspective?

Is it correct? Does it produce correct results in all cases?

Are other people able to read and easily understand your code?

When your supervisor says "Great, now make it also do X..." do you have to rewrite a lot of code?

When you've written a program, does it become a tool that you can use over and over, or is it a use it once and throw it away kind of thing?

If you can answer yes, yes, no, and 'yes, I try to make tools rather than one-off calculations', then you're doing pretty well already. A good deal of what we do as programmers is meant to help with the kinds of things listed above.

Title: Teaching myself, as a physicist, to become a better programmer

Body:
I've always liked physics, and I've always liked coding, so when I got the offer for a PhD position doing numerical physics (details are not relevant, it's mostly parallel programming for a cluster) at a university, it was a no-brainer for me.

However, as most physicists, I'm self taught. I don't have broad background knowledge about how to code in an object oriented way, or the name of that specific algorithm that optimizes the search in some kD tree.

Since all my work so far has been more concerned about the physics and the scientific results, I undoubtedly have some bad habits - more so because my coding is my own, and not really teamwork. I have mostly used C since it is very straightforward and "what you write is what you get" - no need for fancy abstractions. However, I have recently switched to C++ since I'd like to learn more about the power that comes with abstraction, and it's pretty C-like (syntax-wise at least).

How do I teach myself to code in a good, abstract way like a graduate in computer science?

I know my code is efficient, but I want it to be elegant as well, and readable. Keep in mind that I don't have time to read several 1000-page tomes about abstract programming. I need to spend time on actual, physics related research (my supervisor would laugh at me if he knew I spent time thinking about how to program elegantly). How do I assess if my work is also good from a programmer's perspective?


问:
Does C# give you "less rope to hang yourself" than C++?
Joel Spolsky characterized C++ as "enough rope to hang yourself".  Actually, he was summarizing "Effective C++" by Scott Meyers:

It's a book that basically says, C++ is enough rope to hang yourself, and then a couple of extra miles of rope, and then a couple of suicide pills that are disguised as M&Ms...

I don't have a copy of the book, but there are indications that much of the book relates to pitfalls of managing memory which seem like would be rendered moot in C# because the runtime manages those issues for you.

Here are my questions:

Does C# avoid pitfalls that are avoided in C++ only by careful programming?  If so, to what degree and how are they avoided?

Are there new, different pitfalls in C# that a new C# programmer should be aware of?  If so, why couldn't they be avoided by the design of C#?

答:
In my opinion, the dangers of C++ are somewhat exaggerated.

The essential danger is this: While C# lets you perform "unsafe" pointer operations using the unsafe keyword, C++ (being mostly a superset of C) will let you use pointers whenever you feel like it.  Besides the usual dangers inherent with using pointers (which are the same with C), like memory-leaks, buffer overflows, dangling pointers, etc., C++ introduces new ways for you to seriously screw things up.

This "extra rope", so to speak, which Joel Spolsky was talking about, basically comes down to one thing: writing classes which internally manage their own memory, also known as the "Rule of 3" (which can now be called the Rule of 4 or Rule of 5 in C++11).  This means, if you ever want to write a class that manages its own memory allocations internally, you have to know what you're doing or else your program will likely crash.  You have to carefully create a constructor, copy constructor, destructor, and assignment operator, which is surprisingly easy to get wrong, often resulting in bizarre crashes at runtime.

HOWEVER, in actual every-day C++ programming, it's very rare indeed to write a class that manages its own memory, so it's misleading to say that C++ programmers always need to be "careful" to avoid these pitfalls.  Usually, you'll just be doing something more like:

```<code>class Foo
{
    public:

    Foo(const std::string& s)
        : m_first_name(s)
    { }

    private:

    std::string m_first_name;
};
</code>```

This class looks pretty close to what you'd do in Java or C# - it requires no explicit memory management (because the library class std::string takes care of all that automatically), and no "Rule of 3" stuff is required at all since the default copy constructor and assignment operator is fine.

It's only when you try to do something like:

```<code>class Foo
{
    public:

    Foo(const char* s)
    {
        std::size_t len = std::strlen(s);
        m_name = new char[len + 1];
        std::strcpy(m_name, s);
    }

    Foo(const Foo& f); // must implement proper copy constructor

    Foo& operator = (const Foo& f); // must implement proper assignment operator

    ~Foo(); // must free resource in destructor

    private:

    char* m_name;
};
</code>```

In this case, it can be tricky for novices to get the assignment, destructor and copy constructor correct.  But for most cases, there's no reason to ever do this.  C++ makes it very easy to avoid manual memory management 99% of the time by using library classes like std::string and std::vector.

Another related issue is manually managing memory in a way that doesn't take into account the possibility of an exception being thrown.  Like:

```<code>char* s = new char[100];
some_function_which_may_throw();
/* ... */
delete[] s;
</code>```

If some_function_which_may_throw() actually does throw an exception, you're left with a memory leak because the memory allocated for s will never be reclaimed.  But again, in practice this is hardly an issue any more for the same reason that the "Rule of 3" isn't really much of a problem anymore.  It's very rare (and usually unnecessary) to actually manage your own memory with raw pointers.  To avoid the above problem, all you'd need to do is use an std::string or std::vector, and the destructor would automatically get invoked during stack unwinding after the exception was thrown.

So, a general theme here is that many C++ features which were not inherited from C, such as automatic initialization/destruction, copy constructors, and exceptions, force a programmer to be extra careful when doing manual memory management in C++.  But again, this is only a problem if you intend to do manual memory management in the first place, which is hardly ever necessary anymore when you have standard containers and smart pointers.

So, in my opinion, while C++ gives you a lot of extra rope, it's hardly ever necessary to use it to hang yourself, and the pitfalls which Joel was talking about are trivially easy to avoid in modern C++.

Body:
In my opinion, the dangers of C++ are somewhat exaggerated.

The essential danger is this: While C# lets you perform "unsafe" pointer operations using the unsafe keyword, C++ (being mostly a superset of C) will let you use pointers whenever you feel like it.  Besides the usual dangers inherent with using pointers (which are the same with C), like memory-leaks, buffer overflows, dangling pointers, etc., C++ introduces new ways for you to seriously screw things up.

This "extra rope", so to speak, which Joel Spolsky was talking about, basically comes down to one thing: writing classes which internally manage their own memory, also known as the "Rule of 3" (which can now be called the Rule of 4 or Rule of 5 in C++11).  This means, if you ever want to write a class that manages its own memory allocations internally, you have to know what you're doing or else your program will likely crash.  You have to carefully create a constructor, copy constructor, destructor, and assignment operator, which is surprisingly easy to get wrong, often resulting in bizarre crashes at runtime.

HOWEVER, in actual every-day C++ programming, it's very rare indeed to write a class that manages its own memory, so it's misleading to say that C++ programmers always need to be "careful" to avoid these pitfalls.  Usually, you'll just be doing something more like:

class Foo
{
    public:

    Foo(const std::string& s)
        : m_first_name(s)
    { }

    private:

    std::string m_first_name;
};

This class looks pretty close to what you'd do in Java or C# - it requires no explicit memory management (because the library class std::string takes care of all that automatically), and no "Rule of 3" stuff is required at all since the default copy constructor and assignment operator is fine.

It's only when you try to do something like:

class Foo
{
    public:

    Foo(const char* s)
    {
        std::size_t len = std::strlen(s);
        m_name = new char[len + 1];
        std::strcpy(m_name, s);
    }

    Foo(const Foo& f); // must implement proper copy constructor

    Foo& operator = (const Foo& f); // must implement proper assignment operator

    ~Foo(); // must free resource in destructor

    private:

    char* m_name;
};

In this case, it can be tricky for novices to get the assignment, destructor and copy constructor correct.  But for most cases, there's no reason to ever do this.  C++ makes it very easy to avoid manual memory management 99% of the time by using library classes like std::string and std::vector.

Another related issue is manually managing memory in a way that doesn't take into account the possibility of an exception being thrown.  Like:

char* s = new char[100];
some_function_which_may_throw();
/* ... */
delete[] s;

If some_function_which_may_throw() actually does throw an exception, you're left with a memory leak because the memory allocated for s will never be reclaimed.  But again, in practice this is hardly an issue any more for the same reason that the "Rule of 3" isn't really much of a problem anymore.  It's very rare (and usually unnecessary) to actually manage your own memory with raw pointers.  To avoid the above problem, all you'd need to do is use an std::string or std::vector, and the destructor would automatically get invoked during stack unwinding after the exception was thrown.

So, a general theme here is that many C++ features which were not inherited from C, such as automatic initialization/destruction, copy constructors, and exceptions, force a programmer to be extra careful when doing manual memory management in C++.  But again, this is only a problem if you intend to do manual memory management in the first place, which is hardly ever necessary anymore when you have standard containers and smart pointers.

So, in my opinion, while C++ gives you a lot of extra rope, it's hardly ever necessary to use it to hang yourself, and the pitfalls which Joel was talking about are trivially easy to avoid in modern C++.


问:
Is there an "ask for only what you need" interface principle?
I have grown into using a principle for designing and consuming interfaces that says basically, "ask for only what you need."

For instance, if I have a bunch of types that can be deleted, I'll make a Deletable interface:

```<code>interface Deletable {
   void delete();
}
</code>```

Then I can write a generic class:

```<code>class Deleter<T extends Deletable> {
   void delete(T t) {
      t.delete();
   }
}
</code>```

Elsewhere in code I will always ask for the smallest possible responsibility to fulfill the needs of the client code.  So if I only need to delete a File, I'll still ask for a Deletable, not a File.

Is this principle that is common knowledge and already has an accepted name?  Is it controversial?  Is it discussed in textbooks?

答: I do believe that this refers to what Robert Martin calls the Interface Segregation Principle. Interfaces are separated into small and concise ones so that the consumers (clients) will only have to know about the methods that are of interest to them. You can check out more on SOLID.</p>


答:
The fundamental difference between C++ and C# stems from undefined behavior.

It has nothing to do with doing manual memory management. In both cases, that is a solved problem.

C/C++:

In C++, when you make a mistake, the result is undefined.

Or, if you try to make certain kinds of assumptions about the system (e.g. signed integer overflow), chances are that your program will be undefined.

Maybe read this 3-part series on undefined behavior.

This is what makes C++ so fast -- the compiler doesn't have to worry about what happens when things go wrong, so it can avoid checking for correctness.

C#, Java, etc.

In C#, you're guaranteed that many mistakes will blow up in your face as exceptions, and you're guaranteed a lot more about the underlying system.

That is a fundamental barrier to making C# as fast as C++, but it's also a fundamental barrier to making C++ safe, and it makes C# easier to work with and debug.

Everything else is just gravy.

Title: Does C# give you "less rope to hang yourself" than C++?

Body:
Joel Spolsky characterized C++ as "enough rope to hang yourself".  Actually, he was summarizing "Effective C++" by Scott Meyers:

It's a book that basically says, C++ is enough rope to hang yourself, and then a couple of extra miles of rope, and then a couple of suicide pills that are disguised as M&Ms...

I don't have a copy of the book, but there are indications that much of the book relates to pitfalls of managing memory which seem like would be rendered moot in C# because the runtime manages those issues for you.

Here are my questions:

Does C# avoid pitfalls that are avoided in C++ only by careful programming?  If so, to what degree and how are they avoided?

Are there new, different pitfalls in C# that a new C# programmer should be aware of?  If so, why couldn't they be avoided by the design of C#?


答:
Does C# avoid pitfalls that are avoided in C++ only by careful programming? If so, to what degree and how are they avoided?

Most it does, some it doesn't. And of course, it makes some new ones.

Undefined behavior - The biggest pitfall with C++ is that there's a whole lot of the language that is undefined. The compiler can literally blow up the universe when you do these things, and it will be okay. Naturally, this is uncommon, but it is pretty common for your program to work fine on one machine and for really no good reason not work on another. Or worse, subtly act different. C# has a few cases of undefined behavior in its specification, but they're rare, and in areas of the language that are infrequently traveled. C++ has the possibility of running into undefined behavior every time you make a statement.

Memory Leaks - This is less of a concern for modern C++, but for beginners and during about half of its lifetime, C++ made it super easy to leak memory. Effective C++ came right around the evolution of practices to eliminate this concern. That said, C# can still leak memory. The most common case people run into is event capture. If you have an object, and put one of its methods as a handler to an event, the owner of that event needs to be GC'd for the object to die. Most beginners don't realize that event handler counts as a reference. There's also issues with not disposing disposable resources that can leak memory, but these are not nearly as common as pointers in pre-Effective C++.

Compilation - C++ has a retarded compilation model. This leads to a number of tricks to play nice with it, and keep compile times down.

Strings - Modern C++ makes this a little better, but char* is responsible for ~95% of all security breaches before the year 2000. For experienced programmers, they'll focus on std::string, but it's still something to avoid and a problem in older/worse libraries. And that's praying that you don't need unicode support.

And really, that's the tip of the iceberg. The main issue is that C++ is a very poor language for beginners. It is fairly inconsistent, and many of the old really, really bad pitfalls have been dealt with by changing the idioms. The problem is that beginners then need to learn the idioms from something like Effective C++. C# eliminates a lot of these problems altogether, and makes the rest less of a concern until you get further along the learning path.

Are there new, different pitfalls in C# that a new C# programmer should be aware of? If so, why couldn't theybe avoided by the design of C#?

I mentioned the event "memory leak" issue. This isn't a language problem so much as the programmer expecting something that the language can't do.

Another is that the finalizer for a C# object is not technically guaranteed to be run by the runtime. This doesn't usually matter, but it does cause some things to be designed differently than you might expect.

Another semi-pitfall I've seen programmers run into is the capture semantics of anonymous functions. When you capture a variable, you capture the variable. Example:

```<code>List<Action> actions = new List<Action>();
for(int x = 0; x < 10; ++x ){
    actions.Add(() => Console.WriteLine(x));
}

foreach(var action in actions){
    action();
}
</code>```

Doesn't do what naively is thought. This prints 10 10 times.

I'm sure there's a number of others I am forgetting, but the main issue is that they're less pervasive.

Body:
Does C# avoid pitfalls that are avoided in C++ only by careful programming? If so, to what degree and how are they avoided?

Most it does, some it doesn't. And of course, it makes some new ones.

Undefined behavior - The biggest pitfall with C++ is that there's a whole lot of the language that is undefined. The compiler can literally blow up the universe when you do these things, and it will be okay. Naturally, this is uncommon, but it is pretty common for your program to work fine on one machine and for really no good reason not work on another. Or worse, subtly act different. C# has a few cases of undefined behavior in its specification, but they're rare, and in areas of the language that are infrequently traveled. C++ has the possibility of running into undefined behavior every time you make a statement.

Memory Leaks - This is less of a concern for modern C++, but for beginners and during about half of its lifetime, C++ made it super easy to leak memory. Effective C++ came right around the evolution of practices to eliminate this concern. That said, C# can still leak memory. The most common case people run into is event capture. If you have an object, and put one of its methods as a handler to an event, the owner of that event needs to be GC'd for the object to die. Most beginners don't realize that event handler counts as a reference. There's also issues with not disposing disposable resources that can leak memory, but these are not nearly as common as pointers in pre-Effective C++.

Compilation - C++ has a retarded compilation model. This leads to a number of tricks to play nice with it, and keep compile times down.

Strings - Modern C++ makes this a little better, but char* is responsible for ~95% of all security breaches before the year 2000. For experienced programmers, they'll focus on std::string, but it's still something to avoid and a problem in older/worse libraries. And that's praying that you don't need unicode support.

And really, that's the tip of the iceberg. The main issue is that C++ is a very poor language for beginners. It is fairly inconsistent, and many of the old really, really bad pitfalls have been dealt with by changing the idioms. The problem is that beginners then need to learn the idioms from something like Effective C++. C# eliminates a lot of these problems altogether, and makes the rest less of a concern until you get further along the learning path.

Are there new, different pitfalls in C# that a new C# programmer should be aware of? If so, why couldn't theybe avoided by the design of C#?

I mentioned the event "memory leak" issue. This isn't a language problem so much as the programmer expecting something that the language can't do.

Another is that the finalizer for a C# object is not technically guaranteed to be run by the runtime. This doesn't usually matter, but it does cause some things to be designed differently than you might expect.

Another semi-pitfall I've seen programmers run into is the capture semantics of anonymous functions. When you capture a variable, you capture the variable. Example:

List<Action> actions = new List<Action>();
for(int x = 0; x < 10; ++x ){
    actions.Add(() => Console.WriteLine(x));
}

foreach(var action in actions){
    action();
}

Doesn't do what naively is thought. This prints 10 10 times.

I'm sure there's a number of others I am forgetting, but the main issue is that they're less pervasive.


问:
How important is it to learn makefiles?
I work in c++ mostly as a hobby (I'm still in school and therefor don't have a real job). The IDEs generate the makefile for me and so I'm wondering if it's worth learning how to make them myself. By "worth learning" I mean, should I drop everything and learn how to write them before continuing to learn c++? Is learning them going to be really necessary? If so, should I learn about them (general syntax and understanding how they work etc.) or really learn how to write them?</p>

答: If you're working with open source or Unix-like operating systems, yes. Take heart though, they're not that complicated. Learning make will save you a lot of time in the long run.

Title: How important is it to learn makefiles?


问:
Inventory management system design problem
What are the conventions for item batch identifiers in inventory management systems?

For example:

A retail supermarket can order 'Item X' from either 'Supplier A' or 'Supplier B'. When it completes an order for the item from either supplier, it needs to store the record of the receipt. Inventory quantity for the item is increased upon receipt of the order.

However it is also required to store some record of the supplier. Thus some sort of batch identifier is required. This batch identifier will uniquely identify the item received and the supplier from whom it is received. A new batch is created each time items are received in stock (for example, after an order).

Hence, for purposes of accounting / auditing, information available to identify an item after it was sold comprises of ITEM_CODE, ITEM_NAME, BATCH_CODE. The BATCH_CODE is unique and is associated with DATE_RECEIVED, SUPPLIER_CODE, QTY_RECEIVED.

Is this a complete system specification for the above scenario or has anything significant been left out?

答:
There are a number of potential gaps in this analysis that may or may not pose a problem in a particular implementation.  I would argue that some of them lie way outside of the topic of the site (accounting and supply chain management).

However, there is one gap that you will definitely need to close based on the facts mentioned in the question.

You will need to split the term "Item X" into at least two concepts already at the configuration side; inventory item from your site's perspective, and a supplier's item.  For example, stock levels or the link to a corresponding retail item are attributes of the former.  Order code is an attribute of the latter.  The mapping between these two concepts will likely evolve as suppliers pop into and out of business relations with you.


答:
I wouldn't really agree. Maybe less pitfalls than C++ as it existed in 1985.

Does C# avoid pitfalls that are avoided in C++ only by careful
  programming? If so, to what degree and how are they avoided?

Not really. Rules like the Rule of Three have lost massive significance in C++11 thanks to unique_ptr and shared_ptr being Standardised. Using the Standard classes in a vaguely sensible fashion isn't "careful coding", it's "basic coding". Plus, the proportion of the C++ population who are still sufficiently stupid, uninformed, or both to do things like manual memory management is a lot lower than before. The reality is that lecturers who wish to demonstrate rules like that have to spend weeks trying to find examples where they still apply, because the Standard classes cover virtually every use case imaginable. Many Effective C++ techniques have gone the same way- the way of the dodo. Lots of the others aren't really that C++ specific. Let me see. Skipping the first item, the next ten are:

Don't code C++ like it's C. This is really just common sense.

Restrict your interfaces and use encapsulation. OOP.

Two-phase initialization code writers should be burned at the stake. OOP.

Know what value semantics are. Is this really C++ specific?

Restrict your interfaces again, this time in a slightly different way. OOP.

Virtual destructors. Yeah. This one is probably still valid- somewhat. final and override have helped change this particular game for the better. Make your destructor override and you guarantee a nice compiler error if you inherit from someone who didn't make their destructor virtual. Make your class final and no poor scrub can come along and inherit from it accidentally without a virtual destructor.

Bad things happen if cleanup functions fail. This isn't really specific to C++- you can see the same advice for both Java and C#- and, well, pretty much every language. Having cleanup functions that can fail is just plain bad and there's nothing C++ or even OOP about this item.

Be aware of how constructor order influences virtual functions. Hilariously, in Java (either current or past) it would simply incorrectly call the Derived class's function, which is even worse than C++'s behaviour. Regardless, this issue is not specific to C++.

Operator overloads should behave as people expect. Not really specific. Hell, it's hardly even operator overloading specific, the same could be applied to any function- don't give it one name and then make it do something completely unintuitive.

This is actually now considered bad practice. All strongly-exception-safe assignment operators deal with self-assignment just fine, and self-assignment is effectively a logical program error, and checking for self-assignment just isn't worth the performance cost.

Obviously I'm not going to go through every single Effective C++ item, but most of them are simply applying basic concepts to C++. You would find the same advice in any value-typed object-orientated overloadable-operator language. Virtual destructors is about the only one that's a C++ pitfall and is still valid- although, arguably, with the final class of C++11, it's not as valid as it was. Remember that Effective C++ was written when the idea of applying OOP, and C++'s specific features, was still very new. These items are hardly about C++'s pitfalls and more about how to cope with the change from C and how to use OOP correctly.

Edit: The pitfalls of C++ do not include things like the pitfalls of malloc. I mean, for one, every single pitfall you can find in C code you can equally find in unsafe C# code, so that's not particularly relevant, and secondly, just because the Standard defines it for interoperation does not mean that using it is considered C++ code. The Standard defines goto as well, but if you were to write a giant pile of spaghetti mess using it, I'd consider that your problem, not the language's. There's a big difference between "careful coding" and "Following basic idioms of the language".

Are there new, different pitfalls in C# that a new C# programmer
  should be aware of? If so, why couldn't theybe avoided by the design
  of C#?

using sucks. It really does. And I have no idea why something better wasn't done. Also, Base[] = Derived[] and pretty much every use of Object, which exists because the original designers failed to notice the massive success that templates were in C++, and decided that "Let's just have everything inherit from everything and lose all our type safety" was the smarter choice. I also believe that you can find some nasty surprises in things like race conditions with delegates, and other such fun. Then there's other general stuff, like how generics suck horrifically in comparison to templates, the really really unnecessary enforced placing of everything in a class, and such things.


答:
Keep in mind that I don't have time to read several 1000-page tomes
  about abstract programming.

So are you asking for someone to give you a five step check list that will make you a skilled programmer? That's not going to happen!

As with any other discipline, if you want to get good at programming you have to spend time and effort practicing and studying. You learn to write clear, elegant code by writing a lot of code and carefully reading other people's code. Some of those 1000 page tomes will actually save you time by summarizing the hard lessons other folks have learned. It's delusional to think that you can become a skilled programmer as a painless side effect of getting a physics Ph.D.. It's not that you can't come out of a physics Ph.D. with mad programming skills, it's just that it will cost you time and trouble.

Code Complete is a good introduction to the mechanics of software development, including advice on how to write and structure clear, maintainable code. Yes, it is a huge tome, but it certainly not as dense as say, Dirac's "Principles of Quantum Mechanics" or MTW's "Gravitation". Code Complete is as close as you are going to get to a five step checklist to writing better software.

Matlab, VIM, C, MPI, and Valgrind are excellent tools to know. You don't mention using a version control system. If by some fluke you are not already using a version control system you must start using one immediately. Version control is also a god-send for writing your thesis. Other basic tools you should know are a debugger, an execution profiler, a logging framework, and a  unit testing framework. You don't have to read a 1000 page book for each of these. Work through the online tutorials to get the basics and then start working with them. Delve more deeply into the documentation as your needs become more sophisticated.

Advising you about learning computer science fundamentals (as opposed to software construction fundamentals) is more difficult. You don't specify what problem you are working on, whether you are developing new algorithms or applying existing algorithms. Depending on your research problem a survey of the basic data structures and standard algorithms might be helpful. Other problems would benefit more from a solid background in numerical analysis. If you do want to learn the basics of algorithm analysis there several good texts. The Algorithm Design Manual and Introduction to Algorithms spring to mind. There are also a couple of good introductory courses available online now: Design and Analysis of Algorithms, and Algorithms.


答:
What you are stating is completely false. POS systems scans the UPCs only, that is the only level of detail kept for sales.

Receiving of the same item by different suppliers go into the same inventory pool, costing is done by LIFO or FIFO or cost averaging specifically because they don't track sales back to specific receiving.

Serial number ranges may be kept at the time of receiving for use in the case you need to track a specific item back to a supplier,but again it is not recorded at the time of sale.

Note: Everything above is for cheap supermarket type items. For larger more expensive item Serial numbers are recorded at the time of sale to prevent return fraud, or for legal reasons.

Title: Inventory management system design problem

Body:
What are the conventions for item batch identifiers in inventory management systems?

For example:

A retail supermarket can order 'Item X' from either 'Supplier A' or 'Supplier B'. When it completes an order for the item from either supplier, it needs to store the record of the receipt. Inventory quantity for the item is increased upon receipt of the order.

However it is also required to store some record of the supplier. Thus some sort of batch identifier is required. This batch identifier will uniquely identify the item received and the supplier from whom it is received. A new batch is created each time items are received in stock (for example, after an order).

Hence, for purposes of accounting / auditing, information available to identify an item after it was sold comprises of ITEM_CODE, ITEM_NAME, BATCH_CODE. The BATCH_CODE is unique and is associated with DATE_RECEIVED, SUPPLIER_CODE, QTY_RECEIVED.

Is this a complete system specification for the above scenario or has anything significant been left out?


答:
I can tell you that the biggest gains I have made in terms of how I approach solving problems have all been achieved through learning functional languages and parsers. Both discoveries were made by  accident. So I'm telling you now if you are truly serious about becoming a better programmer then you need to learn about the various techniques involved in writing a compiler, e.g. parsers and parser generators, and you need to learn how to compose computations with higher order functions.

An excellent resource for the parser and compiler stuff is PL101: Create Your Own Programming Language. I still haven't found a good intro to functional programming but I hear really good things about SICP.


答:
Yes, it is definitely worth understanding how Makefiles work.  It might not be relevant to you right now (because you are using an IDE that generates them), but the chances are that the knowledge will be useful in the future.

By "worth learning" I mean, should I drop everything and learn how to write them before continuing to learn c++?

Frankly, that is a bizarre notion of "worth learning" ...

But no I don't think you need to do that.

Is learning them going to be really necessary?

We cannot predict whether you are really going to need this knowledge in the future.  It depends on whether you continue with C++ programming and what context you do it in.

If so, should I learn about them (general syntax and understanding how they work etc.) or really learn how to write them?

I'd recommend both.  If you can't write a Makefile, it is debatable that you know what is going on.

There is the other viewpoint which says that too much knowledge is not helpful.

If you get deeply into this you will learn that there are many different versions of Make, and that writing a complicated Makefile that works with multiple versions of Make on multiple platforms is ... hard.  However, in the open source world, it is "best practice" to use tools such as automake, autoconf and so on to generate the makefiles, etc.  If you do that, a lot of the version / platform related complexity is dealt with behind the scenes.

Finally, you tagged the question with "java".  My take is that you shouldn't use make to build Java applications (unless you are building native code libraries as well).  There are Java specific build tools that are much easier to use ... and do a better job than make.  (Ant, Maven, and Gradle are obvious candidates.)

Title: How important is it to learn makefiles?

Body: I work in c++ mostly as a hobby (I'm still in school and therefor don't have a real job). The IDEs generate the makefile for me and so I'm wondering if it's worth learning how to make them myself. By "worth learning" I mean, should I drop everything and learn how to write them before continuing to learn c++? Is learning them going to be really necessary? If so, should I learn about them (general syntax and understanding how they work etc.) or really learn how to write them?</p>


答: I'm bias as i think makefiles are a terrible system. You should learn general syntax so you can modifying an existing makefile. But i don't think learning everything about it nor making one from scratch is useful.</p>

Title: How important is it to learn makefiles?


问:
What are use cases and advantages of pointers?
I often struggle to see the advantages of pointers (except for low level programming).

Why use of char* instead of a String or char[] or what advantages pointer arithmetic brings.

So what are the pros and use cases of pointers?

答:
char* is a crummy example of pointers. You are probably better off using std::string (or some better type that handles your unicode/ansi/multibyte specialness) than char*. For almost any other example of pointers (Employee*, PurchaseOrder*, ...), however, there are many advantages:

scope larger than a single function - allocate the object on the heap and pass the pointer around for a long time

quicker function calls for large objects since you don't have the copy cost of pass-by-value

one way to enable a function to change the parameters passed to it

save space and time in collections copying only an address instead of an entire object

In fact, pointers are so important that most languages that appear not to have them actually have only them. Reference types in C# and Java are essentially pointers disguised as solid objects.

Now, pointer manipulation (p++ on a pointer, or p += delta) is a whole 'nother story. Some people think it's dangerous, some people think it's great. But that's even further from your question.

ContentLicense: CC BY-SA 2.5


答:
Yes 100% yes as i think its impossible to free memory and use it in C# (assuming its managed and you don't go into unsafe mode).

But if you know how to program in C++ which an unbelievable number of people don't. You're pretty much fine. Like Charles Salvia classes don't really manage their memories as it all is handled in preexisting STL classes. I rarely use pointers. In fact i went projects without using a single pointer. (C++11 makes this easier).

As for making typos, silly mistakes and etc (ex: if (i=0) bc the key got stuck when you hit == really quickly) the compiler complains which is nice as it improves quality of code. Other example are forgetting break in switch statements and not allowing you to declare static variables in a function (which i dislike sometimes but is a good idea imo).


问:
What is the right way to version control a password protected archive?
I'm working with a local file which I always extract from a password protected archive (RAR), do some modifications/additions to it and overwrite the old file inside the archive with the new file (I don't overwrite the archive. I overwrite the file inside it). The RAR is password protected for certain confidentiality reasons, and I need it to be that way.

I considered using Git for version control, but from my first use of Git, it appears to be meant for files that are not archived. I wanted to version control my RAR file. But what if I decide to add more files to the RAR and then commit the RAR? Doesn't that ruin the point of having version control where you can also do a diff to compare versions etc.? Does it make sense to use a version control when I'm extracting files from the RAR to do modifications and then putting them back in the RAR and committing the RAR?

Is version control the right way to do this or is there something better?

答:
If all you're doing is overwriting files, it's not really version control. You use Version Control for different versions, releases, builds, etc. of a project.

I think you're looking at this the wrong way. Is there any reason why the rar file can't be unpacked and the files uploaded into a password protected project at any number of git/subversion hosts that offer a free project?

EDIT: Based on your reply, you want it local.

I'm not sure what OS you're using, but here's VisualSVN

This should allow you to setup a local Subversion repo on Windows. Any Subversion IDE integration should work. I know ANKSVN for VS does. You can control access and require login to access it. This will allow an actual version control for you, but still enable to you keep everything local and be secure.

Edit #2: Merely overwriting files isn't a best practice. You have nothing to fall back on should you destroy functionality while trying to improve it.


答:
Considering your mention of lack of time to study theory.

If you've looked back at your old code after a few months and wondered "what kind of an idiot wrote that code", you're making progress.

How did you progress? By seeing better code written by others. A person never knows the value of 'elegance' or 'good' code unless they see it adding value to their work. Rather than read theory, I would encourage you to keep your eyes open to code written by others in your field of work. Keep your eyes open to concepts being discussed on stackoverflow (C++ tag).  Spending just fifteen minutes a day of such searching can randomly expose you to concepts which can help you. It can show you code that is better written than your code. That's when you follow up on Wikipedia and find out more about it. Such learning that comes out of curiosity, will be much longer lasting and useful to you than theory which you will forget when you wake up the next day.

Also consider trying out languages like MATLAB or Python.


答:
No, C# (and Java) are less safe than C++

C++ is locally verifiable.  I can inspect a single class in C++ and determine that the class does not leak memory or other resources, assuming that all the referenced classes are correct.  In Java or C#, it is necessary to check every referenced class to determine if it requires finalization of some sort.

C++:

```<code>{
   some_resource r(...);  // resource initialized
   ...
}  // resource destructor called, no leaks here
</code>```

C#:

```<code>{
   SomeResource r = new SomeResource(...); // resource initialized
   ...
} // did I need to finalize that?  May I should have used 'using'
  // (or in Java, a grotesque try/finally construct)?  No way to tell
  // without checking the documentation for SomeResource
</code>```

C++:

```<code>{
    auto_ptr<SomeInterface> i = SomeFactory.create(...);
    i->f(...);
} // automatic finalization and memory release.  A new implementation of
  // SomeInterface can allocate and free resources with no impact
  // on existing code
</code>```

C#:

```<code>{
   SomeInterface i = SomeFactory.create(...);
   i.f(...);
   ...
} // Sure hope someone didn't create an implementation of SomeInterface
  // that requires finalization.  In C# and Java it is necessary to decide whether
  // any implementation could require finalization when the interface is defined.
  // If the initial decision is 'no finalization', then no future implementation
  // can acquire any resource without creating potential leaks in existing code.
</code>```

Body:
No, C# (and Java) are less safe than C++

C++ is locally verifiable.  I can inspect a single class in C++ and determine that the class does not leak memory or other resources, assuming that all the referenced classes are correct.  In Java or C#, it is necessary to check every referenced class to determine if it requires finalization of some sort.

C++:

{
   some_resource r(...);  // resource initialized
   ...
}  // resource destructor called, no leaks here

C#:

{
   SomeResource r = new SomeResource(...); // resource initialized
   ...
} // did I need to finalize that?  May I should have used 'using'
  // (or in Java, a grotesque try/finally construct)?  No way to tell
  // without checking the documentation for SomeResource

C++:

{
    auto_ptr<SomeInterface> i = SomeFactory.create(...);
    i->f(...);
} // automatic finalization and memory release.  A new implementation of
  // SomeInterface can allocate and free resources with no impact
  // on existing code

C#:

{
   SomeInterface i = SomeFactory.create(...);
   i.f(...);
   ...
} // Sure hope someone didn't create an implementation of SomeInterface
  // that requires finalization.  In C# and Java it is necessary to decide whether
  // any implementation could require finalization when the interface is defined.
  // If the initial decision is 'no finalization', then no future implementation
  // can acquire any resource without creating potential leaks in existing code.


答:
I would consider not to put the RAR file into version control. If you want to have diff/compare capabilities, it is much better put your (text?) files into version control. If you need that RAR file, create a a script to build the RAR file from scratch in a reproducible manner. Put that script also into version control. </p>

<p>Concerning confidentiality: I would use a crypted file system, for example something like True Crypt, for your local files (your clear-text working copy and also the git repository). </p>

Title: What is the right way to version control a password protected archive?

Body:
I'm working with a local file which I always extract from a password protected archive (RAR), do some modifications/additions to it and overwrite the old file inside the archive with the new file (I don't overwrite the archive. I overwrite the file inside it). The RAR is password protected for certain confidentiality reasons, and I need it to be that way.

I considered using Git for version control, but from my first use of Git, it appears to be meant for files that are not archived. I wanted to version control my RAR file. But what if I decide to add more files to the RAR and then commit the RAR? Doesn't that ruin the point of having version control where you can also do a diff to compare versions etc.? Does it make sense to use a version control when I'm extracting files from the RAR to do modifications and then putting them back in the RAR and committing the RAR?

Is version control the right way to do this or is there something better?

Body:
I would consider not to put the RAR file into version control. If you want to have diff/compare capabilities, it is much better put your (text?) files into version control. If you need that RAR file, create a a script to build the RAR file from scratch in a reproducible manner. Put that script also into version control.

Concerning confidentiality: I would use a crypted file system, for example something like True Crypt, for your local files (your clear-text working copy and also the git repository).


答:
If all you have in your repo is a rar-ed file, you lose pretty much all the benefits of a sophisticated version control system, such as branching / merging, diffs, efficient differential storage, etc. If you want to keep going down that road, then you don't really need a version control system - a directory of RAR files will do exactly the same for you (minus the IDE integration, but you can easily script your way out of that one).

If you do want to leverage the benefits of source control, here's what you can do:

Set up a dedicated machine to work on, with full-disk crypto. The machine can be a VM if you don't have a spare one lying around, as long as everything is encrypted. Make sure nobody has access to that machine except yourself. Pick strong passwords.

On that machine, set up a git repo and your development environment.

Lock down network access: your development machine should have a very restrictive set of firewall rules (and a good firewall). Most importantly, lock down all incoming traffic except what you absolutely need: there is no reason to allow incoming HTTP traffic, for example. If it's a VM running on your local workstation, you don't need any network access at all, except for downloading software updates.

Copy the RAR file to the development machine, unpack it, and put the unpacked files in your git repo.

Whenever you need to ship a RAR, export the git repo's HEAD version and RAR it up with a suitable password, then copy it off the development machine.

This method actually has a few advantages over your current approach: the unpacked files are never written to disk unencrypted (because the entire development machine's disk is encrypted), and since the development machine serves only this one purpose, you can apply far more restrictive security measures - for example, you don't need to run a web browser (you can do that on your 'regular' machine), you don't need to read any e-mails, you don't need things like flash, Java, etc. And if at some point you stop working on that project, you can just wipe the crypto key, and everything you ever knew about the project will be gone. Also, the encryption provided by TrueCrypt and similar full-disk crypto solutions is far better than anything RAR has to offer.

Either way, you need to decide on a threat model to defend against, and see which strategy works best.


问:
What is the purpose of returning $this in PHP
```<code>function select($select = '*')
    {
        if( is_string($select) ) {
            $select = explode(',', $select) ;
        }

        foreach($select as $s) {
            $s = trim($s) ;

            if($s != '') {
                $this->aSelect[] = $s ;
            }
        }

        return $this ;
    }
</code>```

In PHP, what is meant by return $this.

答:
By returning $this you it makes it easier for the programmer to chain commands. Consider a car object. You could say $car->start()->forward()->left()->forward() on line if you return $this in each function.

There is actually a question about this in stack overflow which could help clarify what method chaining is: https://stackoverflow.com/questions/3724112/php-method-chaining


答:
There are many scenarios in which one might want to return $this from a function, but the most popular one is 'method chaining'.

For example, in an SQL abstraction layer, you may have an object that represents a query, and then call a series of methods on it to extend it. Consider the following code:

```<code>$query = $database->select();
$query->from('users');
$query->whereEquals('username', $username);
$query->orderBy('username');
$query->limit(1);
$user = $query->executeSingleRow();
</code>```

If each of $query's methods returns the modified query object, we can instead write this as:

```<code>$user = $database
            ->select()
            ->from('users')
            ->whereEquals('username', $username)
            ->orderBy('username')
            ->limit(1)
            ->executeSingleRow();
</code>```

The second version is closer to how you'd write an actual SQL query, and it works without introducing the exta $query variable.

Title: What is the purpose of returning $this in PHP

Body:
```<code>function select($select = '*')
    {
        if( is_string($select) ) {
            $select = explode(',', $select) ;
        }

        foreach($select as $s) {
            $s = trim($s) ;

            if($s != '') {
                $this->aSelect[] = $s ;
            }
        }

        return $this ;
    }
</code>```

In PHP, what is meant by return $this.

Body:
There are many scenarios in which one might want to return $this from a function, but the most popular one is 'method chaining'.

For example, in an SQL abstraction layer, you may have an object that represents a query, and then call a series of methods on it to extend it. Consider the following code:

$query = $database->select();
$query->from('users');
$query->whereEquals('username', $username);
$query->orderBy('username');
$query->limit(1);
$user = $query->executeSingleRow();

If each of $query's methods returns the modified query object, we can instead write this as:

$user = $database
            ->select()
            ->from('users')
            ->whereEquals('username', $username)
            ->orderBy('username')
            ->limit(1)
            ->executeSingleRow();

The second version is closer to how you'd write an actual SQL query, and it works without introducing the exta $query variable.


答: The best answer is actually included in the question: pointers are for low-level programming. Granted, if you're using C, not using pointers is like programming with one hand tied behind your back, but the answer to that is to use a higher-level language instead.</p>

Title: What are use cases and advantages of pointers?

Body:
I often struggle to see the advantages of pointers (except for low level programming).

Why use of char* instead of a String or char[] or what advantages pointer arithmetic brings.

So what are the pros and use cases of pointers?


问:
When should I use StringBuilder or StringBuffer?
In a production web application, my fellow programmers used StringBuffer everywhere. Now I am taking care of application development and corrections. After reading StringBuilder and StringBuffer I have decided to replace all the StringBuffer code with StringBuilder because we don't need thread safety in our data beans.

For example: (In each data bean I can see the use of StringBuffer)

```<code>@Override
public String toString() {
    StringBuffer sb = new StringBuffer();// replace it from StringBuilder
    sb.append(" ABCD : ").append(abcd);
    sb.append(", EFGH : ").append(efgh);
    sb.append(", IJKL : ").append(ijkl);
}
</code>```

We create a separate data beans for each session/request. A session is used by a single user no other user can access it.

Should I consider other points before migrating?

If there is a single thread (no waiting threads/no new thread will be looking for object lock), it performs equally with either StringBuffer or StringBuilder. I know in the case of StringBuffer, it takes time to take the object lock but I want to know if there is any performance difference between them except the hold/release of the object lock.

答:
The only difference between the two is the synchronization used in StringBuffer.  The overhead of synchronization is not huge in the grand scheme of things, but it is significant relative to the StringBuilder methods that don't have them.  The JVM is doing work that it wouldn't otherwise have to do--especially with only one thread, etc.

If your code works and people aren't complaining about performance, I wouldn't worry about it.  You aren't going to get a lot of bang for your buck.  However, if you are writing new code, or are updating code that uses StringBuffer, I'd suggest converting them StringBuilder at the same time.


问:
What is the name of the method to find index from array, in Objective-c?
I have a following method to find index of a book object which have a book name:

```<code>+(NSInteger)indexXXX:(NSString *)bookName XXX:(NSArray *)books
{
  for (NSInteger i = 0; i < books.count; i++) {
    NSDictionary *book = [books objectAtIndex:i];
    if ([[book objectForKey:@"bookName"] isEqualToString:bookName]) {
      return i;
    }
  }
  return -1;
}
</code>```

But I don't know what name should I use for this method.

Could you tell me some method names commonly used for this kind of method.

答:
Usually we just name methods after what they do, so something like indexOfObjectWithName: inArray: would work.

To carry on past answering this question, the method can be made much simpler:

```<code>{
    NSArray *names = [books valueForKey: @"bookName"];
    return [names indexOfObject: bookName];
}
</code>```

Body:
Usually we just name methods after what they do, so something like indexOfObjectWithName: inArray: would work.

To carry on past answering this question, the method can be made much simpler:

{
    NSArray *names = [books valueForKey: @"bookName"];
    return [names indexOfObject: bookName];
}


答:
StringBuilder was added at a point (Java 1.5) to be a better and faster StringBuffer and the compiler uses it under the hood to implement the + operator on Strings.

This means that by using StringBuilder you cannot make your code run on JVM's older than when the class was introduced.  This would be a problem to us, for a while yet. If you always run the latest, you don't need to care.

I would not go through the optimization process you go through, though for the following reasons.

Outside tight loops the advantage is negligible.  Unless it explicitly shows up as a hotspot in a profiler, I wouldn't bother.

Changing code may introduce errors, and you must retest your application thoroughly.  That may be a lot more expensive than living with a synchronized class in a non-synchronized setting.

Title: When should I use StringBuilder or StringBuffer?

Body:
In a production web application, my fellow programmers used StringBuffer everywhere. Now I am taking care of application development and corrections. After reading StringBuilder and StringBuffer I have decided to replace all the StringBuffer code with StringBuilder because we don't need thread safety in our data beans.

For example: (In each data bean I can see the use of StringBuffer)

```<code>@Override
public String toString() {
    StringBuffer sb = new StringBuffer();// replace it from StringBuilder
    sb.append(" ABCD : ").append(abcd);
    sb.append(", EFGH : ").append(efgh);
    sb.append(", IJKL : ").append(ijkl);
}
</code>```

We create a separate data beans for each session/request. A session is used by a single user no other user can access it.

Should I consider other points before migrating?

If there is a single thread (no waiting threads/no new thread will be looking for object lock), it performs equally with either StringBuffer or StringBuilder. I know in the case of StringBuffer, it takes time to take the object lock but I want to know if there is any performance difference between them except the hold/release of the object lock.


答: You could also put your files under version control, and then rar all the files together with the .git directory. Then you get all the benefits of git and you have all the content secured.</p>


问:
How to manage a developer who has poor communication skills
I manage a small team of developers on an application which is in the mid-point of its lifecycle, within a big firm. This unfortunately means there is commonly a 30/70 split of Programming tasks to "other technical work". This work includes:

Working with DBA / Unix / Network / Loadbalancer teams on various tasks

Placing and managing orders for hardware or infrastructure in different regions

Running tests that have not yet been migrated to CI

Analysis

Support / Investigation

Its fair to say that the Developers would all prefer to be coding, rather than doing these more mundane tasks, so I try to hand out the fun programming jobs evenly amongst the team.

Most of the team was hired because, though they may not have the elite programming skills to write their own compiler / game engine / high-frequency trading system etc., they are good communicators who "can get stuff done", work with other teams, and somewhat navigate the complex bureaucracy here. They are good developers, but they are also good all-round technical staff.

However, one member of the team probably has above-average coding skills, but below-average communication skills. Traditionally, the previous Development Manager tended to give him the Programming tasks and not the more mundane tasks listed above. However, I don't feel that this is fair to the rest of the team, who have shown an aptitude for developing a well-rounded skillset that is commonly required in a big-business IT department.

What should I do in this situation? If I continue to give him more programming work, I know that it will be done faster (and conversely, I would expect him to complete the other work slower). But it goes against my principles, and promotes the idea that you can carve out a "comfortable niche" for yourself simply by being bad at the tasks you don't like.

I want to clarify that I'm not trying to address this issue due to a grudge, or that I have a "chip on my shoulder" as was mentioned. I'm looking for advice on how to keep a well-rounded team, which is happy and motivated. By observing the variety of answers to this question, it seems like there are a lot of different opinions on how to achieve this.

答:
You should hire a junior to do all the grunt work, and let everyone know that they need to help him with anything he/she asks for help with. </p>

<p>They will be more inclined to bother the “above-average” coder because of their abilities and the rest of the team gets a new lackey. The junior gets to learn from the ground up and the company ends up with a well rounded employee in the end. </p>

Body:
You should hire a junior to do all the grunt work, and let everyone know that they need to help him with anything he/she asks for help with.

They will be more inclined to bother the “above-average” coder because of their abilities and the rest of the team gets a new lackey. The junior gets to learn from the ground up and the company ends up with a well rounded employee in the end.


问:
What are you thoughts on GWT?
Since I'm learning Java in this period and I just finished with the tutorials I think I'm ready to start contributing to a project (since I know from experience this is the best way to really learn).

I've seen GWT, looks interesting so I thought I should give it a try. I'm thinking however, since GWT deploys Java applications in JavaScript why should I learn GWT when I could learn the actual thing instead (this being JavaScript).
My question: is it worth it? Wouldn't someone be better of learning JavaScript if they want to build JS applications, instead of using Java and GWT? I realize that it might be easier to build certain things with GWT but in the end is it worth it?

Thanks.

答:
A few reasons that is good to catch up with GWT:

Every technology has a life cycle. GWT is at its up swing. Learning GWT will give you the technology advantage over a longer period of future time.

GWT using java, brings structure to web application. JavaScript is more suited for scripting. Backed by java, GWT is more suitable for large applications. If you have noticed the frameworks/toolkits on top of JavaScript, you may conclude like I do that JavaScript by itself is not enough for serious projects. All those frameworks bring structures to the application development. GWT is one of those frameworks, and is the one that will prevail.

Mobile application is a revolution in the software world. The revolution is at its early stage right now. More and more software will move to mobile platforms. GWT is now the most comprehensive cross-platform application development tool you can find.

Given that said, GWT is actually not tightly related to the web service frameworks from google or from sun (servlet). The integrated tools focus more on integration with their servers, due to google's or sun's business nature. To leverage the technology power of GWT, one should more or less ignore some of the server integration hyper. Just use GWT as an client application tool, it should be more beneficial to your future career.

OwnerDisplayName: Anonymous Coward

Title: What are you thoughts on GWT?


答:
As with many aspects of IDE output, a typical auto-generated makefile is often inefficiently structured.

With an appropriate level of understanding, it is often possible to significantly improve the performance (faster builds etc).  However, unless you really know what's going on, you are more likely to FUBAR, when fiddling with an autogen-ed file.

I highly recommend being able to understand what is going on... whether you subsequently choose to start editing an existing one, or creating your own, is a separate issue.

Title: How important is it to learn makefiles?


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
The position of curly braces should be

meta data

configurable in the IDE by the programmer. That way, those pesky braces in all code, regardless of author, look the same.


答:
It depends on what you want to do (as for most tools anyway).

If you want to go into the details of web development, use many (sometimes different) tricks of the browser environment, and the newest features of them, have the guts to fight with small tricks that makes your web app 'look cool', GWT will always be in your way: if you have the time and experience, you can do all and more with your hands. And yes, there are many other toolkits that will help you along the way programming in JavaScript.

However, if you want to make a "not-so-fancy", but stable GUI for your application that "should", and in most cases really do the same, and look the same in various browsers without tricks, GWT is a good choice, the best I know about. Explanation: Google is definitely motivated to keep it in sync with the most browsers and the newest technologies, and definitely has enough resources to do it. Yes, you adhere to another giant instead of doing your own stuff. Question: what is your job? To provide the same service to the widest rage of users through a web interface with the smallest effort - or make a shiny, exceptional web portal which has the coolest features on the newest platforms.

+1 reason: I think it is beneficial to keep your application in one codebase, and one language. You could do neat trick in database scripts - but you lock yourself to that db server. You can do external stuff with shell scripts or batch files - but you lock yourself to the operating system. You can implement some of the controller logic in JavaScript to provide a rich client interface in a browser - but you may lock yourself in one browser. For all cases, it is not easy to keep them in sync with the core application data structure and requirements (and perhaps the hardest one is the constantly changing browser+JS tools environment). I am convinced that if the core application is in Java, all stuff should be in Java - with a very small fraction of cases when you really have to put a part of the logic into another environment.

I picked GWT because of my answers to the above questions - and it does what I wanted it to do: in about 2 weeks after installation I had an acceptable web interface for an internal server monitoring system - although I had experience with Swing. (No, I have not used the default look and feel and yes, I used CSS and classes for presenting logical information :-) )

Check your current and planned tasks - and choose the right tool for them.

Title: What are you thoughts on GWT?

Body:
Since I'm learning Java in this period and I just finished with the tutorials I think I'm ready to start contributing to a project (since I know from experience this is the best way to really learn).

I've seen GWT, looks interesting so I thought I should give it a try. I'm thinking however, since GWT deploys Java applications in JavaScript why should I learn GWT when I could learn the actual thing instead (this being JavaScript).
My question: is it worth it? Wouldn't someone be better of learning JavaScript if they want to build JS applications, instead of using Java and GWT? I realize that it might be easier to build certain things with GWT but in the end is it worth it?

Thanks.


问:
Understanding the Macro Aspects of Data Structures
I am studying data structures right now, but I still need to find a teacher/site/book with a clear explanation of the macro aspects of this topic.

What I mean is: most lessons/text books mix everything together, with no logical structure. They start with linked lists, then talk about stacks, queues, heap priorities and so on. But as far as I can tell, a linked list and a stack are not really in the same category. After all you can use the linked list to implement different types of data strcutures (e.g., a stack, a queue, etc).

So would it be right to say that the types of data structures are: the stack, the queue, the hash-table, the heap, and the tree; while arrays (static) and linked lists (dynamic) are tools you are going to use to implement those data structures?

If the above statement is not completely correct, maybe a linked list is indeed a data structure in itself, and therefore we would be using one data structure (e.g., the linked list) to build other data structures on top of it (e.g., a stack)?

答:
I would say you always need to switch between macro (system level) and micro views (let's say function level) if you are to ever understand something out of programming the middle or big systems.

For switching between views, books like:

The Art of Computer Programming by Donald E. Knuth (algorithm to micro level)

Algorithms by Rober Sedgewick (versions in Java, C++, C) (both macro to algorithm and algorithm to micro level)

Algorith Design Manual by Steven Skienna (macro to algorithm level)

The Pragmatic Programmer by Dave Thomas, Andy Hunt

By far, the last part from Algorithms in Java 4th Edition by Robert Sedgewick is the one that will help change these micro and macro glasses often, but without loosing sight of the big prize.


答:
A graduate in Computer Science doesn't know how to code well when they graduate; they are not so much in demand when they leave University.  Only if they get the experience.

The answer to your question is you need to learn Design Patterns. I programmed in Java, .NET and now I work as a PHP, Javascript and MySQL programmer. .NET by the way has a very large level of abstraction, e.g. ASP.NET. It means you can skip the abstraction learning. Languages like Perl, PHP, etc. have a low level of abstraction.

Read Head First Design Patterns, it is a good book. It is quite a comprehensive book. That is all what you will need.


问:
Should I prefer instance methods over class methods in Ruby?
I'm working on a rails application, and I've been pulling functionality out of my rails code and into pure ruby classes in lib/. I've found myself often writing classes like this:

```<code> class MailchimpIntegration
  def subscribe_email(email, fname, lname)
    Gibbon.list_subscribe(:id => NEWSLETTER_LIST_ID, :email_address => email,
      :merge_vars => {'fname' => fname, 'lname' => lname },
      :email_type => "html",  :double_optin => false, :send_welcome => false)
  end

  def unsubscribe_email(email)
    Gibbon.list_unsubscribe(:id => NEWSLETTER_LIST_ID, :email_address => email)
  end

  def change_details(old_email, email, fname, lname)
    Gibbon.list_update_member(:id => NEWSLETTER_LIST_ID, :email_address => old_email,
      :merge_vars => {'email' => email, 'fname' => fname, 'lname' => lname })
  end

  def get_email_info(email)
    Gibbon.list_member_info(:id => NEWSLETTER_LIST_ID, :email_address => [email])["data"].first
  end
end
</code>```

My question is: Should I change these methods to be class methods?

It seems reasonable to do, as I'll probably end up calling these by just newing up a MailchimpIntegration class each time. However, I generally prefer to have instance methods as they can be more easily stubbed etc, although this seems to be less of an issue in ruby.

I have several classes like this in my system, so I'd be keen to see what people think about this.

答:
I'm putting this in as an answer, since I could be wrong, but I think I have a good reason for going with instance methods as opposed to class methods in this case.

The mailchimp class above is called from the User class when the user is saved, email edited, etc, realized that I need to make sure I don't call the mailchimp API in test, or all my tests will be super slow. (I stub out the mailchimp stuff in the tests dealing with that, but I don't for the other tests which just deal with user).

With class methods, this seems like it would be a pain since I can't easily stub out all the methods, but with MailchimpIntegration objects, I can just put:

```<code>  def mailchimp
    if Rails.env.production?
      MailchimpIntegration.new
    else
      NullObject.new
    end
  end
</code>```

In my user class, and stub that out to return my stub object with I'm testing the integration.

Body:
I'm putting this in as an answer, since I could be wrong, but I think I have a good reason for going with instance methods as opposed to class methods in this case.

The mailchimp class above is called from the User class when the user is saved, email edited, etc, realized that I need to make sure I don't call the mailchimp API in test, or all my tests will be super slow. (I stub out the mailchimp stuff in the tests dealing with that, but I don't for the other tests which just deal with user).

With class methods, this seems like it would be a pain since I can't easily stub out all the methods, but with MailchimpIntegration objects, I can just put:

  def mailchimp
    if Rails.env.production?
      MailchimpIntegration.new
    else
      NullObject.new
    end
  end

In my user class, and stub that out to return my stub object with I'm testing the integration.


问:
What are the advantages of programming to under an OS as opposed to bare metal executive?
Assume you are presented with an embedded system application to program, in C, on a multi-core environment (think a Cavium or Tilera) and need to choose between two environments:

Code the application under Linux in SMP mode or code the application under a thin bare metal executive (something like a very minimal RTOS), perhaps with a single core running UP Linux that can serve control tasks.

For the purpose of this question, assume that both environment provide the same level of performance guarantees in any measurable aspects of run time performance, including number of meaningful action per second, jitter, latency, real time considerations - the works. (and yes, I realize this is by far not a trivial assumption at all, bare with me).

How would you justify going with a Linux SMP based solution rather then a bare metal thin executive solution?

The question may seems silly. It certainly seems obvious to me - but I have to convince someone that does not think the same. Could you help make a list of arguments in favor of choosing a real SMP aware OS (Linux) vs. a bare metal executive assuming performance guarantees are NOT an issue?

Many thanks

答:
Some initial advantages include:

Code safety because the operating system can enforce memory protection and run some tasks in supervisor mode and others in user mode.  A few years ago when I had a class for a very popular RTOS I was shocked to see it used a flat, shared memory space.  Not sure if this is common, but it seems like a big jump backward.

Availability of wide ranging support for many peripherals through drivers.

If a device is not available, a driver can implement just the functionality needed to fit with a corresponding stack, rather than everything that goes with having the device.  Typically at least one similar device will have been written and can be used as an example.

There may be compiler or library level support for thread safe support for Linux.  If you have an executive, you may lack this and you may need to provide it yourself.  If the executive has an active user base, there may be a combination of libraries available for purchase or via open source, but the quality may depend on how wide and deep the support that community provides.  Pick your community with care.

If you start without all the baggage that comes with a real operating system, how long until you can't get along without those extra features?  Who writes, integrates, and maintains them?

Hope this helps.


问:
How can I ensure a portion of my project's code remains in all derivative works?
I had an idea for a website. After much coding and thinking out the idea, I've got it to a decent stage.

If I were someone else, potentially a more commercially-minded person, I might want to sell it, or slather it with ads. However, I've fallen somewhat in love with open-source, and I'd like to host the project on GitHub and give it a nice open-source license.

However, the project seems to be getting better all the time and, in fact, I think that it'll quickly grow to be fairly popular. So I want to put ads on it that benefit charity.

How can I ensure that one small text advertisement benefiting charity remains in all derivative works? Are there any licenses that would let me do this?

p.s. My other requirement for a license is that it gives me attribution (in the same form as the MIT license would be fine)

[EDIT]
I've decided to just let it be Apache licensed. I'm hoping that people will just leave charity-benefiting ads in.

答:
If by "open source" you mean "Free Software", then you have no other choice but to allow every possible kind of commercial exploitation, except those that would prevent people from accessing the sources. If you put restrictions on the source, such as mandating the inclusion of certain advertisements, then the software is no longer "free" (as in speech).

So you want to make money off of the software: that's fine, nothing wrong with that. But I believe making in "open source, but not really" isn't the right way to do it: you will miss out on many of the benefits of Free Software (for example, your advertisement clause will make it impossible to include your software in, say, debian), but you won't see much of the benefits of proprietary software either.

Going proprietary is one way to go, and unless you are a full-scale bearded hippie, I don't see any problem with that - you will miss out on free contributions, you will have a harder time gaining traction in the market, and you will have to actively persuade people to buy your product rather than just throwing it out there and waiting for people to bite; but you will also be able to put whatever price tag you like on the software, and pepper it with as many ads as you like.

The other alternative is to go completely Open Source: pick a suitable pre-written Free Software license (there is no point writing your own: the existing ones already cover pretty much all needs), and release it. You can't make any money from selling licenses, and you can't include ads in the software either (that would be pointless, as any fork could just remove them), but here are a few things you can exploit for money:

Support. As the author, you are the prime source of inside information on the software; it's OK to make people pay for that information.

Custom extensions and modifications. More often than you think, people are more than willing to pay to see your software incorporate feature X, even if that means everyone else will also get the feature. They don't pay your for exclusive rights to your development effort, but for prioritizing features they need the most.

Resume building. If it becomes popular, you'll be famous. Not rock star famous, but enough to give your professional networking a significant boost and increase your employability.

And then, there's dual licensing - in short, you can offer the product gratis under an Open Source license (typically one from the GPL family), and offer the option to "upgrade" to a commercial license that allows things your Open Source license doesn't (such as re-selling with modifications without providing sources). This is a thin line though, and it won't help your 'street credit' in Free Software land.


答:
The only way you can protect yourself against this sort of thing is to a) have a license that protects you from this, b) catch someone doing it, and c) use the court systems for remedy. Are you prepared to do that? Let's say you craft the perfect extension to a license which fully protects you. Are you willing and able to fight that in court when someone violates it?

No matter how great your website software is, the chance of you making money off of it once it goes open source is very nearly 0%. Accept that, and realize that the benefit of giving your source code away reaps benefits far greater than a small amount of money. If your software is as great as you think it is, giving it away will help people and that's a good thing.

Title: How can I ensure a portion of my project's code remains in all derivative works?

Body:
I had an idea for a website. After much coding and thinking out the idea, I've got it to a decent stage.

If I were someone else, potentially a more commercially-minded person, I might want to sell it, or slather it with ads. However, I've fallen somewhat in love with open-source, and I'd like to host the project on GitHub and give it a nice open-source license.

However, the project seems to be getting better all the time and, in fact, I think that it'll quickly grow to be fairly popular. So I want to put ads on it that benefit charity.

How can I ensure that one small text advertisement benefiting charity remains in all derivative works? Are there any licenses that would let me do this?

p.s. My other requirement for a license is that it gives me attribution (in the same form as the MIT license would be fine)

[EDIT]
I've decided to just let it be Apache licensed. I'm hoping that people will just leave charity-benefiting ads in.


问:
TDD with SQL and data manipulation functions
While I'm a professional programmer, I've never been formally trained in software engineering. As I'm frequently visiting here and SO, I've noticed a trend for writing unit tests whenever possible and, as my software gets more complex and sophisticated, I see automated testing as a good idea in aiding debugging.

However, most of my work involves writing complex SQL and then processing the output in some way. How would you write a test to ensure your SQL was returning the correct data, for example? Then, say if the data wasn't under your control (e.g., that of a 3rd party system), how can you efficiently test your processing routines without having to hand write reams of dummy data?

The best solution I can think of is making views of the data that, together, cover most cases. I can then join those views with my SQL to see if it's returning the correct records and manually process the views to see if my functions, etc. are doing what they're supposed to. Still, it seems excessive and flakey; particularly finding data to test against...

答:
At some point you're going to need test data. If you're using a 3rd party system, the schema has already been created, but you'll need to address future changes. Hopefully, you you can get these changes from upgrade documentation, but you may be forced to compare database versions yourself.

The expected result sets can be saved in database tables or external files/spreadsheets. I've even seen CHECKSUM used or comparison. When you test a view/sproc, you'll get a failure since they don't exist. Then you create the object with enough code to at least execute (SELECT -1 as [wrong_data];) and you'll get a failure because it doesn't match the result set. Once they match, you have your greenlight.

I've started to work with project owners and ask them to mock reports in a spreadsheet and try to come up with partial data for me (You could put the result data in a test table.). There was some pushback at first, but they realized I'm going to create a report and they're going to have to verify it anyway. This has saved time in the long run. If they want to make a change request, they get to redo the spreadsheet. Now they can answer the question, "How hard would it be to add...?"


问:
How can you learn names of methods or classes of a framework or an API?
I've been programming C++ for a year now. I've gone through the language features and I've written good programs with it, so I decided to move on to OpenGL. At first it seemed confusing. As I kept going through tutorials it appeared to be easier, but I can't remember the names of classes, methods, arguments, etc.

In fact this doesn't just apply for OpenGL; I often get stuck with other frameworks too. I have a program in my head, I know how it would work, but I cannot remember the names of methods or classes to use.

My question here is, in a nutshell, what techniques can you use to memorize those names? Does writing it over and over help you grasp it?

答:
Probably you will never be able to memorize all classes, methods and attributes of all libraries you use because it is simply too much information to keep in your head.

The more you use specific parts of libraries the more familiar and comfortable you will get with them, and eventually you will be able to recall the most used functions/classes without any reference.

However, for less used parts of the libraries you will still have to use reference material as it would be pointless to try to commit whole libraries including all the classes, functions and their attributes to your memory.

So in short:

just do more programming with the specific libraries to memorize the commonly used parts.

don't waste time to try and hard-learn all whole libraries function after function. Just use the references and you will eventually memorize the material that you use and need the most.

Good luck


答:
You don't memorize all those names. If the framework or the API is well done, those names will be intuitive.

For example if I want to save a file and I know that there is somewhere a method which does just that, I expect something like File.Save(path, contents). If the API provides it as IOOperations.OverwriteContents(path, new), then I will have hard time finding the method I need, and it probably means that this API sucks, because of a non-conventional, very unclear way of naming things.

Some examples:

I recently tried to use NPOI. I downloaded the library and opened it in Object Browser. The library is full of names like:

```<code>NPOI.POIFS.Dev.POIFSLister.DisplayDirectory(
    NPOI.POIFS.FileSystem.DirectoryNode dir,
    string indent)
</code>```

Without detailed documentation, I have no idea what is POIFS, what is Dev, what Lister of POIFS is listing, what DisplayDirectory displays and how do I create a NPOI.POIFS.FileSystem.DirectoryNode.

There is no way to use this library unless you have a few hours to read the documentation.

Let's say you want to serialize some XML, and you're pretty sure that .NET Framework has somewhere a method which does just that for you, but you have no idea of its name.

Among all System. assemblies, System.Xml sounds promising. Let's look inside. Hm. System.Xml.Serialization maybe? Ouch, lots of stuff inside. Let's look for names containing "serializer" or "serialize" inside. Here it is: XmlSerializer, and inside, the Serialize(Stream stream, object o) method.

Without knowing anything about this assembly before, you achieved to find what you need in a few seconds.

Remember that to help you finding the classes and methods you need, you have:

Documentation. It exists for that.

Stack Overflow search and Google. It helps when the API fails to be clear: if you have a hard time finding a method, chances are other people had the same issue.

Intellisense (auto-completion).

Title: How can you learn names of methods or classes of a framework or an API?

Body:
I've been programming C++ for a year now. I've gone through the language features and I've written good programs with it, so I decided to move on to OpenGL. At first it seemed confusing. As I kept going through tutorials it appeared to be easier, but I can't remember the names of classes, methods, arguments, etc.

In fact this doesn't just apply for OpenGL; I often get stuck with other frameworks too. I have a program in my head, I know how it would work, but I cannot remember the names of methods or classes to use.

My question here is, in a nutshell, what techniques can you use to memorize those names? Does writing it over and over help you grasp it?

Body:
You don't memorize all those names. If the framework or the API is well done, those names will be intuitive.

For example if I want to save a file and I know that there is somewhere a method which does just that, I expect something like File.Save(path, contents). If the API provides it as IOOperations.OverwriteContents(path, new), then I will have hard time finding the method I need, and it probably means that this API sucks, because of a non-conventional, very unclear way of naming things.

Some examples:

I recently tried to use NPOI. I downloaded the library and opened it in Object Browser. The library is full of names like:

NPOI.POIFS.Dev.POIFSLister.DisplayDirectory(
    NPOI.POIFS.FileSystem.DirectoryNode dir,
    string indent)

Without detailed documentation, I have no idea what is POIFS, what is Dev, what Lister of POIFS is listing, what DisplayDirectory displays and how do I create a NPOI.POIFS.FileSystem.DirectoryNode.

There is no way to use this library unless you have a few hours to read the documentation.

Let's say you want to serialize some XML, and you're pretty sure that .NET Framework has somewhere a method which does just that for you, but you have no idea of its name.

Among all System. assemblies, System.Xml sounds promising. Let's look inside. Hm. System.Xml.Serialization maybe? Ouch, lots of stuff inside. Let's look for names containing "serializer" or "serialize" inside. Here it is: XmlSerializer, and inside, the Serialize(Stream stream, object o) method.

Without knowing anything about this assembly before, you achieved to find what you need in a few seconds.

Remember that to help you finding the classes and methods you need, you have:

Documentation. It exists for that.

Stack Overflow search and Google. It helps when the API fails to be clear: if you have a hard time finding a method, chances are other people had the same issue.

Intellisense (auto-completion).


问:
How to structure template system using plain PHP?
I was reading this question over on stackoverflow:

https://stackoverflow.com/questions/104516/calling-php-functions-within-heredoc-strings

and the accepted answer says to do plain PHP templates like this:

template.php:

```<html>
    <head>
        <title><?=$title?></title>
    </head>
    <body>
        <?=getContent()?>
    </body>
</html>```

index.php:

```<?php

$title = 'Demo Title';

function getContent() {
    return '<p>Hello World!</p>';
}

include('template.php');

?>```

To me the above isn't well structured in the sense that template.php depends on variables that are defined in other scripts. And you're using an include() to execute code when you do include('template.php')(as opposed to using include() to include a class or a function which isn't immediately executed).

I feel like a better approach is to wrap your template inside a function:

template.php:

```<?php

function template($title, $content) {
    ob_start(); ?>

<html>
    <head>
        <title><?=$title?></title>
    </head>
    <body>
        <?=$content?>
    </body>
</html>

    <?php return ob_get_clean();
}

?>```

index.php:

```<?php

require_once('template.php');

print template('Demo Title', '<p>Hello World!</p>');

?>```

Is the second approach better? Is there an even better way to do it?

答:
Because Codeigniter is my favorite framework, I propose you a Codeigniter-ish solution:

```<code>class Template {
    protected $path, $data;

    public function __construct($path, $data = array()) {
        $this->path = $path;
        $this->data = $data;
    }

    public function render() {
        if(file_exists($this->path)){
            //Extracts vars to current view scope
            extract($this->data);

            //Starts output buffering
            ob_start();

            //Includes contents
            include $this->path;
            $buffer = ob_get_contents();
            @ob_end_clean();

            //Returns output buffer
            return $buffer;
        } else {
            //Throws exception
        }
    }
}
</code>```

Your template would look like:

```<code><html>
    <head>
        <title><?=$title?></title>
    </head>
    <body>
        <?=$content?>
    </body>
</html>
</code>```

And you would render it by instantiating the class, passing data in an array as a constructor parameter and calling the 'render' method:

```<code>$data = array('title' => 'My title', 'content' => 'My content');
$tmpl = new Template('template.php', $data);
echo $tmpl->render();
</code>```

In this way you are not directly executing the included code, and you are also keeping your template readable, so designers will be happy.

Body:
Because Codeigniter is my favorite framework, I propose you a Codeigniter-ish solution:

class Template {
    protected $path, $data;

    public function __construct($path, $data = array()) {
        $this->path = $path;
        $this->data = $data;
    }

    public function render() {
        if(file_exists($this->path)){
            //Extracts vars to current view scope
            extract($this->data);

            //Starts output buffering
            ob_start();

            //Includes contents
            include $this->path;
            $buffer = ob_get_contents();
            @ob_end_clean();

            //Returns output buffer
            return $buffer;
        } else {
            //Throws exception
        }
    }
}

Your template would look like:

<html>
    <head>
        <title><?=$title?></title>
    </head>
    <body>
        <?=$content?>
    </body>
</html>

And you would render it by instantiating the class, passing data in an array as a constructor parameter and calling the 'render' method:

$data = array('title' => 'My title', 'content' => 'My content');
$tmpl = new Template('template.php', $data);
echo $tmpl->render();

In this way you are not directly executing the included code, and you are also keeping your template readable, so designers will be happy.