答:
Without seeing the code in question, there are a few ways to write Java code in C++, some worse than others.

At the one extreme, there's laying out your source like Java: everything in one file, everything within the class definition, etc.:

```<code>class HelloWorldApp {
public:
    void main() {
        cout << "Hello World!" << endl;
    }
};
</code>```

This is how Java source would be laid out.  It's technically legal in C++, but putting everything in the header file and everything inline (by defining it in the class declaration) is terrible style and will kill your compile performance.  Don't do it.

Excessively OO - To oversimplify, in Java, it's the Kingdom of the Nouns, where everything is an object.  Good (i.e., idiomatic) C++ code is more likely to use free functions, templates, etc., instead of trying to cram everything into an object.

No RAII - You already mentioned this - using pointers and manual cleanup instead of smart pointers.  C++ gives you tools like RAII and smart pointers, so good (i.e., idiomatic) C++ code uses those tools.

No advanced C++ - The basics of Java and C++ are similar enough, but once you get into more advanced features (templates, C++'s algorithms library, etc.), they start to diverge.

Except for #1, none of these make a C++ program a bad program, but it's also not the kind of code I prefer to work on as a C++ programmer.  (I also wouldn't enjoy working with non-idiomatic or C-style Perl, non-idiomatic Python, etc.)  A language has its own tools and idioms and philosophy, and good code uses those tools and idioms instead of trying to use the lowest common denominator or trying to reproduce another language's approach.  Writing non-idiomatic code in a particular language / problem domain / whatever doesn't make someone a bad programmer, it just means that they have more to learn about that language / problem domain / whatever.  And there's nothing wrong with that; there's a very long list of things I have more to learn about, and C++ in particular has an absolute ton of stuff to learn.

Regarding the particular question of writing error-prone code with the intent to clean it up later, it's not black and white:

If some prototype code fails to handle every possible exception and every possible corner case, then that's to be expected.  Get it working, then get it working robustly.  No problem.

If some prototype code is written in what's simply a bad style or a bad design (bad for the given language and its idioms, a fundamentally bad design for the problem, etc.), then unless you're writing it as a throw-away proof-of-concept, you're not gaining anything.

To use raw pointers versus smart pointers as an example, if you're going to work in C++, using RAII and smart pointers are fundamental enough that it should be faster to write code that way than to go back and clean it up later.  Again, failing to do this doesn't mean someone's a bad programmer, unprofessional, etc., but it does mean there's more to learn.

Title: Why is it bad to write something in language X as if you're writing a program in language Y in terms of using a shared coding paradigm

Body:
A while ago, I asked a question on SO about something written in C++, but instead of getting an answer to the problem at hand, the comments went all crazy on my coding style, even when I indicated that it was a WIP piece of code and that I meant to clean it up later when I had the base case running. (I got so many down votes that I decided to pull the question, as my rep on SO already is near-abysmal)

It made me wonder why people adopt such a hard line "you're a noob, go fuck yourself" attitude. I was being accused of writing C++ as if it was Java. Something that I cannot understand, and that still baffles me.

I've been programming in quite a few OOP languages for a number of years now, albeit in intervals. I choose the language to use in terms of its available libraries and optimal execution environments for the job at hand. I adopt design patterns in OOP code and I'm quite confident  that my use of patterns is sound and that OO wise, I can hold my own. I understand the OOP toolbox, but choose to use the tools only when I think it's really required, not to just use a neat trick to show my coding wits. (Which I know are not top notch, but I think aren't at n00b level either).

I design my code before I write a single line. To define tests, I list the goals of a certain class, and the test criteria that it has to adhere to. Because it is easier to me to create sequence diagrams and then write code, I chose to write my tests after the interface has become obvious.

I must admit that in the piece of code I posted in the question, I was still using pointers, instead of using smart pointers. I use RAII whenever I can. I know proper RAII means safeguarding against nullpointers, but I work incrementally. It was a work in progress and I meant to clean it up later. This way of working was condemned strongly.

In my view, I should have a working example first so I can see if the base case is a viable way of thought. I also happen to think that cleaning up the code is something that is typical of the refactoring phase of agile, after the base case has been proven. I must admit that although I'm slowly getting the Cxx standard, I prefer to use what I understand, instead of taking the risk of using concepts that I have yet to master in production code. I do try new stuff once in a while, but usually in play projects that I have on the side, just for that purpose.

[edit] I'd like to clarify that gnat's suggestion [1] did not show up in the search I did before I started to ask my question. However although his suggestion does cover one aspect of the question, the question he linked to does not answer the heart of my question, just part of it. My question is more about the response I got to my coding style and the professional aspects of handling different coding styles and (apparent) levels of skill. With my previous question on SO and it's response as a case in point.
[/edit]

The question then is: why scoff someone that doesn't use your coding style?

The matters/subdivisions at hand for me are:

Why would it be a bad programming practice to use more error prone code in prototype situations, if refactoring makes it more robust afterward?

How would can program written in C++ be like it was written in Java? What makes it a bad program, (considering that I indicated the intent of the current style and the planned work to improve?)

How would I be a bad professional if I chose to use a construct that is used in a certain programming paradigm (e.g. OOP/DP)?

[1] Develop fast and buggy, then correct errors or be slow, careful for each line of code?

Body:
Without seeing the code in question, there are a few ways to write Java code in C++, some worse than others.

At the one extreme, there's laying out your source like Java: everything in one file, everything within the class definition, etc.:

class HelloWorldApp {
public:
    void main() {
        cout << "Hello World!" << endl;
    }
};

This is how Java source would be laid out.  It's technically legal in C++, but putting everything in the header file and everything inline (by defining it in the class declaration) is terrible style and will kill your compile performance.  Don't do it.

Excessively OO - To oversimplify, in Java, it's the Kingdom of the Nouns, where everything is an object.  Good (i.e., idiomatic) C++ code is more likely to use free functions, templates, etc., instead of trying to cram everything into an object.

No RAII - You already mentioned this - using pointers and manual cleanup instead of smart pointers.  C++ gives you tools like RAII and smart pointers, so good (i.e., idiomatic) C++ code uses those tools.

No advanced C++ - The basics of Java and C++ are similar enough, but once you get into more advanced features (templates, C++'s algorithms library, etc.), they start to diverge.

Except for #1, none of these make a C++ program a bad program, but it's also not the kind of code I prefer to work on as a C++ programmer.  (I also wouldn't enjoy working with non-idiomatic or C-style Perl, non-idiomatic Python, etc.)  A language has its own tools and idioms and philosophy, and good code uses those tools and idioms instead of trying to use the lowest common denominator or trying to reproduce another language's approach.  Writing non-idiomatic code in a particular language / problem domain / whatever doesn't make someone a bad programmer, it just means that they have more to learn about that language / problem domain / whatever.  And there's nothing wrong with that; there's a very long list of things I have more to learn about, and C++ in particular has an absolute ton of stuff to learn.

Regarding the particular question of writing error-prone code with the intent to clean it up later, it's not black and white:

If some prototype code fails to handle every possible exception and every possible corner case, then that's to be expected.  Get it working, then get it working robustly.  No problem.

If some prototype code is written in what's simply a bad style or a bad design (bad for the given language and its idioms, a fundamentally bad design for the problem, etc.), then unless you're writing it as a throw-away proof-of-concept, you're not gaining anything.

To use raw pointers versus smart pointers as an example, if you're going to work in C++, using RAII and smart pointers are fundamental enough that it should be faster to write code that way than to go back and clean it up later.  Again, failing to do this doesn't mean someone's a bad programmer, unprofessional, etc., but it does mean there's more to learn.


问:
Why is it bad to write something in language X as if you're writing a program in language Y in terms of using a shared coding paradigm
A while ago, I asked a question on SO about something written in C++, but instead of getting an answer to the problem at hand, the comments went all crazy on my coding style, even when I indicated that it was a WIP piece of code and that I meant to clean it up later when I had the base case running. (I got so many down votes that I decided to pull the question, as my rep on SO already is near-abysmal)

It made me wonder why people adopt such a hard line "you're a noob, go fuck yourself" attitude. I was being accused of writing C++ as if it was Java. Something that I cannot understand, and that still baffles me.

I've been programming in quite a few OOP languages for a number of years now, albeit in intervals. I choose the language to use in terms of its available libraries and optimal execution environments for the job at hand. I adopt design patterns in OOP code and I'm quite confident  that my use of patterns is sound and that OO wise, I can hold my own. I understand the OOP toolbox, but choose to use the tools only when I think it's really required, not to just use a neat trick to show my coding wits. (Which I know are not top notch, but I think aren't at n00b level either).

I design my code before I write a single line. To define tests, I list the goals of a certain class, and the test criteria that it has to adhere to. Because it is easier to me to create sequence diagrams and then write code, I chose to write my tests after the interface has become obvious.

I must admit that in the piece of code I posted in the question, I was still using pointers, instead of using smart pointers. I use RAII whenever I can. I know proper RAII means safeguarding against nullpointers, but I work incrementally. It was a work in progress and I meant to clean it up later. This way of working was condemned strongly.

In my view, I should have a working example first so I can see if the base case is a viable way of thought. I also happen to think that cleaning up the code is something that is typical of the refactoring phase of agile, after the base case has been proven. I must admit that although I'm slowly getting the Cxx standard, I prefer to use what I understand, instead of taking the risk of using concepts that I have yet to master in production code. I do try new stuff once in a while, but usually in play projects that I have on the side, just for that purpose.

[edit] I'd like to clarify that gnat's suggestion [1] did not show up in the search I did before I started to ask my question. However although his suggestion does cover one aspect of the question, the question he linked to does not answer the heart of my question, just part of it. My question is more about the response I got to my coding style and the professional aspects of handling different coding styles and (apparent) levels of skill. With my previous question on SO and it's response as a case in point.
[/edit]

The question then is: why scoff someone that doesn't use your coding style?

The matters/subdivisions at hand for me are:

Why would it be a bad programming practice to use more error prone code in prototype situations, if refactoring makes it more robust afterward?

How would can program written in C++ be like it was written in Java? What makes it a bad program, (considering that I indicated the intent of the current style and the planned work to improve?)

How would I be a bad professional if I chose to use a construct that is used in a certain programming paradigm (e.g. OOP/DP)?

[1] Develop fast and buggy, then correct errors or be slow, careful for each line of code?

答:
I'm not a hardcore C++ developer, but...

Why would it be a bad programming practice to use more error prone code in prototype situations, if refactoring makes it more robust afterward?

One thing to keep in mind is that an error in C++ usually means "undefined behavior". In a safe language the worst that could happen is an exception terminating your program immediately. In C++, you're lucky if you get a segfault. It's entirely possible your program keeps going doing something subtly wrong. It could also behave correctly for a period of time and manifest bugs much later, or it could behave correctly all the time but eventually eat up all your memory.

In any case, it only takes a single mistake to take program execution completely off the rails and into uncharted territory. It's likely that for the full-time C++ developer, the "base case" means "no possibility of undefined behavior or memory leaks."

How would can program written in C++ be like it was written in Java? What makes it a bad program?

I don't think there's an answer to this that won't be largely speculatory and opinionated. If you want my take on it though, Java tends to have a couple of antipatterns associated like the fact that everything has to be an object. Where in other languages you'd pass a pointer, functor, or function, in Java you usually find tons of vacuous and narrowly-useful ThingDoers, FooFactories, and IFrobnicators which are just functions in disguise.

Likewise, where in other languages you might pass a simple tuple or nameless struct, in Java to bundle up even just 2 objects into a simple data container requires you to predefine a 30+ line NamedThing class with setters, getters, and Javadocs. Java's relative lack of features forces programmers to do object-oriented double backflips to get things done sometimes. The resulting code is rarely idiomatic outside of Java.

Then there's the fact that in C++ you need a very simplified object graph to manage memory manually; usually an object is owned by exactly one other object. In Java you don't need to follow such tight constraints, because the garbage collector ensures things will get cleaned up when there's no more references to them. So there's definitely a risk of incorrect memory management if you just transliterate code from Java to C++.

Finally, it could just be elitism. I won't pretend they make up the majority, but I've definitely seen a sentiment of "I don't need a language that'll hold my hand and keep me from doing stupid things" amongst some C++ developers. In their minds C++ is a "real" language and if you can't handle its idiosyncrasies you're not a "real programmer".

ContentLicense: CC BY-SA 3.0


问:
Should I refactor my unit tests when I extract a class out of the System Under Test?
I wrote this class that does a few things (perhaps this is a violation of the Single Responsibility Principle).  I realize now that some other part of the project needs a piece of that logic and the way I'm going to expose it is to extract a class out of my original System Under Test.

I anticipate being able to do this without having to change any test code, but when I finish, you could argue that the test isn't a unit test anymore.  It'll be testing the original class and the class I've extracted.  In other words, I'll have one test case, but two systems under test.

Am I supposed to refactor my test code after I'm done?  IE: Create an ExtractedClassTest and move all the relevant tests from OriginalClassTest into it?  This seems like it could be a little risky: I may lose some coverage in the process, it may not be as simple as moving a test and I'd end up rewriting some test code that I know used to work but may not anymore, etc.

On the other hand, if I leave the OriginalClassTest as-is, I can see this being a test maintenance issue.  It'll be a little confusing to find where the ExtractedClass's tests are. Your first impression will be that it doesn't exist.  Over time with lots of production code refactorings, this could become a serious issue.

I'm new to TDD so I'd like an expert's advice.  Thanks!

答:
After watching this amazing talk "Ian Cooper: TDD, where did it all go wrong", I'm going to disagree with @pdr.  I think you should only keep the original tests.  Your ability to refactor your system under test without breaking, writing or changing any tests is the whole purpose of writing tests in the first place. </p>

<p>If I were to test the extracted class, I'd be testing the implementation rather than the behavior.  As a result, my code would be more difficult to refactor in the future: These new tests would likely fail even if the behavior still worked.  </p>

Body:
After watching this amazing talk "Ian Cooper: TDD, where did it all go wrong", I'm going to disagree with @pdr.  I think you should only keep the original tests.  Your ability to refactor your system under test without breaking, writing or changing any tests is the whole purpose of writing tests in the first place.

If I were to test the extracted class, I'd be testing the implementation rather than the behavior.  As a result, my code would be more difficult to refactor in the future: These new tests would likely fail even if the behavior still worked.


答:
Each programming language has a set of idioms and best practices, which will usually lead to elegant, correct, and performant code. Here are a few worst-practices that are perfectly fine in some other language:

I will yell if you write for ($i = 0; $i < 42; $i++) { … } in Perl, but not in PHP

(in Perl, variables should be declared, and such loops should iterate over a range)

I will weep if you write new Foo() in C++ without good reason, but not in Java

(C++ doesn't have garbage collection, so RAII should be used. Noobs will leak memory otherwise)

I will cringe if you declare all your variables at the top of your function, except in C89, Pascal, or JavaScript.

I will facepalm if you put all your functions into a class in Python, but not in Java

(Python is a multi-paradigm language instead forcing “OOP” and supports functions at the top level)

I will cry if you return null in Scala, but not in any C-like language

(because Scala has an Option type)

I will complain if you write a recursive algorithm in Java, but not in OCaml

(because Java's stack overflows quickly, whereas OCaml has tail call optimization)

…

It is easy to use a new language as if it were something you know, and with luck it will even work. “You can write Fortran in any language”. But you really don't want to ignore the specific features language X offers, because chances are good that X offers some advantage over U.

“I choose the language to use in terms of its available libraries and optimal execution environments for the job at hand” – but whether this language X is actually better than language U for the job at hand also depends on how familiar with that language, or how long it will take to get sufficiently familiar in order to use it well. You wouldn't yield a heavy chainsaw just because it cuts wood fastest, when you actually want your old pen knife because it fits into your hand perfectly. Unless you actually want to fell a tree.

But your question is more about a cultural issue: learning all best practices takes a lot of time, and newbies ask the most questions, whereas gurus answer them. But what is obvious to a guru is not obvious to a newbie, and gurus sometimes forget that. As a newbie, the solution is not to stop asking questions. However, one can show an openness to learn and apply best practices, e.g. by trying to clean up your code as much as possible before showing it to others. Most languages have a few core best practices which are easy to learn, even when the whole learning curve is actually very long.

A common problem is that people new to programming disregard any indentation or other formatting, and then are confused because their program doesn't work. I would be confused as well, and the first step to understanding a program is making sure it's perfectly layouted. Then, simple errors like a forgotten closing quote or a missing comma suddenly become obvious. I trust that you already practice good formatting, and here it's a metaphor for other best practices: best practices prevent errors, best practices make finding errors easier, applying best practices comes before finding the problem.

It is too cheap to say “I'll fix it later”, when fixing it now would have solved your problem (also, that fabled “clean-up phase” may never come, so the only responsible option is to do it right the first time). At the very least, trying to make your code as good as possible before asking others for help makes it easier for them to reason about your code, so is the polite thing to do.


问:
What design pattern can I use to represent processing data from any stream?
I'm reading data from a stream in buffered series of bytes (say 1024 bytes at a time) and do some comparison, checking, or processing, before writing it back to the same type of stream.

Currently data comes from file.  But in the future it may come from other sources (memorymapped file, TCP etc)

Is there a design pattern I can implement?  Or is that not necessary?

答:
The .NET Framework provides the Stream abstract class for this purpose.

.NET offers a number of Stream Reader and Writer objects out of the box.  One of those may already fit your needs, or you can inherit from Stream in a new class, and write your own custom implementation.


问:
Best practice to return a long string in a stub
I have some methods im trying to test which use a StreamReader dependency that i mock using Rhino mocks. But it is a large xmlFile. In the spirit of unit testing im trying to keep away from using a test file in my test project.

On the other hand copy-pasting 100 lines of xml into my test class seems sort of ugly. What is the best practice when returning large strings using a stub.

答:
I'm not sure what "spirit of unit testing" you are talking about. But if you really need to address that spirit ...

Have basic tests that use small data sets. You can put string constants in your code for this purpose.

Have not-so-basic tests that actually test the things that need to be tested. For these tests, your driver can feel free to call on all the resources you need to get the job done. The file system is such a resource.

The files which contain the test data become configuration items that are controlled in your software configuration management system.


问:
Is it fine to make a default constructor unusable?
Specifically asking about the default constructor

Given that the constructor initializes all the data for an object, if I create a class that can't be used without proper initialization, is it not the case that the default constructor is useless?  Consider:

// A class for handling lines in a CSV file
class CSV_Entry {
private:
    unsigned num_entries;
    std::string string_version;
    std::vector<std::string> vector_version;
    ...etc
public:
    CSV_Entry();
    CSV_Entry(const std::string& src_line);

    // returns a vector copy of the original entry
    std::vector<std::string> get_vector_snapshot();
}

int main( void ) {
    ...etc

    CSV_Entry example = CSV_Entry();
    std::vector<std::string> current_entry = example.get_vector_snapshot();

    ...etc
}
```

<p>That variable <code>current_entry</code> is essentially useless no?   If someone tries to process it later on, they would likely get errors; then they'd create code to handle such errors...</p>

<p>To mitigate such additional, unnecessary code: why not make the default constructor unusable?  Like so,</p>

<pre class="lang-cpp prettyprint-override"><code>...etc

CSV_Entry() {
    throw Verbose_Exception( "CSV_Entry: do not use the default constructor" );
}

...etc
</code>```

PS: on a side note, if it is fine to just make the default constructor unusable, is it fine to put that throw in the header, since no other implementation details are revealed anyway?

答: Yes, it's fine (actually, it's good) to make the default constructor unusable if there's no sensible way to initialize the object without any arguments. But don't "disable" it by throwing an exception. Make it private instead. Ideally your interface won't contain any methods or constructors people "aren't supposed to" call.


问:
How can I handle this string concatenation in C in a reusable way
I've been writing a small C application that operates on files, and I've found that I have been copy+pasting this code around my functions:

```<code>char fullpath[PATH_MAX];
fullpath[0] = '\0';
strcat(fullpath, BASE_PATH);
strcat(fullpath, subdir);
strcat(fullpath, "/");
strcat(fullpath, filename);

// do something with fullpath...
</code>```

Is there a better way? The first thought that comes to mind is to create a macro but I'm sure this is a common problem in C, and I'm wondering how others have solve it.

答:
How about passing the address of fullpath, subdir, and filename into a function and have that function concatenate all of the strings for you?

Something to the effect of:

```<code>void main(...)
{
    char fullpath[PATH_MAX];
    memset(fullpath, 0x00, PATH_MAX); //note: probably wrong syntax for memset
    ...
    ConcatPath(&fullpath, subdir, filename);
}

ConcatPath(char *fullpath, char *subdir, char *filename)
{
    strcat(fullpath, BASE_PATH);  //note need some casting magic here to reference
    strcat(fullpath, subdir);     // fullpath & other strings correctly.
    strcat(fullpath, "/");
    strcat(fullpath, filename);
}
</code>```

Body:
How about passing the address of fullpath, subdir, and filename into a function and have that function concatenate all of the strings for you?

Something to the effect of:

void main(...)
{
    char fullpath[PATH_MAX];
    memset(fullpath, 0x00, PATH_MAX); //note: probably wrong syntax for memset
    ...
    ConcatPath(&fullpath, subdir, filename);
}

ConcatPath(char *fullpath, char *subdir, char *filename)
{
    strcat(fullpath, BASE_PATH);  //note need some casting magic here to reference
    strcat(fullpath, subdir);     // fullpath & other strings correctly.
    strcat(fullpath, "/");
    strcat(fullpath, filename);
}


答:
In the spirit of unit testing im trying to keep away from using a test file in my test project.

In the battle between idealism and pragmatism, sometimes a truce is needed.

The main push for not using test files is threefold:

Your job isn't to test reading files from disk, it's to test the stuff at hand.

Having files tends towards multiple tests using the same file, which in turn tends towards the tests not being isolated.

Reading from disk is pretty much always going to be slower.

Which conflict against three of the core traits of unit tests: fast, isolated, focused.

But you're right. Having giant blobs of xml in your tests isn't terribly maintainable or pretty. Simply placing a small file into your test project isn't a gross violations of these motivations. In C#, loading a file is dead simple and nearly foolproof. You'll need to work to keep the file isolated to keep it from being an inter-test dependency, and you may need to move it back to code if it slows your tests too much.

Title: Best practice to return a long string in a stub

Body:
I have some methods im trying to test which use a StreamReader dependency that i mock using Rhino mocks. But it is a large xmlFile. In the spirit of unit testing im trying to keep away from using a test file in my test project.

On the other hand copy-pasting 100 lines of xml into my test class seems sort of ugly. What is the best practice when returning large strings using a stub.


答:
Slightly off topic answer...

Don't worry - this is a common "behavior" in any expert community. And be honest, if you're good in any language, and you will meet a code what is "strange", probably you will criticizing it too. (because, want TEACH).

I'm in the perl-world - when will see something like:

```<code>$imax=$#array;
$str=""
for($i=0; $i<$imax; $i++) {
    $str = "$str" . $array[$i];
}
</code>```

instead of:

```<code>my $str = join '', @array;
</code>```

sure will comment it - (read: teach the author) about the join function.

Anyway, too much criticism is counterproductive at all, and one of the best example is the next: (grabbed from: http://perl-begin.org/humour/#How_can_I_switch_off_the_T.V..3F)

(This bit was posted anonymously to a pastebot on 23 March, 2011. It is placed here for posterity after some editing.) - slightly edited too

Question: how can I switch on my TV?

What the OP wants to hear?

For example: Locate on/off button your TV
remote a press it. The button is usually red and located at the
topmost line on the remote.

The #perl expert's answer: First, what do you mean with "switch on"?
Define it first. Nopaste your TV, TV remote and the living room too.

... after a nopaste:

Your room is ugly. And the TV looks terrible. Use Mr. Clean on the
screen, and clean your living room first. Use three cleaning mops
instead of two. Use HDMI and never use scart (?) connectors, unless
you really want to. Your TV remote has unreadable buttons, clean up
first. You're a beginner, so read:

http://experts.blog/how_to_design_a_future_3D_TV.html
http://experts.blog/the_basics_of_tv_repairing.html
http://experts.blog/viruses_in_living_room_short_essay.html
http://experts.blog/global_chip_replacement_guide.html

IRC guest: But, i don't want be a TV expert.

Answer: Why do you want to switch the TV on then?!

Body:
Slightly off topic answer...

Don't worry - this is a common "behavior" in any expert community. And be honest, if you're good in any language, and you will meet a code what is "strange", probably you will criticizing it too. (because, want TEACH).

I'm in the perl-world - when will see something like:

$imax=$#array;
$str=""
for($i=0; $i<$imax; $i++) {
    $str = "$str" . $array[$i];
}

instead of:

my $str = join '', @array;

sure will comment it - (read: teach the author) about the join function.

Anyway, too much criticism is counterproductive at all, and one of the best example is the next: (grabbed from: http://perl-begin.org/humour/#How_can_I_switch_off_the_T.V..3F)

(This bit was posted anonymously to a pastebot on 23 March, 2011. It is placed here for posterity after some editing.) - slightly edited too

Question: how can I switch on my TV?

What the OP wants to hear?

For example: Locate on/off button your TV
remote a press it. The button is usually red and located at the
topmost line on the remote.

The #perl expert's answer: First, what do you mean with "switch on"?
Define it first. Nopaste your TV, TV remote and the living room too.

... after a nopaste:

Your room is ugly. And the TV looks terrible. Use Mr. Clean on the
screen, and clean your living room first. Use three cleaning mops
instead of two. Use HDMI and never use scart (?) connectors, unless
you really want to. Your TV remote has unreadable buttons, clean up
first. You're a beginner, so read:

http://experts.blog/how_to_design_a_future_3D_TV.html
http://experts.blog/the_basics_of_tv_repairing.html
http://experts.blog/viruses_in_living_room_short_essay.html
http://experts.blog/global_chip_replacement_guide.html

IRC guest: But, i don't want be a TV expert.

Answer: Why do you want to switch the TV on then?!

ContentLicense: CC BY-SA 4.0


问:
How to model more than one 'last name'?
In Spanish-speaking countries we use more than one last name, like:

First name ↘                           ↙ Last name

                  Pedro Arturo Rodríguez Loyola

          Middle name ↗                               ↖ (?)

I'm trying to model data for patient name. In our country it's important, so I can't neglect the second last name, but I would like to build an application that can makes sense to other developers, especially from English-speaking countries.

I created a similar question on English.SE, it has some insights about why it's important to persist both values.

答:
Let’s consider this in another way.

Your system has to connect to other systems, it does not matter how flexible you are if they are not.  So what does the systems you have to transfer data with do?

When I phone up my doctor for an appointment they ask me for my date of birth, the systems then shows them a list of people that match,  then they ask me for my name, lastly the ask for my address to confirm that they have selected the correct person.

The doctor needs to know the name address me by when talking to me; they also need to know the name to put on an letter if they write to me.

Therefore way not just a single text field that allows spaces.   There is no reason to even separate the first from the last name, unless you will process them in same way.

Title: How to model more than one 'last name'?


问:
Injecting dependencies (DI) in c++ applications
I am playing with dependency injection, but i am not sure I am doing it right.
Especially, I am not sure what should be the correct way to build classes with injected dependencies.

Say I have a class A that creates class B. Class B depends on class C and class C depends on class D. Who should be responsible for creating class D?

It could be class A. However, in a large system, class A might end up creating and assembling a very large number of objects.

A separate builder class that will create D, C and B. A will use this builder class.

Some other option.

In addition, I read a lot about DI containers. However, it seems that there are no major frameworks for C++. Also, if I understand correctly, DI can be performed well even without containers. Am I correct?

答:
Who should be responsible for creating class D?

Every time the question like that pops up, it indicates a dependency to inject. The whole idea is to "delegate" responsibility outside of the object that seems to be having a problem figuring how to handle it.

Using your example, since class A doesn't seem to possess sufficient "knowledge" to figure how to create D, you invert the control and expose this as a dependency needed for class A, by making it require a factory that knows how to create instances of class D.


问:
Initialization of objects in a system using dependency injection
This is a follow up question to the following post: Injecting dependencies (DI) in c++ applications

In a system that uses DI, someone, somewhere should be responsible to create the various objects and "wire" them. I find it difficult to figure out who should do this. I read about one option that it should be the "root class". However, in that case it seems that the root class might be responsible for creating a very large number of objects.

I though of an option to use smaller builder classes that will be used the root class - is that a good way to do it?

Note: I tagged 'C++' in this question because I am developing in C++. I am not sure if it makes any difference to the answer.

答:
If you're using a DI Container, the DI Container is responsible for  figuring out what the needed dependencies are.  If you're injecting dependencies through the class constructor, the caller of the constructor is responsible.

So in your original example of

```<code>A --> B --> C --> D
</code>```

A would be responsible for handing the necessary dependencies to B, B would be responsible for handing the necessary dependencies to C, and so on.

Body:
If you're using a DI Container, the DI Container is responsible for  figuring out what the needed dependencies are.  If you're injecting dependencies through the class constructor, the caller of the constructor is responsible.

So in your original example of

A --> B --> C --> D

A would be responsible for handing the necessary dependencies to B, B would be responsible for handing the necessary dependencies to C, and so on.


答:
It's  not a complicated thing..... or I am missing something.

Have these fields: name (varchar), lastname (varchar).

Then a form to fill the complete name, example: Jorge Patricio and the last name Pèrez Gonzáles.

In the search, you have many comparison operators, for example in MySQL, like like which will help you looking.

Mostly the composed last names always are in order. Pérez González mostly says its last name that way, and not in reversed order.

You will be over-designing your database other way.

Title: How to model more than one 'last name'?

Body:
In Spanish-speaking countries we use more than one last name, like:

First name ↘                           ↙ Last name

                  Pedro Arturo Rodríguez Loyola

          Middle name ↗                               ↖ (?)

I'm trying to model data for patient name. In our country it's important, so I can't neglect the second last name, but I would like to build an application that can makes sense to other developers, especially from English-speaking countries.

I created a similar question on English.SE, it has some insights about why it's important to persist both values.


答:
It depends on the intended lifetime and ownership of your objects. To construct an object of type C you need an object of type D. Shall this D object have the same lifetime as the C object? Then it makes sense to construct the D object at the same scope where the C object is constructed. Shall the D object live longer than C? Then you should construct it outside before and pass it to the function which constructs C.

Given your objects B, C and D shall have the same lifetime, and that lifetime shall be controlled by an object of type A, it makes sense to let A construct them and "wire" them. If the D object shall live longer, it must be constructed (and destroyed) outside of A.

If you note that A gets too much responsibilities by managing other, dependent objects of B, A might use a "BFactory" class for this purpose, like @gnat suggested as a response to your other question. And if you want to avoid A having to construct that factory, this factory could also be injected into A through an interface "IBFactory".

And if your system gets really large, because you have to not four but 400 classes to manage, then a DI container would be the better choice.

Title: Initialization of objects in a system using dependency injection

Body:
This is a follow up question to the following post: Injecting dependencies (DI) in c++ applications

In a system that uses DI, someone, somewhere should be responsible to create the various objects and "wire" them. I find it difficult to figure out who should do this. I read about one option that it should be the "root class". However, in that case it seems that the root class might be responsible for creating a very large number of objects.

I though of an option to use smaller builder classes that will be used the root class - is that a good way to do it?

Note: I tagged 'C++' in this question because I am developing in C++. I am not sure if it makes any difference to the answer.


问:
Reflecting on finished project with no other technical criticisms?
I'm a coop (in college but I work 3 months, then do classes for 3 months, work again for 3 months, etc until I graduate) at a company in their IT department. My job usually has to do with writing software but we are not a software company and much of the software that is is written in India. This work term (3 months) I was given a large project, to design some software to visualize data pulled from another one of our systems.

I ended up at the end of this term with two pieces of software for, one 100% done (the data pulling back end) and the other 80% done (the graphical front end). I had fun and learned a lot as always, but I'm not too happy with the results code wise. I have never gotten a chance for a code review or a chance to do any learning about design and analysis strategies for the reason I mention above in the year that I've been here (4 terms).

Here's how the project went, and it reflects how I have done pretty much every project to date, although it's more clear in this project as this is the biggest thing I've done so far. The first thing I did was diagram out how the whole system would operate from a high level. I don't usually do this but I was asked to by my boss. Then, I dove right into the problem and start banging away. To me, I find that it helps (and is more fun at the same time) to get something down and working to revise for organization shortly after so that I can continue in an organized fashion. From there the building slowed down a bit as the project got bigger. I would get more confused but also start diagramming more things out first, stopping to think about how what I'm currently building will fit into the entire system. This continued on for a while until my 3 month term was almost up. Here, I started rushing to get things done. I started destroying some of the organization in favor of quick things so that I could get a working prototype (I was only asked for a prototype so I figured this was alright and if the project went forward I could always revise it). This is where my entire thing started to fall apart as I didn't really have time to properly think through how a lot of what I was coding would affect everything else. I feel like now, at the final stage, I have a lot a mix of loosely and tightly coupled code with a barely working prototype.

In hindsight, here's what I see:

I did a good job on the original overview and it helped me too because I could break down the entire thing into a few main chunks. Problems started to arise when I got into specifics of each chunk. There was a good set idea on what each piece would do, but not the specific parts that made that piece work (I don't know what I could have done more though to explain each piece though. I find when it comes down to specifics like this, I find out as I go).

There were many things about the system that I was pulling data from that I did not know at the very start and I should have gotten a lot more insight onto how the system works as a whole. However, at the start of the term I'm always shy and tend to not ask questions. This probably also contributed to why I usually don't know the specifics of each piece until I'm actually doing them.

I was also a victim of a bit of scope creep as few features were added to the todo list with about a month and a half to go.

I never seem to know exactly where I want to go on specific parts. I try something and if that doesn't work, I try something else until it works or I get something that's neater. Is this the right way to do things?

My questions:

What could I have done better? I know no one here will know the specifics of my project but there's no one else with coding knowledge who could tell me how I could grow in this situation.

How could I review myself better? Since I never really have anyone else reviewing my coding and I'm not working with any other coders directly, how could I have reflected better on my own project, both after, and during the project?

The question about what I could do better is directed mainly at the bolded portions of my explanation where I feel most concerned about how I approached the problem.

答:
A couple of thoughts.

Three months is not a lot of time.  That you got one complete project working, and another 80% done in that time (utilizing the entire SDLC), is fairly impressive.  In my experience, employers expect this to happen in a coop setting; being a coop is primarily an educational process, not a product push.

For better or worse, getting a working product out the door is generally considered more valuable that crossing every best practices T and dotting every coding style I.

There was a good set idea on what each piece would do, but not the specific parts that made that piece work

It is the job of a Software Engineer to design and code implementations of specified problems.  Some problems are better specified than others.  To improve on a specification (I assume that you had a formal set of requirements), you can write a Software Design Specification.  The SDS describes the public API of each class in  your project, and states what it is supposed to do (the expected inputs and outputs, etc).  This can form the basis for Unit Tests that formalize those requirements into a coded specification.

I started destroying some of the organization in favor of quick things so that I could get a working prototype

As you gain experience in software development, it will become easier for you to combine rapid prototyping with a sensible design structure.


问:
Is declaring STL variables in a class definition too revealing?
If you are trying to hide implementation, would declaring STL variables be too revealing?  </p>

```<code>// in Word_Bucket.h
class Word_Bucket {
private:
    std::vector<std::string> contents;

    ...etc
}
</code>```

<p>... but then if you wrap it up, to hide the implementation, won't you have to reveal it in the wrapper's interface anyway?</p>

```<code>// in Word_Bucket.h
class Word_Bucket {
private:
    Bucket contents;

    ...etc
}

// in Bucket.h
class Bucket {
private:
    std::vector<template_stuff> contents;

    ...etc
}
</code>```

答:
The point of Information Hiding in OOP isn't for any purpose of secrecy. Even without the header files, inspection of your binaries can reveal quite a bit about your internal implementation.

The purpose of Information Hiding is to define the boundaries of the black box for users of a class to interface with, and provides an implicit contract for how your class is expected to behave.

Declaring members public or private isn't to keep them secret, it is to segregate "Here are the controls, don't worry about this other stuff".

If I see a vector in a class declaration as a private member, I'm going to assume that the class manages elements in that vector, and that I don't have to deal with it.


问:
Is there a valid case for two components to depend on each other?
Dependencies are services required by an object to perform its responsibilities. In OOP context it can be thought as a parameter in a constructor.

In my experience I've never found a case for a valid cyclic A <--> B dependency. Every time I find this it turns out to be one of two cases:

A and B should actually be a single component (AB)

one of components violates single responsibility principle and should be divided into separate ones (A1 --> B --> A2)

To be clear, I'm not talking about cycles in objects used for data structures. I'm interested in components which provide behavior and collaborate between themselves.

答:
This is just a self-fulfilling prophecy - whenever you find a cyclic dependency A <--> B where neither A nor B can be split up into smaller components, that gives you a striking argument for having A and B to be combined to single component (AB). As long as you argue that way, you obviously cannot come to a different conclusion.

Lets take a real-world example: Microsofts Scripting Runtime. This library contains components "File" and "Folder". Each File has a parent folder, and each Folder can contain a list of files. So we have indeed a cyclic dependency. Can those two components be split into smaller ones? I guess not without changing the whole semantics. Do they have behaviour? Of course, there are tight to objects in the file system which can be deleted, queried, tested for existence, moved, and so on. Should they be combined into one bigger component? Well, in some sense they are already, they are both part of the FileSystemObject part of the Scripting Runtime, and you cannot reference and use a File or Folder component alone. But now this boils down just to your point of view: on one level of abstraction, these two objects are different components on their own, on another they are not. And you can take this as proof of your hypothesis or a disproof, whatever you like.


答:
Contrary to whatsisname's answer, I do happen to think that information hiding attempts to not to make users of a class aware of its implementation and thus not make assumptions based on the current implementation, because ideally this could change without affecting user code. Given this, C++ is indeed bad at information hiding, because users of a class can see its private parts. (Pun not intentional, but noted.)

As so many things about C++, this is a sacrifice made to performance and backwards compatibility: In order to have stack-based objects, the compiler needs to know the size of those objects at compile-time. Given C's compilation model, this requires the information to be accessible through the class' definition.

You can work around that by either hiding implementations behind polymorphic base classes or by employing the pimple idiom. That will require additional runtime costs, but that's what it takes. Had C++ implemented full information hiding, you would pay for this all the time.

Title: Is declaring STL variables in a class definition too revealing?

Body:
If you are trying to hide implementation, would declaring STL variables be too revealing?  </p>

```<code>// in Word_Bucket.h
class Word_Bucket {
private:
    std::vector<std::string> contents;

    ...etc
}
</code>```

<p>... but then if you wrap it up, to hide the implementation, won't you have to reveal it in the wrapper's interface anyway?</p>

```<code>// in Word_Bucket.h
class Word_Bucket {
private:
    Bucket contents;

    ...etc
}

// in Bucket.h
class Bucket {
private:
    std::vector<template_stuff> contents;

    ...etc
}
</code>```


问:
How to Recover from Inconsistent Job State without Database Polling
I'm working on scaling an application which is currently polling a mySQL database to send async jobs to a background processing system.

A state machine is being used to keep track of the entities progress throughout a workflow. For example, we might have three states:

Scheduled

Processing

Complete

My plan is to add a messaging queue system to broker the jobs sent to the background processing system. So Application A would insert a new entity, then push a message to the queue. Application B would consume these messages and route them to the correct background processing job.

```<code>def do_work(entity)
  # Precondition check
  raise "Wrong State" unless entity.scheduled?

  # Update state to processing
  entity.processing

  # ... do work

  # Update state to complete
  entity.complete
end
</code>```

Given a job like above, I am having a hard time determining how it would be possible to recover from a situation where there was an error between the processing and complete event transitions. For example a process crash.

The job processor would re-try the job, but now the entity is in an inconsistent state, and would fail.

How could I handle this case without resulting back to polling the entity table looking for stale jobs?

Edit

There are two different concepts at play here. We have the data, and we have the state of the data as it relates to the job execution (scheduled/processing) + the state of the workflow (complete).

Both of these pieces of information are in the same table. So after data grows the process of polling becomes inefficient (reads/updates/inserts constantly happening).

So maybe a solution is to have Application B move active jobs into a separate datastore. So when the "clean up" task that @Ӎσᶎ refers to is running, the dataset should be much smaller.

Ultimately, there it seems like there is no way to avoid polling the database to ensure data is a correct state.

答:
I'm going to consider this more in the form of a risk management plan than a program design, because that's where the program design has to start.

It looks as though you have two communication channels - the database and a message queue. We'll assume the database is accurate, since if it fails it will normally require manual intervention. But everything else can fail, even in unlikely circumstances (fires!)

The normal flow seems to be:

```<code>process a:
     (1) create job
     (2) add to database
     (3) send message
process b:
     (4) message received
     (5) get job from database
     (6) process job
     (7) mark complete in database
</code>```

Possibly each of these steps can fail. "create job" might generate an invalid job (that can't be completed, say), or might fail to retrieve required information. So you'll probably want some kind of error reporting mechanism (no, really :)

Note that one of those might be resolvable by retrying (data not available), but the other will probably want an error detection mechanism - the "clean up" task. And the cleanup needs to categorise problems as fixable or not, ideally by having the code to fix them built in. That way its output is normal process flow and error reports, just like every other part of the program.

I suggest going through your code and at least mentally noting the hierarchy of error processing you already have, from "if this string can be turned into an integer do..." right up to "if there's an unhandled exception somewhere in the program". The "clean up" code is more closely aligned to this than it is to normal execution. It's akin to the heap checking code that programs like valgrind have - you run it periodically to make sure that your program state is correct.

One way or another you're going to end up with a thread or process somewhere that schedules jobs. Either right at the start (your question talks about scheduling jobs rather than just queuing them), or purely to run the clean up task. If the latter you might be able to run it as a separate executable via cron (I suggest under windows not getting involved with their equivalent, just my personal memory of it being a PITA to use programmatically. One of the parts of "clean up" is to make sure the scheduled task exists)

You might be able to reduce the frequency of the cleanup task by triggering it manually from the steps above when there are certain types of errors (ie, if processing a job takes longer than allowed abandon it and call clean up). If you can make it lightweight enough you might be able to get away with running it every time step 5 above runs, but I suggest not doing that even if you can initially. Or at least test it with several years worth of data in all your tables.

But regardless, I suggest running it at program start up then daily or so, just to catch things you haven't thought of yet. Like, what happens when your program gets shut down? How fast does it exit when the computer is shut down, and can it leave a job "paused" to be resumed or does it have time to reset the job to "ready to be run"? What if the database task to reset the job times out because the database is in the process of shutting down too?

(edit: moving data out of the "queue" table once it is processed will speed things up, and more so over time as the number of processed jobs grows. Depending on the amount of data and number of failures the clean up has to deal with it may be possible to add that to either the "get job" or "mark complete" steps. But that's for really simple jobs).

Body:
I'm going to consider this more in the form of a risk management plan than a program design, because that's where the program design has to start.

It looks as though you have two communication channels - the database and a message queue. We'll assume the database is accurate, since if it fails it will normally require manual intervention. But everything else can fail, even in unlikely circumstances (fires!)

The normal flow seems to be:

process a:
     (1) create job
     (2) add to database
     (3) send message
process b:
     (4) message received
     (5) get job from database
     (6) process job
     (7) mark complete in database

Possibly each of these steps can fail. "create job" might generate an invalid job (that can't be completed, say), or might fail to retrieve required information. So you'll probably want some kind of error reporting mechanism (no, really :)

Note that one of those might be resolvable by retrying (data not available), but the other will probably want an error detection mechanism - the "clean up" task. And the cleanup needs to categorise problems as fixable or not, ideally by having the code to fix them built in. That way its output is normal process flow and error reports, just like every other part of the program.

I suggest going through your code and at least mentally noting the hierarchy of error processing you already have, from "if this string can be turned into an integer do..." right up to "if there's an unhandled exception somewhere in the program". The "clean up" code is more closely aligned to this than it is to normal execution. It's akin to the heap checking code that programs like valgrind have - you run it periodically to make sure that your program state is correct.

One way or another you're going to end up with a thread or process somewhere that schedules jobs. Either right at the start (your question talks about scheduling jobs rather than just queuing them), or purely to run the clean up task. If the latter you might be able to run it as a separate executable via cron (I suggest under windows not getting involved with their equivalent, just my personal memory of it being a PITA to use programmatically. One of the parts of "clean up" is to make sure the scheduled task exists)

You might be able to reduce the frequency of the cleanup task by triggering it manually from the steps above when there are certain types of errors (ie, if processing a job takes longer than allowed abandon it and call clean up). If you can make it lightweight enough you might be able to get away with running it every time step 5 above runs, but I suggest not doing that even if you can initially. Or at least test it with several years worth of data in all your tables.

But regardless, I suggest running it at program start up then daily or so, just to catch things you haven't thought of yet. Like, what happens when your program gets shut down? How fast does it exit when the computer is shut down, and can it leave a job "paused" to be resumed or does it have time to reset the job to "ready to be run"? What if the database task to reset the job times out because the database is in the process of shutting down too?

(edit: moving data out of the "queue" table once it is processed will speed things up, and more so over time as the number of processed jobs grows. Depending on the amount of data and number of failures the clean up has to deal with it may be possible to add that to either the "get job" or "mark complete" steps. But that's for really simple jobs).


答:
If you really want to hide the details of your contents implementation, instead of declaring it as a Bucket, declare it as a Bucket*.  You can proceed as follows:

```<code>// in Word_Bucket.h
class Bucket; // simple forward declaration of the type allows to use a pointer to it

class Word_Bucket {
private:
    Bucket* contents;
}
</code>```

You'll have to use new and delete in the constructor and destructor of Word_Bucket but using this technique, only Word_Bucket.cpp needs to include Bucket.h.

Body:
If you really want to hide the details of your contents implementation, instead of declaring it as a Bucket, declare it as a Bucket*.  You can proceed as follows:

// in Word_Bucket.h
class Bucket; // simple forward declaration of the type allows to use a pointer to it

class Word_Bucket {
private:
    Bucket* contents;
}

You'll have to use new and delete in the constructor and destructor of Word_Bucket but using this technique, only Word_Bucket.cpp needs to include Bucket.h.


问:
Automated GUI tests take too long because of doing same steps before the "main test action" can proceed
We are developing a desktop application and I am responsible for GUI testing. Currently we have around 500 tests which take 8 hours to complete.

The tests are testing almost every button/menu/field etc. in the application. Some functions are taking 3 - 15 minutes because the application is actually measuring something, but most of the tests takes around 2 minutes.

The biggest problem I see is that a lot of tests are doing  same steps before the "main test action" can proceed, for instance start with import of documents to use for testing, which takes several seconds.

How to reduce this time?

Parallel testing or some fancy execution environment is probably not a solution or what I ask for. I am more interested in the design of the test or some tips for decreasing the repetition of work.

答:
One strategy I see used is to group your tests by duration.  Let's say you've got 300 tests.  100 of them run in 30 seconds or less.  100 of them run 30 seconds - 60 seconds, and 100 of them run longer than that (maybe do a little statistical analysis to break them into 3 or 4 groups).

If you structure your test execution process (for example, using tagging in Cucumber) so that they are grouped by how long they typically take, you can run your quick stuff maybe every day, your medium stuff every other day, and your long running stuff once a week.

It's not ideal, but "ideal" costs money (parallel processing against a large virtual grid for example), and not every shop can afford the expense.


问:
Name for use of methods that return rather than set
There exists a general OOP principle that methods should return local variables rather than set object fields.

For instance, say I have the following piece of code (example in Java):

```<code>public class Number {
    public int myNum;
}

public class Horrible {
    public static void areYouSerious(Number num){
        num.myNum = 47;
    }
}

public class Test {
    public int num = new Number();

    public void doHorribleThings(){
        Horrible.areYouSerious(num);
    }

    public static void main(String[] args){
        Test test = new Test();
        test.doHorribleThings();
    }
}
</code>```

Obviously this style of programming can go sideways very quickly, and becomes a massive headache for anyone attempting to maintain it. A more correct way of doing this would be the following:

```<code>public class Number {
    public int myNum;
}

public class NotAsBad {
    public static int getDefaultVal(){
        return 47;
    }
}

public class Test {
    public int num = new Number();

    public void doHorribleThings(){
        num.myNum = NotAsBad.getDefaultVal();
    }

    public static void main(String[] args){
        Test test = new Test();
        test.doHorribleThings();
    }
}
</code>```

The first example is modifying a passed in reference, whereas the second is generalizing the static setting function, making it return a value which can be used to set the object field.

Is there a name for the principle that the second method should be preferred over the first? A sort of "modularity" principle?

Just as encapsulation is the term for restricting variable manipulation, I would like a term for limiting the scope of the effects of some piece of functionality.

If there is no existing term, I am going to call it consequence localization.

答:
How about this instead?

```<code>public class Number
{
    private int startingValue;

    public Number(int value)
    {
        startingValue = Value;
    }
}

public static class EvenBetter
{
    public static int GetDefaultValue()
    {
        return 47;
    }
}

public static void Main(String[] args)
{
    int number = new Number(EvenBetter.GetDefaultValue());
}
</code>```

You can clarify it further by putting the static GetDefaultValue() method into the Number class, and then instantiate it thusly:

```<code>int number = new Number(Number.GetDefaultValue());
</code>```

or somesuch.

The reason that your first example is "bad" is that it is basically a "side-effect generator."  What you're trying to achieve (eventually) is Functional Programming with Immutability.  You do this by writing functions that accept some input and return some output without modifying the original input or causing other side-effects to occur.

For example: Map functions are not bad (even though they appear to produce side effects), because you always return a new collection, rather than modifying the collection in-place.

Body:
How about this instead?

public class Number
{
    private int startingValue;

    public Number(int value)
    {
        startingValue = Value;
    }
}

public static class EvenBetter
{
    public static int GetDefaultValue()
    {
        return 47;
    }
}

public static void Main(String[] args)
{
    int number = new Number(EvenBetter.GetDefaultValue());
}

You can clarify it further by putting the static GetDefaultValue() method into the Number class, and then instantiate it thusly:

int number = new Number(Number.GetDefaultValue());

or somesuch.

The reason that your first example is "bad" is that it is basically a "side-effect generator."  What you're trying to achieve (eventually) is Functional Programming with Immutability.  You do this by writing functions that accept some input and return some output without modifying the original input or causing other side-effects to occur.

For example: Map functions are not bad (even though they appear to produce side effects), because you always return a new collection, rather than modifying the collection in-place.


答:
method args should be pass by value or passed as immutable object references

That's what I read in some references materials under "encapsulation" topics. eg; java.lang.String. have'nt found any other term for it though.

Title: Name for use of methods that return rather than set

Body:
There exists a general OOP principle that methods should return local variables rather than set object fields.

For instance, say I have the following piece of code (example in Java):

```<code>public class Number {
    public int myNum;
}

public class Horrible {
    public static void areYouSerious(Number num){
        num.myNum = 47;
    }
}

public class Test {
    public int num = new Number();

    public void doHorribleThings(){
        Horrible.areYouSerious(num);
    }

    public static void main(String[] args){
        Test test = new Test();
        test.doHorribleThings();
    }
}
</code>```

Obviously this style of programming can go sideways very quickly, and becomes a massive headache for anyone attempting to maintain it. A more correct way of doing this would be the following:

```<code>public class Number {
    public int myNum;
}

public class NotAsBad {
    public static int getDefaultVal(){
        return 47;
    }
}

public class Test {
    public int num = new Number();

    public void doHorribleThings(){
        num.myNum = NotAsBad.getDefaultVal();
    }

    public static void main(String[] args){
        Test test = new Test();
        test.doHorribleThings();
    }
}
</code>```

The first example is modifying a passed in reference, whereas the second is generalizing the static setting function, making it return a value which can be used to set the object field.

Is there a name for the principle that the second method should be preferred over the first? A sort of "modularity" principle?

Just as encapsulation is the term for restricting variable manipulation, I would like a term for limiting the scope of the effects of some piece of functionality.

If there is no existing term, I am going to call it consequence localization.


问:
One Event Sent to Multiple Listeners, Want to Log Notification Once

I have a system in place where a Cache is made up of many Cache Nodes.  When one is added, a CacheNodeAdded event is raised by the Cache.  The Cache has a redundant set of Monitors listening for this event.  Monitors are responsible for notifying on Cache events.

Since I have multiple Monitors, but only want to be notified once, Step 3 is what I am looking to implement.

Solutions I can't use:

Cache notifying directly.  Monitors must be used.

Have each Monitor check the log to see if the notification has been sent.  Since they all run separately, they could all access the list of notifications at the same time, see the notification hasn't been sent, and notify multiple times as a result.

Solution I'm toying with:

When event is received, get a list of all Monitor IDs (GUID), order the list, and the first Monitor in the list gets to send the notification.  This is a simple solution but it seems a little inelegant.

Are there any other simple solutions that I may be overlooking?

答:
A write-lock can be acquired by the Monitor that has received the event over the log, do logging and set the logged flag to 'true' in the global logging context which all Monitors can look up and update has a reference of. Subsequent monitors may skip the logging step after reading the logged flag status.

Lookup of in memory context flag is expected less costly than that of the log itself.


问:
Design pattern for method to accept one of several static items in C#?
I want to illustrated my question by way of a (hopefully) representative example.

Lets say I have a situation where I am developing a class library in C# to be used in some simulations.  I want to define the planets (Earth, Mars, Saturn, etc.) and have each of them have some properties and methods that are common in interface (name, signature, etc.) but unique in implementation per-each. I.e. Earth.Mass is not equal to Mars.Mass.

So far no big deal.

I want to have some other classes/methods/algorithm that accept as an argument a planet and use its defined properties and method:

```<code>double MyApparentWeight(Planet someplanet, double MassInKG)
double DistanceFromInKM(Planet someplanet, Planet originplanet)
</code>```

Planets could be used all over the place by someone using this library.  All "Earth"s should be identical and all "Saturn"s should be identical.  Obviously the "Earth"s are distinct from the "Saturn"s.

I also want a user of the library to be able to easily create a new planet (e.g. Vulcan, Endor, Tralfamadore, Persephone, Rupert, etc.).  It should be forced to supply the properties and methods of the existing ones and hence be useable by the MyApparentWeight and DistanceFromInKM methods.

So the base level approach is that there is a Planet class and then the specific ones (Earth, Vulcan, etc.) simply inherit from that.  In this case though a user needs to either create an instance of Earth and carry it around or create a new one every time it is needed.  That could be unnecessarily clunky (especially in light of the expected users) and possibly a performance hit since some Planets could have initialization steps of reading date from files, etc.

The next idea was the above but with a singleton paradigm.  That's basically what I've done so far.  This seems to be dictating internal implementation to any new Planets that are created (and again some what of a concern given the potential level of some users).

This project is how I've been cutting my C#/.NET teeth.  My initial naive approach was to try to do static classes with interfaces or inheritance.  Obviously I learned quickly the folly of that path.  At a high level that is the kind of paradigm I would have wanted though.

Is there some other design pattern that I'm missing that could cover this type of situation?

Appreciate any suggestions.

Updates

I may not have made it clear that this Planet example was only meant to be illustrative structurally and not directly representative of the actual computations.  Some people seemed to get a little wrapped up in the implementations of what data is being represented within them and other peripheral aspects.

The suggestions of the individual planets (like Earth) merely being instances of the Planet class didn't catch my points about potentially significant different implementations for their internal mechanics supporting their methods and properties. I'm also at a loss as to how it helps with not wanting to manage carrying around those instances potentially anywhere you may want to use them or having to create new instances.

Glenn's extension of Stephen's suggestion I think actually works the best in the context of what I need here.  I can couple that with rsbarro's suggestion of having static properties for the built in Planet children.  (Actually more like interface IPlanet implementers).  That provides the easiest access for the users for the most commonly used items and offers a slight performance improvement of not having to retrieve from the dictionary by name each time.  It still offers the ability for the users to dynamically add more types of Planets.

I don't yet have the rep to up-vote all of the answers I mentioned above or I would.

Thank you all for your suggestions and feedback.

答:
You could make static properties on Planet for each of the specific planets you want to create.

For example:

```<code>public class Planet
{
    public string Name { get; set; }
    public double Mass { get; set; }

    private static Planet _earth;
    public static Planet Earth { get { return GetEarth(); } }

    //Use this approach so that you only create a planet if it is needed
    private static Planet GetEarth()
    {
         if(_earth == null)
              _earth = new Planet { Name = "Earth", Mass = 123.0 };
         return _earth;
    }
}
</code>```

This approach is similar to how the System.Drawing.Color class works. Take a look at that in ILSpy, specifically the named color properties like Aqua, White, etc.

OwnerDisplayName: kcc

Body:
You could make static properties on Planet for each of the specific planets you want to create.

For example:

public class Planet
{
    public string Name { get; set; }
    public double Mass { get; set; }

    private static Planet _earth;
    public static Planet Earth { get { return GetEarth(); } }

    //Use this approach so that you only create a planet if it is needed
    private static Planet GetEarth()
    {
         if(_earth == null)
              _earth = new Planet { Name = "Earth", Mass = 123.0 };
         return _earth;
    }
}

This approach is similar to how the System.Drawing.Color class works. Take a look at that in ILSpy, specifically the named color properties like Aqua, White, etc.


问:
Solutions to problems that .NET can solve better than Java (or vice-versa)
To me it seems these are two different platforms that address similar enterprise(but not only) problems. I'm interested however in problems that Java can solve better than C#/.NET or C#/.NET can solve better than Java. Leaving aside the 'cost' factor, since that is somehow not an issue for big enterprise companies (the developers probably cost more than the licenses from Microsoft - it's just a thought) and even for small projects there are free/open-source tools for .NET so the cost can be zero for the .NET world as well. With Mono, you can port .NET to Linux and MacOS as well so the benefit that Java had(cross platform) isn't THE decision factor to use Java nowadays..

What real world problems can you think of where .NET would be a much better solution than Java, and vice-versa? I'm only interested in solutions to problems.

答:
There are some language features in C# (4/5) such as LINQ, using predicate and some functional aspects that many would argue place it ahead of Java 6 in terms of productivity/flexibility (YMMV on that).  Others would argue that C# is becoming a big cesspit of every brand new idea that happens to be popular and it's getting harder to wield effectively (YMMV on that).

Some will also argue that the Java eco-system is far more flexible and that the JVM is probably the most capable and flexible runtime around (if you look at the various languages that run on the JVM adn their interoperability with Java).  Again YMMV.

What it really boils down to is the quality of the developer(s) who are designing and writing the code.  .NET and the Java eco-system are so close in capabilities that its usually the developer that makes a difference.

From a systems integration flexibility aspect, yes Java still has an edge there.  Cross platform is still an issue - many enterprises will see using Mono as risky (again YMMV here) and there are some systems that Mono won't run on that have JVMs (Some older big IBM machines for example).  Java has also been around a bit longer and has that established 'trust' in enterprises, it's not easy for .NET to gain that trust at say a mega-bank.

Meh - I conclude with no real conclusion, which I think mirrors the fact that Java and .NET are neck and neck these days.

ContentLicense: CC BY-SA 2.5


问:
Is it possible to have setup and tear down methods run only for specific unittests?
I currently have a test class with a setUp method for creating a temp file and a tearDown method for deleting a temp file.

However, only some of the the test_ methods in that class require this functionality.

Is possible to either ignore those 2 methods for the test cases which do not require it or to only call those 2 methods for test cases which do require it?

It feels a bit 'wrong' to call these 2 methods for every test even if the temp file is not getting used in each one.

答:
Martijn Pieters' solution of splitting tests by class does not always work for me because I split tests by criteria other than what setUp and tearDown they need.

So for this kind of situation I typically use a context manager like this:

```<code>import contextlib
@contextlib.contextmanager
def temp_dir():
    tmpdir = tempfile.mkdtemp(dir="whatever")
    try:
        yield tmpdir
    finally:
        shutil.rmtree(tmpdir)
</code>```

And then just use it where I need it:

```<code>def test_whatever(self):
    with temp_dir() as whatever:
        something_or_other()
</code>```

I create a temporary directory to stuff all of my temporary files into. This way the directory gets a random name but the files in it have constant names. I find it easier to manage if I need to perform diagnosis on the temporary files. I just need to get the name of the temporary directory instead of having to figure out the name of multiple files.

Body:
Martijn Pieters' solution of splitting tests by class does not always work for me because I split tests by criteria other than what setUp and tearDown they need.

So for this kind of situation I typically use a context manager like this:

import contextlib
@contextlib.contextmanager
def temp_dir():
    tmpdir = tempfile.mkdtemp(dir="whatever")
    try:
        yield tmpdir
    finally:
        shutil.rmtree(tmpdir)

And then just use it where I need it:

def test_whatever(self):
    with temp_dir() as whatever:
        something_or_other()

I create a temporary directory to stuff all of my temporary files into. This way the directory gets a random name but the files in it have constant names. I find it easier to manage if I need to perform diagnosis on the temporary files. I just need to get the name of the temporary directory instead of having to figure out the name of multiple files.


答:
I would have a generic planet class, with read-only properties that were set by constructor parameters.

```<code>class Planet
{
    public string Name { get; private set; }
    public double Mass { get; private set; }

    public Planet(string name, double mass)
    {
        this.Name = name;
        this.Mass = mass;
    }
}
</code>```

I would then have a PlanetFactory class for generating well known planets:

```<code>static class PlanetFactory
{
    public static Planet CreateEarth()
    {
        return new Planet("Earth", 597219000000000000000000);
    }

    public static CreateByName(string name)
    {
        if (name.Equals("Earth")) return CreateEarth();
    }
}
</code>```

I would then have a manager class to hold all of your planets:

```<code>class PlanetManager
{
    private Dictionary<string, Planet> planets;

    public GetPlanet(string name)
    {
        if (!planets.ContainsKey(name))
        {
            planets.add(name, PlanetFactory.CreateByName(name));
        }

        return planets[name];
    }
}
</code>```

This approach means that you can easily add new well-known planets and provide a mechanism for adding new planets through the PlanetManager class (though you would need a different method to do so).

Title: Design pattern for method to accept one of several static items in C#?

Body:
I want to illustrated my question by way of a (hopefully) representative example.

Lets say I have a situation where I am developing a class library in C# to be used in some simulations.  I want to define the planets (Earth, Mars, Saturn, etc.) and have each of them have some properties and methods that are common in interface (name, signature, etc.) but unique in implementation per-each. I.e. Earth.Mass is not equal to Mars.Mass.

So far no big deal.

I want to have some other classes/methods/algorithm that accept as an argument a planet and use its defined properties and method:

```<code>double MyApparentWeight(Planet someplanet, double MassInKG)
double DistanceFromInKM(Planet someplanet, Planet originplanet)
</code>```

Planets could be used all over the place by someone using this library.  All "Earth"s should be identical and all "Saturn"s should be identical.  Obviously the "Earth"s are distinct from the "Saturn"s.

I also want a user of the library to be able to easily create a new planet (e.g. Vulcan, Endor, Tralfamadore, Persephone, Rupert, etc.).  It should be forced to supply the properties and methods of the existing ones and hence be useable by the MyApparentWeight and DistanceFromInKM methods.

So the base level approach is that there is a Planet class and then the specific ones (Earth, Vulcan, etc.) simply inherit from that.  In this case though a user needs to either create an instance of Earth and carry it around or create a new one every time it is needed.  That could be unnecessarily clunky (especially in light of the expected users) and possibly a performance hit since some Planets could have initialization steps of reading date from files, etc.

The next idea was the above but with a singleton paradigm.  That's basically what I've done so far.  This seems to be dictating internal implementation to any new Planets that are created (and again some what of a concern given the potential level of some users).

This project is how I've been cutting my C#/.NET teeth.  My initial naive approach was to try to do static classes with interfaces or inheritance.  Obviously I learned quickly the folly of that path.  At a high level that is the kind of paradigm I would have wanted though.

Is there some other design pattern that I'm missing that could cover this type of situation?

Appreciate any suggestions.

Updates

I may not have made it clear that this Planet example was only meant to be illustrative structurally and not directly representative of the actual computations.  Some people seemed to get a little wrapped up in the implementations of what data is being represented within them and other peripheral aspects.

The suggestions of the individual planets (like Earth) merely being instances of the Planet class didn't catch my points about potentially significant different implementations for their internal mechanics supporting their methods and properties. I'm also at a loss as to how it helps with not wanting to manage carrying around those instances potentially anywhere you may want to use them or having to create new instances.

Glenn's extension of Stephen's suggestion I think actually works the best in the context of what I need here.  I can couple that with rsbarro's suggestion of having static properties for the built in Planet children.  (Actually more like interface IPlanet implementers).  That provides the easiest access for the users for the most commonly used items and offers a slight performance improvement of not having to retrieve from the dictionary by name each time.  It still offers the ability for the users to dynamically add more types of Planets.

I don't yet have the rep to up-vote all of the answers I mentioned above or I would.

Thank you all for your suggestions and feedback.

Body:
I would have a generic planet class, with read-only properties that were set by constructor parameters.

class Planet
{
    public string Name { get; private set; }
    public double Mass { get; private set; }

    public Planet(string name, double mass)
    {
        this.Name = name;
        this.Mass = mass;
    }
}

I would then have a PlanetFactory class for generating well known planets:

static class PlanetFactory
{
    public static Planet CreateEarth()
    {
        return new Planet("Earth", 597219000000000000000000);
    }

    public static CreateByName(string name)
    {
        if (name.Equals("Earth")) return CreateEarth();
    }
}

I would then have a manager class to hold all of your planets:

class PlanetManager
{
    private Dictionary<string, Planet> planets;

    public GetPlanet(string name)
    {
        if (!planets.ContainsKey(name))
        {
            planets.add(name, PlanetFactory.CreateByName(name));
        }

        return planets[name];
    }
}

This approach means that you can easily add new well-known planets and provide a mechanism for adding new planets through the PlanetManager class (though you would need a different method to do so).


答:
I would use a solution similiar to Stephens, in that it involves a dictionary and PlanetManager is static.

This example assumes that you already have a base Planet type and subclasses of Planet (such as Earth) for different planets. This would also work for planetary implementations without subclassing (as in all planets are instances of Planet and not a derived class). If you are extending Planet to create all of your planets, I recommend making Planet abstract so that it must be extended to create instances.

```<code>public static class PlanetManager
{
    static PlanetManager()
    {
        // Initialize the planets dictionary in a static constructor
        _planets = new Dictionary<string, Planet>();
        // Add existing planets to the dictionary using the appropriate constructor
        _planets.Add("earth", new Earth());
    }

    private static Dictionary<string, Planet> _planets;

    public static void AddPlanet(string name, Planet planet)
    {
        if(name == null)
        {
            throw new ArgumentNullException("name");
        }

        if(planet == null)
        {
            throw new ArgumentNullException("planet");
        }

        if(_planets.ContainsKey(name.ToLower()))
        {
            // Only one planet per name
            throw new InvalidOperationException("That planet already exists.");
        }

        // Add the planet to the dictionary
        _planets[name.ToLower()] = planet;
    }

    public static Planet GetPlanet(string name)
    {
        if(name == null)
        {
            // Null checks
            throw new ArgumentNullException("name");
        }

        // Case-insensitive planet matching that lets exceptions fall through to caller
        return _planets[name.ToLower()];
    }
}
</code>```

This implementation is not thread safe.

Body:
I would use a solution similiar to Stephens, in that it involves a dictionary and PlanetManager is static.

This example assumes that you already have a base Planet type and subclasses of Planet (such as Earth) for different planets. This would also work for planetary implementations without subclassing (as in all planets are instances of Planet and not a derived class). If you are extending Planet to create all of your planets, I recommend making Planet abstract so that it must be extended to create instances.

public static class PlanetManager
{
    static PlanetManager()
    {
        // Initialize the planets dictionary in a static constructor
        _planets = new Dictionary<string, Planet>();
        // Add existing planets to the dictionary using the appropriate constructor
        _planets.Add("earth", new Earth());
    }

    private static Dictionary<string, Planet> _planets;

    public static void AddPlanet(string name, Planet planet)
    {
        if(name == null)
        {
            throw new ArgumentNullException("name");
        }

        if(planet == null)
        {
            throw new ArgumentNullException("planet");
        }

        if(_planets.ContainsKey(name.ToLower()))
        {
            // Only one planet per name
            throw new InvalidOperationException("That planet already exists.");
        }

        // Add the planet to the dictionary
        _planets[name.ToLower()] = planet;
    }

    public static Planet GetPlanet(string name)
    {
        if(name == null)
        {
            // Null checks
            throw new ArgumentNullException("name");
        }

        // Case-insensitive planet matching that lets exceptions fall through to caller
        return _planets[name.ToLower()];
    }
}

This implementation is not thread safe.


问:
Why are inheritance and interfaces restricted to instance members?
Disclaimer: I think the rules are almost the same in most OO languages, but since I'm most familiar with C# I'll be relating to this specific language.

I think that the use of attributes and reflection could be largely reduced if static members would apply the same principles as OO instances.

Static properties and methods can be "overridden" by decedents by using the new keyword, but they cannot be forced to implement one via an interface, neither can the 'base' keyword be used (only explicitly naming the base type is supported). To make things worse, the members cannot be referenced via an instance, but have to always be specifically qualified with the exact type.

Constructors also have limited "inheritance" support, one can choose which base constructor is called, but you cannot force an object to support a constructor that takes certain parameters by defining it in an interface.

The best hint I could find to answer this question so far is this one on stack overflow (answering a different question).

In his answer Jörg points out three principals that apply to Object Orientation:

messaging,

local retention and protection and hiding of state-process, and

extreme late-binding of all things.

Now I fully understand that if you want to pass on a state-full class from one method to another as an object, these principles make sense. However in my opinion the principle of inheritance, overriding base methods with alternative or additional functionality, could also be beneficial to stateless business logic.

One example where forcing an object to implement a certain constructor would be helpful is with de-serialization. For example where the constructor should accept an XML node. In C# it is dynamically implementable using reflection, but having compile-time errors and avoiding the reflection boilerplate would add lots of value!

Static method/member interfaces would be helpful in situations where some aspects of a value are type specific, without any relation to the instance. For example a class could have a DisplayName, Unit, Weight, Factor or other aspects that are the same across all instances of the specific type, regardless of the instance value. Attributes (or Annotation) can be used to exploit these without the need to create an instance, however, there again it's extra boilerplate code and no way to enforce their implementation with compile-time errors.

I admit there are many simple ways to work around these points, I'm not looking for workarounds. Returning a static value in an instance-property is quite common, and it is not that much overhead to create an instance of an object just to read out the type-specific aspects, but I'd like to know the rationale background on why static things have been systematically excluded. I have heard about "the virtual stack" before, but don't really know how it works technically (and cannot find any simple explanation on the net).

Are the reasons of technical or philosophical nature?

Edit: elaborating on static interfaces:

An example of how I think a static interface could provide a strongly typed, compiletime checked, alternative to reflection:

```<code>public staticInterface MyStaticInterface
{
    constructor(XmlNode node);
    string DisplayName { get; }
    int Weight { get; }
}
</code>```

The usage:

```<code>public void FillNodesToolBox()
{
    MyStaticInterface[] nodes =
        assembly.GetTypes().Where(t => t.Implements<MyStaticInterface>());

    for (int i = nodes.Length - 1; i >= 0 ; i--)
    {
        Console.WriteLine(string.Concat(
            nodes[i].DisplayName, " (", nodes[i].Weight.ToString(), ")"));
    }
}
</code>```

Looking back, this actually looks like making my Type object inherit from System.Type, adding some properties to it, which is different than a static member...

string.Empty != typeof(string).Emty (the latter will not compile).

Maybe I'm starting to find the answer, but it feels like I'm walking in a paradoxical circle, it doesn't quite 'snap' yet....

答:
Constructors also have limited "inheritance" support, one can choose which base constructor is called, but you cannot force an object to support a constructor that takes certain parameters by defining it in an interface.

An interface by definition has no knowledge of its underlying type. Technically there doesn't even need to be an underlying type; an interface is simply a collection of functions. Although mainstream OOP languages have a built-in mechanism for interfaces and expect you to "attach" them to classes, you could just as well take a bunch of delegates/lambdas/functions with known signatures into some container type and that'd be an interface too.

One example where forcing an object to implement a certain constructor would be helpful is with de-serialization. For example where the constructor should accept an XML node.

In my opinion this is a bad idea. What happens when you want to serialize/deserialize the class in a different way? Or multiple ways at once? A class should have only one reason to change, and knowing how to serialize itself gives it a second reason. Granted, serialization is an interesting case because it requires breaking encapsulation, but I still feel it's best handled externally.

Static method/member interfaces would be helpful in situations where some aspects of a value are type specific, without any relation to the instance. For example a class could have a DisplayName, Unit, Weight, Factor or other aspects that are the same across all instances of the specific type, regardless of the instance value.

A static field points to precisely one thing by definition; that's why it's not tied to any one instance of a class. Something can't be static and overridable at the same time. Think about what overriding something means; you'd have something that knows how to locate the field you're trying to access. That would make whatever you're trying to get an instance field. It might not be an instance field of the instances of the class, but you'd be turning the class itself into an object.

As a final note, inheritance is already a problematic mechanism. It's not inherently composable since you can only inherit from one thing at a time (otherwise you open up a different can of worms) and if you don't put restrictions on what can be overridden, changes to the base class that would be safe when considered in isolation can break subclasses. Being able to override static fields would be of very dubious value.


答:
You are, for whatever reason, hard-coding data into your program.  This is itself a code smell (what do you do when mars suffers a catastrophic collision and losses 5% if it's mass?), but sometimes real code is smelly and there are some ways to do this which are better than others.

Since in our example we want to allow downstream programmers to create their own planet instances, we'll want a non-static Planet class or struct.  And, since there are some real-life planets as well, some form of static method to populate that class would be appropriate.  You could make a new sub-class for each standard planet, or you could make a distinct static method for each planet, but I think both patterns introduce too much complexity.

A simple single static  'static IPlanet GetPlanet(string name)' should suffice for interface's sake, and hard-coding the values wrapped inside some control structure is more than complexity enough.  If an eight or nine branch method seems too complex for you, you can always go the clean route and just include an XML file with the data in your assembly.

Of course, if your "planets" really had different methods and internal behaviors, different classes would be appropriate.... but a single 'GetPlanet' method would still be a fair way to select between them.


问:
Tablet development for a dedicated system
I need to make an architectural decision for developing (actually porting) my embedded solution on a tablet.

The choice comes down to Ubuntu or Android, so I have some specific questions to help me decide.

On Android, is it possible to develop applications outside of Dalvik, using Python? If yes, can I access the hardware this way, without the API's provided by the Android SDK?

On Android, can I control the process' core_affinity to bind a process to a single core? And can i use isolcpus to isolate other processes from that core making it a (almost) dedicated core for a process? This is possible in regular linux, not sure if it can be done in Android.

On Ubuntu, how much control over the HW do I have outside Ubuntu SDK?

答: If the device in question is a custom or generic tablet on a conventional platform (x86, ARM...), then ask yourself what do you need exactly from it. Do you really need a whole Ubuntu distribution, or will the tablet boot directly into your application? In that case I would go for a basic embedded linux distribution that will take care of your hardware and a QT interface. If the device is running Android then you need to use the appropriate toolkit and API for Android OS. You could also go with a full blown Ubuntu and just develop a web app. In that case all you need is a web browser and you can run it on virtually any tablet, phone, or PC. </p>