答:
A lot of people think that unit testing is method-based; it's not. It should be based around the smallest unit that makes sense. For most things this means the class is what you should be testing as a whole entity. Not individual methods on it.

Now obviously you will be calling methods on the class, but you should be thinking of the tests as applying to the black box object you have, so you should be able to see that whatever logical operations your class provides; these are the things you need to test. If your class is so large that the logical operation is too complex, then you have a design issue that should be fixed first.

A class with a thousand methods may appear testable, but if you only test each method individually you're not really testing the class. Some classes might require to be in a certain state before a method is called, for example a network class that needs a connection set up before sending data. The send data method cannot be considered independently of the whole class.

So you should see that private methods are irrelevant to the testing. If you cannot exercise your private methods by calling the public interface of your class, then those private methods are useless and are not going to be used anyway.

I think many people try to turn private methods into testable units because it appears easy to run tests for them, but this takes the test granularity too far. Martin Fowler says

Although I start with the notion of the unit being a class, I often
  take a bunch of closely related classes and treat them as a single
  unit

which makes a lot of sense for an object-oriented system, objects being designed to be units. If you want to test individual methods, perhaps you should be creating a procedural system like C, or a class comprised entirely of static functions instead.

Title: TDD Red-Green-Refactor and if/how to test methods that become private

Body:
as far as I understand it, most people seem to agree that private methods should not be tested directly, but rather through whatever public methods call them. I can see their point, but I have some problems with this when I try to follow the "Three Laws of TDD", and use the "Red - green - refactor" cycle. I think it's best explained by an example:

Right now, I need a program that can read a file (containing tab-separated data) and filter out all columns that contain non-numerical data. I guess there's probably some simple tools available already to do this, but I decided to implement it from scratch myself, mostly because I figured it could be a nice and clean project for me to get some practice with TDD.

So, first, I "put the red hat on", that is, I need a test that fails. I figured, I'll need a method that finds all the non-numerical fields in a line. So I write a simple test, of course it fails to compile immediately, so I start writing the function itself, and after a couple of cycles back and forth (red/green) I have a working function and a complete test.

Next, I continue with a function, "gatherNonNumericColumns" that reads the file, one line at a time, and calls my "findNonNumericFields"-function on each line to gather up all the columns that eventually must be removed. A couple of red-green-cycles, and I'm done, having again, a working function and a complete test.

Now, I figure I should refactor. Since my method "findNonNumericFields" was designed only because I figured I would need it when implementing "gatherNonNumericColumns", it seems to me that it would be reasonable to let "findNonNumericFields" become private. However, that would break my first tests, since they would no longer have access to the method they were testing.

So, I end up with a private methods, and a suite of test that test it. Since so many people advice that private methods should not be tested, it feels like I've painted myself into a corner here. But where exactly did I fail?

I gather I could have started out at a higher level, writing a test that tests what will eventually become my public method (that is, findAndFilterOutAllNonNumericalColumns), but that feels somewhat counter to the whole point of TDD (at least according to Uncle Bob): That you should switch constantly between writing tests and production code, and that at any point in time, all your tests worked within the last minute or so. Because if I start out by writing a test for a public method, there will be several minutes (or hours, or even days in very complex cases) before I get all the details in the private methods to work so that the test testing the public method passes.

So, what to do? Is TDD (with the rapid red-green-refactor cycle) simply not compatible with private methods? Or is there a fault in my design?


问:
TDD Red-Green-Refactor and if/how to test methods that become private
as far as I understand it, most people seem to agree that private methods should not be tested directly, but rather through whatever public methods call them. I can see their point, but I have some problems with this when I try to follow the "Three Laws of TDD", and use the "Red - green - refactor" cycle. I think it's best explained by an example:

Right now, I need a program that can read a file (containing tab-separated data) and filter out all columns that contain non-numerical data. I guess there's probably some simple tools available already to do this, but I decided to implement it from scratch myself, mostly because I figured it could be a nice and clean project for me to get some practice with TDD.

So, first, I "put the red hat on", that is, I need a test that fails. I figured, I'll need a method that finds all the non-numerical fields in a line. So I write a simple test, of course it fails to compile immediately, so I start writing the function itself, and after a couple of cycles back and forth (red/green) I have a working function and a complete test.

Next, I continue with a function, "gatherNonNumericColumns" that reads the file, one line at a time, and calls my "findNonNumericFields"-function on each line to gather up all the columns that eventually must be removed. A couple of red-green-cycles, and I'm done, having again, a working function and a complete test.

Now, I figure I should refactor. Since my method "findNonNumericFields" was designed only because I figured I would need it when implementing "gatherNonNumericColumns", it seems to me that it would be reasonable to let "findNonNumericFields" become private. However, that would break my first tests, since they would no longer have access to the method they were testing.

So, I end up with a private methods, and a suite of test that test it. Since so many people advice that private methods should not be tested, it feels like I've painted myself into a corner here. But where exactly did I fail?

I gather I could have started out at a higher level, writing a test that tests what will eventually become my public method (that is, findAndFilterOutAllNonNumericalColumns), but that feels somewhat counter to the whole point of TDD (at least according to Uncle Bob): That you should switch constantly between writing tests and production code, and that at any point in time, all your tests worked within the last minute or so. Because if I start out by writing a test for a public method, there will be several minutes (or hours, or even days in very complex cases) before I get all the details in the private methods to work so that the test testing the public method passes.

So, what to do? Is TDD (with the rapid red-green-refactor cycle) simply not compatible with private methods? Or is there a fault in my design?

答:
Personally, I feel you went to far into the implementation mindset when you wrote the tests. You assumed you would need certain methods. But do you really need them to do what the class is supposed to do? Would the class fail if someone came along and refactored them internally? If you were using the class (and that should be the mindset of the tester in my opinion), you could really care less if there is an explicit method to check for numbers.

You should test the public interface of a class. The private implementation is private for a reason. It's not part of the public interface because it's not needed and can change. It's an implementation detail.

If you write tests against the public interface, you will never actually get the problem you ran into. Either you can create test cases for the public interface that cover your private methods (great) or you cannot. In that case, it might be time to think hard about the private methods and maybe scrap them alltogether if they cannot be reached anyway.

ContentLicense: CC BY-SA 3.0


问:
How to share memory between applications written in C/C++
I'm going through a program written in C/C++ for control in robotics. Basically, three different programs run at the same time, and they communicate via shared memory. Google-ling around I found thinks like vxWorks and the boost libraries interprocess headers (Boost documentation: Sharing memory between processes). </p>

<p>Now, I don't want to look at the implementation, I can read the link above. But I cannot get my head around to how the boost library does this. I mean, one application allocates memory, and other access that memory, but how do they communicate? isn't it unsafe to do this? </p>

答:
Notice that C and C++ are different languages.

Shared memory is impossible in purely standard C11, or C++11 (since the standard does not define that), or even C++14 (whose n3690 draft, and presumably official standard, does not mention shared memory outside of multi-threading). So you need extra libraries to get shared memory. But some operating systems have support for shared memory. So several libraries providing shared memory, built above existing operating system services, exist. You could perhaps consider using the POCO framework library (which abstracts over OS specific details)

For Linux (and perhaps POSIX), look into shm_overview(7). You'll need to synchronize, so see also sem_overview(7)

VXWorks (which I don't know, but googled for it) has VxMP

You need to carefully understand what is really happening. You probably want to share only plain old data struct-s (not C++ classes!) and you should be very careful about the addresses (each process might get different address for the common shared memory segment) and about synchronization.

Alternatively, use threads. Notice that C++11 standard defines a thread library.


答:
shared memory is not the complete picture for IPC, its a data-passing mechanism but you still need some way to inform the other process that some data has been updated and is available to be read. How you do this is up to you, typically you'd use an OS mutex or event object, each process waits on this to be set, the application writing sets it once its finished writing. Then threads in the other programs wake up and read.

Alternatively you can poll, read the data regularly for a value that changes when the data is updated (eg a incrementing counter).

Title: How to share memory between applications written in C/C++

Body:
I'm going through a program written in C/C++ for control in robotics. Basically, three different programs run at the same time, and they communicate via shared memory. Google-ling around I found thinks like vxWorks and the boost libraries interprocess headers (Boost documentation: Sharing memory between processes). </p>

<p>Now, I don't want to look at the implementation, I can read the link above. But I cannot get my head around to how the boost library does this. I mean, one application allocates memory, and other access that memory, but how do they communicate? isn't it unsafe to do this? </p>


答:
Shared memory is still just memory. You can put a mutex, spinlock or any other synchronization primitive in there, and use them to synchronize your processes' access to the shared memory, exactly like threads use those primitives to synchronize access to the memory visible to them.

The only real differences are:

threads share all memory and the same address space, so raw pointers work for them. Memory shared between processes works exactly the same, but may be mapped at different addresses in each process, so you can't simply pass raw pointers between them

NB. this has a knock-on effect on some implementation details of virtual methods, runtime type information, and some other C++ mechanisms. Stick to trivially-initializable (plain old data) types with no virtual methods or dynamic casts in your shared memory, don't use typeid on them, and you should be fine.

some synchronization primitives may need special flags or attributes to work correctly between processes (see the PTHREAD_PROCESS_SHARED attribute for POSIX thread mutexes, for example). This isn't really to do with the memory and synchronization in themselves, but due to the kernel/scheduler interaction needed to wake up sleeping waiters.

So:

but how do they communicate?

The same way different threads communicate, allowing for the caveats above

isn't it unsafe to do this?

Yes, it's exactly as unsafe for processes to communicate via shared memory as it is for threads to communicate via shared memory, and they need equivalent (or identical) synchronization to make it safe.


答:
Boost uses memory mapping of a file.

Both unix and windows support creation of files that don't exist on the normal file system for just this purpose.

Then you will need to synchronize access to that memory like you would if different threads were to access it. Meaning concurrent reads can happen without synchronization but as soon as one process want to write you will need to prevent the others from accessing it.

Atomic operations on the shared memory is still possible if you want a lockless synchronization.


问:
Why do many exception messages not contain useful details?
It seems there is a certain amount of agreement that exception messages should contain useful details.

Why is it that many common exceptions from system components do not contain useful details?

A few examples:

.NET List index access ArgumentOutOfRangeException does not tell me the index value that was tried and was invalid, nor does it tell me the allowed range.

Basically all exception messages from the MSVC C++ standard library are utterly useless (in the same vein as above).

Oracle exceptions in .NET, telling you (paraphrased) "TABLE OR VIEW not found", but not which one.

So, to me it seems that for the most part exception messages do not contain sufficient details to be useful. Are my expectations out of line? Am I using exceptions wrong that I even notice this? Or maybe my impression is wrong: a majority of exceptions do actually provide useful details?

答:
What makes you think the index value or the required range or the name of the table is a useful detail, for an exception?

Exceptions aren't an error handling mechanism; they are a recovery mechanism.

The point of exceptions is to bubble up to the level of code that can handle the exception. Wherever that level is, either you have the information needed, or it is not relevant. If there is information you need, but don't have immediate access to, you are not handling the exception at the appropriate level.

The one time I can think of where extra information could be helpful is at the absolute top level of your application where you crash and emit an error dump; but it is not the job of the exception to access, compile and store this information.

I'm not saying that you can just put "throw new Exception" everywhere and call it good, it is possible to write bad exceptions. But including irrelevant information is not nessecary to use them properly.

ContentLicense: CC BY-SA 4.0


问:
Designing exception classes
I'm coding a small library and I'm having some trouble with designing the exception handling. I must say that I am (still) confused by this feature of the C++ language and I tried to read as much as possible on the subject to come to an understanding of what would I have to do to properly work with exception classes.

I decided to use a system_error type of approach taking inspiration from the STL implementation of the future_error class.

I have an enumeration containing the error codes:

```<code>enum class my_errc : int
{
    error_x = 100,
    error_z = 101,
    error_y = 102
};
</code>```

and a single exception class (backed up by an error_category type of structures and everything else needed by the system_error model):

```<code>// error category implementation
class my_error_category_impl : public std::error_category
{
    const char* name () const noexcept override
    {
        return "my_lib";
    }

    std::string  message (int ec) const override
    {
        std::string msg;
        switch (my_errc(ec))
        {
        case my_errc::error_x:
            msg = "Failed 1.";
            break;
        case my_errc::error_z:
            msg = "Failed 2.";
            break;
        case my_errc::error_y:
            msg = "Failed 3.";
            break;
        default:
            msg = "unknown.";
        }

        return msg;
    }

    std::error_condition default_error_condition (int ec) const noexcept override
    {
        return std::error_condition(ec, *this);
    }
};

// unique instance of the error category
struct my_category
{
    static const std::error_category& instance () noexcept
    {
        static my_error_category_impl category;
        return category;
    }
};

// overload for error code creation
inline std::error_code make_error_code (my_errc ec) noexcept
{
    return std::error_code(static_cast<int>(ec), my_category::instance());
}

// overload for error condition creation
inline std::error_condition make_error_condition (my_errc ec) noexcept
{
    return std::error_condition(static_cast<int>(ec), my_category::instance());
}

/**
 * Exception type thrown by the lib.
 */
class my_error : public virtual std::runtime_error
{
public:
    explicit my_error (my_errc ec) noexcept :
        std::runtime_error("my_namespace ")
        , internal_code(make_error_code(ec))
    { }

    const char* what () const noexcept override
    {
        return internal_code.message().c_str();
    }

    std::error_code code () const noexcept
    {
        return internal_code;
    }

private:
    std::error_code internal_code;
};

// specialization for error code enumerations
// must be done in the std namespace

    namespace std
    {
    template <>
    struct is_error_code_enum<my_errc> : public true_type { };
    }
</code>```

I only have a small number of situations in which I throw exceptions illustrated by the error code enumeration.

The above did not sit well with one of my reviewers. He was of the opinion that I should have created a hierarchy of exception classes with a base class derived from std::runtime_error because having the error code embedded in the condition mixes things - exceptions and error codes - and it would be more tedious to deal with a the point of handling; the exception hierarchy would also allow for easy customization of the error message.

One of my arguments was that I wanted to keep it simple, that my library did not need to throw multiple types of exceptions and that the customization is also easy in this case as it is handled automatically - the error_code has an error_category associated with it that translates the code to the proper error message.

I have to say that I did not defend well my choice, testament to the fact that I still have some misunderstandings regarding C++ exceptions.

I would like to know if my design makes sense. What would be the advantages of the other method over the one I chose as I have to admit I fail to see that also? What could I do to improve?

答:
I think your colleague was right: you are designing your exception cases based on how simple it is to implement within the hierarchy, not based on the exception-handling needs of the client code.

With one exception type and an enumeration for the error condition (your solution), if the client code needs to handle single error cases (for example, my_errc::error_x) they must write code like this:

```<code>try {
    your_library.exception_thowing_function();
} catch(const my_error& err) {
    switch(err.code()) { // this could also be an if
    case my_errc::error_x:
        // handle error here
        break;
    default:
        throw; // we are not interested in other errors
    }
}
</code>```

With multiple exception types (having a common base for the entire hierarchy), you can write:

```<code>try {
    your_library.exception_thowing_function();
} catch(const my_error_x& err) {
    // handle error here
}
</code>```

where exception classes look like this:

```<code>// base class for all exceptions in your library
class my_error: public std::runtime_error { ... };

// error x: corresponding to my_errc::error_x condition in your code
class my_error_x: public my_error { ... };
</code>```

When writing a library, the focus should be on it's ease of use, not (necessarily) ease of the internal implementation.

You should only compromize the ease of use (how client code will look like) when the effort of doing it right in the library, is prohibitive.

OwnerDisplayName: celavek

Title: Designing exception classes

Body:
I think your colleague was right: you are designing your exception cases based on how simple it is to implement within the hierarchy, not based on the exception-handling needs of the client code.

With one exception type and an enumeration for the error condition (your solution), if the client code needs to handle single error cases (for example, my_errc::error_x) they must write code like this:

try {
    your_library.exception_thowing_function();
} catch(const my_error& err) {
    switch(err.code()) { // this could also be an if
    case my_errc::error_x:
        // handle error here
        break;
    default:
        throw; // we are not interested in other errors
    }
}

With multiple exception types (having a common base for the entire hierarchy), you can write:

try {
    your_library.exception_thowing_function();
} catch(const my_error_x& err) {
    // handle error here
}

where exception classes look like this:

// base class for all exceptions in your library
class my_error: public std::runtime_error { ... };

// error x: corresponding to my_errc::error_x condition in your code
class my_error_x: public my_error { ... };

When writing a library, the focus should be on it's ease of use, not (necessarily) ease of the internal implementation.

You should only compromize the ease of use (how client code will look like) when the effort of doing it right in the library, is prohibitive.

OwnerDisplayName: utnapistim


答:
But I cannot get my head around to how the boost library does this.

The boost interprocess mechanism has three necessary components to work:

memory-mapped file: a memory-mapped file needs to be created and passed to a boost.interprocess allocator. This allocator will take chunks of the file and use them as if they were returned by a std::allocator, with mapping applied so that the memory is compatible to in-process specific memory.

boost.interprocess container; this kind of container will use the memory returned by the allocator and offer a std::container like interface (begin/end/size/push_back, etc).

synchronization mechanism; this can be any interprocess mutex and should be used to prevent data access race conditions.

I mean, one application allocates memory, and other access that memory, but how do they communicate? isn't it unsafe to do this?

The allocated memory is actually a shared memory-mapped file
The communication is indirect, with both applications setting or reading the data, as they need.
The safety comes from using interprocess synchronization primitives.


问:
performance versus reusability
How can I write functions that are reusable without sacrificing performance? I am repeatedly coming up against the situation where I want to write a function in a way that makes it reusable (e.g. it makes no assumptions about the data environment) but knowing the overall flow of the program I know it isn't the most efficent method. For example if I want to write a function that validates a stock code but is reusable I can't just assume that the recordset is open. However if I open and close the recordset everytime the function is called then the performance hit when looping through thousands of rows could be huge.

So for performance I might have:

```<code>Function IsValidStockRef(strStockRef, rstStockRecords)
    rstStockRecords.Find ("stockref='" & strStockRef & "'")
    IsValidStockRef = Not rstStockRecords.EOF
End Function
</code>```

But for reusability I would need something like the following:

```<code>Function IsValidStockRef(strStockRef)
    Dim rstStockRecords As ADODB.Recordset

    Set rstStockRecords = New ADODB.Recordset
    rstStockRecords.Open strTable, gconnADO

    rstStockRecords.Find ("stockref='" & strStockRef & "'")
    IsValidStockRef = Not rstStockRecords.EOF

    rstStockRecords.Close
    Set rstStockRecords = Nothing
End Function
</code>```

I'm concerned that the impact on performance of opening and closing that recordset when called from within a loop over thousands of rows/records would be severe but using the first method makes the function less reusable.

What should I do?

答:
You should do whatever yields the greater business value in this situation.

Writing software is always a trade-off. Almost never are all valid goals (maintainability, performance, clarity, conciseness, security etc. etc.) completely aligned. Do not fall into the trap of those short-sighted people who consider one of these dimensions as paramount and tell you to sacrifice everything to it.

Instead, understand what risks and what benefits each alternative offers, quantize them and go with the one that maximizes the outcome. (You don't have to actually make numerical estimates, of course. It's enough to weigh factors such as "using this class means locking us into that hash algorithm, but since we're not using it to guard against malicious attack, only for convenience, this one is good enough that we can just ignore the 1:1,000,000,000 chance of an accidental collision".)

The most important thing is to remember that they are trade-offs; no single principle justifies everything to satisfy, and no decision, once taken, need stand eternally. You may always have to revise in hindsight when circumstances change in a way you didn't foresee. That's a pain, but not nearly as painful as making the same decision without hindsight.

Title: performance versus reusability


问:
using node.js server with mysql-module and PHP for a penny-auction website?
I'm building a penny-auction platform like DealDash and just read into the WebSocket and node.js topic.
I used PHP, MySQL and Ajax to build the website. I'm nearly finished and just have to implement the WebSocket function for the auctions to display correctly for all users.

I found a script to help me getting started with node.js and mysql, so I can still retrieve the data from my database every second. Because I need the auction timer and price to be displayed asynchronously for all users. Because I also have to complete this project in some days. But I'm considering learning more about NoSQL-db's and node.js, etc. afterwards of course.

However I've managed to have all auction items updated on the starting page async. with multiple browsers. So changes are updated for every user like I wanted it to be.

Now every auction has a single page to get further details to an auction and to the product. And usually I used $_GET['id'] in PHP/MySQL to receive the needed data which specific auction this is. But the node.js server-file server.js is the file to SELECT * FROM db.

So here's my problem. Do I have to tell the server-file, if the user is on an specific auction-id-page it has to make another specific query? I can't image that, because other projects like a social network would've dozens of specific queries, all written in the node.js server-file?
Also using an if-else statement in the server-file doesn't seem right? Also I don't know how I would get this specific id of an auction.

I'm just confused about the right way to realize something like that, because I'm so used to PHP/MySQL/Ajax and hope you could help me with that.

答:
Well, for such a "complex" project, i suggest that you split up your domains into smaller pieces, call it modules. Maybe it is easier to work with apis/resources instead of direct queries to the database.

Let me explain this a bit. Let's assume you want a front end part and a backend part. The front-end and the backend talks over an API, in my case a REST api. Let's say you want to display the information for auction number #2522. Your front-end logic makes a get request to your backend like:

GET api.myauctionpage.com/auction/2522.

The backend now has the responsibility to translate your get request into database queries and gathering informationen. If its done, it send the information to the client in a machine readable way (e.g. JSON, XML...).

For instance the return for the get request above would be something like:

{id: 2522, current_price: 25.00, betters: [{better_id: 123, better_name: 'charly'}, {better_id: 963, better_name: 'christine101'}]}

The front page logic now has the data and can starting to put it into the page and display it to the customer. In our case the current price is 25.00 and there are two betters, charly and christine101.

You see, I decoupled the logics and the backend does not care who the information wants and the frontend does not care how he gets the information.

Now it is up to you how you use or combine the api with your frontend, if you request every informationen every second or if you want to update it with websocket "events".

The backend can be written in PHP or even JavaScript (+node.js) or both, as long as the front end has a unique and correct way to request the informationen.


答:
You could have two overloaded functions. That way you can use both of them according to the situation.

You can't never (I've never seen it happen) optimize for everything, so you got to settle for something. Choose what you believe is more important.

Title: performance versus reusability

Body:
How can I write functions that are reusable without sacrificing performance? I am repeatedly coming up against the situation where I want to write a function in a way that makes it reusable (e.g. it makes no assumptions about the data environment) but knowing the overall flow of the program I know it isn't the most efficent method. For example if I want to write a function that validates a stock code but is reusable I can't just assume that the recordset is open. However if I open and close the recordset everytime the function is called then the performance hit when looping through thousands of rows could be huge.

So for performance I might have:

```<code>Function IsValidStockRef(strStockRef, rstStockRecords)
    rstStockRecords.Find ("stockref='" & strStockRef & "'")
    IsValidStockRef = Not rstStockRecords.EOF
End Function
</code>```

But for reusability I would need something like the following:

```<code>Function IsValidStockRef(strStockRef)
    Dim rstStockRecords As ADODB.Recordset

    Set rstStockRecords = New ADODB.Recordset
    rstStockRecords.Open strTable, gconnADO

    rstStockRecords.Find ("stockref='" & strStockRef & "'")
    IsValidStockRef = Not rstStockRecords.EOF

    rstStockRecords.Close
    Set rstStockRecords = Nothing
End Function
</code>```

I'm concerned that the impact on performance of opening and closing that recordset when called from within a loop over thousands of rows/records would be severe but using the first method makes the function less reusable.

What should I do?


问:
Full screen command line app that user cannot close in any way
All I'd like user to see is a "full screen" command line interface running my program. Users can enter certain input when prompted to, but they shouldn't be able under any circumstances to stop the program, and i.e. go and browse the disk. No CTRL+Z, ALT+F4 and such. I must assume users will be tech-savy and will know all key shortcuts and workarounds there are. Also, ideally, there should be a key combination that prompts for password when pressed, and if password is correct program closes. I assume this part won't be hard, I am mentioning it just in a case.

Users will be supervised to some extent so I'm not afraid of them i.e. rebooting PC and doing funny things before autostart kicks in. But short of restarting PC they shouldn't have any ways to stop the program, or to multitask and use anything in the computer aside from my program. Is it realistically possible, what would you suggest?

OS is going to be Ubuntu, and I was thinking using Python, but I am open to any alternative. The app itself is going to be incredibly simple (matching users input against some data in file and printing feedback), the hard part for me is preventing users from closing it, so I can "learn" just about any language if some are better than others for this task.

I am not looking for exact implementation, more like how to get on the right track. Once I know what exactly am I looking for, I can google and figure implementation on my own. I hope this question is not entirely out of place here, and thank you in advance for your help.

答: "Kiosk" applications like this are notoriously difficult to secure.  Your best starting point is to ditch the traditional command line and implement your own shell in its entirety, and to make it the user's actual shell (i.e., via chsh), so they can't slip out of it.


问:
How can I Identify which condition satisfied the if statement?
Suppose, I am using a if statement as such:

```<code>if(A || B || C || D)
{

   echo "Hurrah! if is satisfied!";
   echo "But! How can I know which was true of the 4 (A,B,C,D)";

}
</code>```

Is there any way I can know which condition(s) among A,B,C,D were true?

答:
Well, there's a simple statement that you're probably familiar with:

```<code>if(A || B || C || D)
{

   echo "Hurrah! if is satisfied!";
   echo "But! How can I know which was true of the 4 (A,B,C,D)";

   if (A)
      echo "A was true";

   if (B) /* NOT else if */
      echo "B was true";
}
</code>```

There's no way to unscramble an egg. You can't get A back from A||B||C||D.

Body:
Well, there's a simple statement that you're probably familiar with:

if(A || B || C || D)
{

   echo "Hurrah! if is satisfied!";
   echo "But! How can I know which was true of the 4 (A,B,C,D)";

   if (A)
      echo "A was true";

   if (B) /* NOT else if */
      echo "B was true";
}

There's no way to unscramble an egg. You can't get A back from A||B||C||D.


答:
You kinda can....

Assuming each of A, B, C and D are either 0 or 1:

```<code>result = A + 2*B + 4*C + 8*D;
if (result) {
   echo "Hurrah! if is satisfied!";

   // you can now check different bits of your result
}
</code>```

Title: How can I Identify which condition satisfied the if statement?

Body:
Suppose, I am using a if statement as such:

```<code>if(A || B || C || D)
{

   echo "Hurrah! if is satisfied!";
   echo "But! How can I know which was true of the 4 (A,B,C,D)";

}
</code>```

Is there any way I can know which condition(s) among A,B,C,D were true?

Body:
You kinda can....

Assuming each of A, B, C and D are either 0 or 1:

result = A + 2*B + 4*C + 8*D;
if (result) {
   echo "Hurrah! if is satisfied!";

   // you can now check different bits of your result
}


答:
2 functions: one opens the recordset and passes it to a data analysis function.

The first can be bypassed if you already have an open recordset. The second can assume that it will be passed an open recordset, ignoring where it came from, and process the data.

You have both performance and re-usability then!

Title: performance versus reusability


问:
How do I do SQL Server mapping with a new Desktop application written in C#?
In 2 weeks I will be starting a new job as a software developer in a company that currently does not employ any professional programmers.  My first task will be to rewrite a Excel/VBA application in C#, with an SQL back end.

I am currently a C# developer but we don't use a database back end; previously I was a database administrator but I didn't program.  I have very little experience at joining up the two worlds.

What are the options for modelling the database access in a C# desktop application with a SQL Server back end?  I would want to have some separation between the layers (database, logic, user interface).

答: What I think you want is domain driven design, In simple terms separation of concerns. Read about it and you are good to go. To keep it simple since you say yo new, Just have User Interface layer in its own project, a service / logic layer in its own project. a data access layer in its own project and other layers depending on the project. For the data access i would recommend you use Entity Framework to bind with your database (preferable database first option since you have db admin background). Now read and get familiar with Linq and Entity Framework and i think you are good to go. </p>


答:
Neither of these seems more reusable than the other. They just seem to be at different abstraction levels. The first is for calling code that understands the stock system intimately enough to know that validating a stock reference means looking through a Recordset with some kind of query. The second is for calling code that just wants to know whether a stock code is valid or not and has no interest concerning itself with how you'd verify such a thing.

But as with most abstractions, this one is "leaky". In this case the abstraction leaks through its performance- the calling code can't completely ignore how validation is implemented because if it did, it might call into that function thousands of times as you described and seriously degrade overall performance.

Ultimately, if you have to choose between poorly abstracted code and unacceptable performance, you have to choose the poorly abstracted code. But first, you should look for a better solution- a compromise that maintains acceptable performance and presents a decent (if not ideal) abstraction. Unfortunately I don't know VBA very well, but in an OO language, my first thought would be to give calling code a class with methods like:

```<code>BeginValidation()
IsValidStockRef(strStockRef)
EndValidation()
</code>```

Here your Begin... and End... methods do the one-time lifecycle management of the record set, the IsValidStockRef matches your first version, but uses this record set which the class itself has taken responsibility for, rather than having it passed in. Calling code would then call the Begin... and End... methods outside of the loop, and the validation method inside.

Note: This is only a very rough illustrative example, and might be considered a first-pass at refactoring. The names could probably use tweaking, and depending on the language there should be a more clean or idiomatic way to do it (C# for example could use the constructor to begin and Dispose() to end). Ideally code that just wants to check if a stock ref is valid shouldn't itself have to do any lifecycle management at all.

This represents a slight degredation to the abstraction we're presenting: now calling code needs to know enough about validation to understand that it's something which requires some kind of setup and teardown. But in return for that relatively modest compromise, we now have methods that can be used easily by calling code, without hurting our performance.

Title: performance versus reusability

Body:
Neither of these seems more reusable than the other. They just seem to be at different abstraction levels. The first is for calling code that understands the stock system intimately enough to know that validating a stock reference means looking through a Recordset with some kind of query. The second is for calling code that just wants to know whether a stock code is valid or not and has no interest concerning itself with how you'd verify such a thing.

But as with most abstractions, this one is "leaky". In this case the abstraction leaks through its performance- the calling code can't completely ignore how validation is implemented because if it did, it might call into that function thousands of times as you described and seriously degrade overall performance.

Ultimately, if you have to choose between poorly abstracted code and unacceptable performance, you have to choose the poorly abstracted code. But first, you should look for a better solution- a compromise that maintains acceptable performance and presents a decent (if not ideal) abstraction. Unfortunately I don't know VBA very well, but in an OO language, my first thought would be to give calling code a class with methods like:

BeginValidation()
IsValidStockRef(strStockRef)
EndValidation()

Here your Begin... and End... methods do the one-time lifecycle management of the record set, the IsValidStockRef matches your first version, but uses this record set which the class itself has taken responsibility for, rather than having it passed in. Calling code would then call the Begin... and End... methods outside of the loop, and the validation method inside.

Note: This is only a very rough illustrative example, and might be considered a first-pass at refactoring. The names could probably use tweaking, and depending on the language there should be a more clean or idiomatic way to do it (C# for example could use the constructor to begin and Dispose() to end). Ideally code that just wants to check if a stock ref is valid shouldn't itself have to do any lifecycle management at all.

This represents a slight degredation to the abstraction we're presenting: now calling code needs to know enough about validation to understand that it's something which requires some kind of setup and teardown. But in return for that relatively modest compromise, we now have methods that can be used easily by calling code, without hurting our performance.


问:
How do you decide your side projects
At any given time, I usually have a bunch of ideas for weekend/side projects that I can work on. The ideas can be generally be categorized into these:

Self Learning: Learning a new language/ technology/ framework

Work related: Learning/Doing something that would help you at work

Money: Projects that (you think) can make some money

Fun/Utility projects

These are just the rough categories that I can think of and there can be more/other ways of classification.

My question is based on your experience what should drive the decision of what kind of project to work on. What parameters apart from the type of project should impact this decision (time, effort, money...)

答:
Always have a project you can work on in meetings

For example, I had a thing I called "Meeting Lisp".

This was a lisp interpreter written in C that I hacked on intermittently over the period of a couple of years at my old job.

The Rules:

I could only work on it during meetings.

The source had to fit on one 66-line by 80-column page.  (So I could work on it discreetly in meetings!)

The code had to compile cleanly.

No debugging at the computer.  Bugs had to be diagnosed and fixed at the next meeting.

This include compilation errors.

It had an "include" command, so parts of the library were in lisp and didn't count against the page limit.

I learned a lot and it was a great way to pass the time in boring meetings, so I guess it combined #2 with #1 and #4.

Title: How do you decide your side projects

ContentLicense: CC BY-SA 2.5


答:
You definitely should design your application with discrete layers - data access, business logic, UI etc.

However, I'm going to go against the trend and advise you not to use Entity Framework for your data access layer.

An ORM should be purely a mapper between database and POCO classes. In my eyes, EF breaks the single responsibility principle by trying to do too much - caching, change tracking, lazy loading etc etc. All this extra functionality places too heavy a load on performance.

Instead, I suggest that you should use a simple micro-ORM such as Dapper, Peta Poco or OrmLite. Your choice will depend on the exact functionality required and whether you have an existing database. My vote would go to OrmLite, as it supports code-first design (generating database elements from C# class definitions) and async/await functionality.

Title: How do I do SQL Server mapping with a new Desktop application written in C#?

Body:
In 2 weeks I will be starting a new job as a software developer in a company that currently does not employ any professional programmers.  My first task will be to rewrite a Excel/VBA application in C#, with an SQL back end.

I am currently a C# developer but we don't use a database back end; previously I was a database administrator but I didn't program.  I have very little experience at joining up the two worlds.

What are the options for modelling the database access in a C# desktop application with a SQL Server back end?  I would want to have some separation between the layers (database, logic, user interface).


答:
Remember that tests can be refactored too! If you make a method private, you're reducing the public API, and hence it's perfectly acceptable to throw away some corresponding tests for that "lost functionality" (AKA reduced complexity).

Others have said your private method will either be called as part of your other API tests, or it will be unreachable and hence deletable. In fact, things are more fine-grained if we think about execution paths.

For example, if we have a public method which performs division we might want to test the path which results in division-by-zero. If we make the method private, we get a choice: either we can consider the division-by-zero path, or we can eliminate that path by considering how it's called by the other methods.

In this way, we may throw away some tests (eg. divide-by-zero) and refactor the others in terms of the remaining public API. Of course, in an ideal world the existing tests take care of all those remaining paths, but reality is always a compromise ;)


答:
I wonder why your language only has two levels of privacy, fully public and completely private.

Can you arrange your non-public methods be package-accessible or something like that? Then put your tests in the same package and enjoy testing the inner workings which are not a part of the public interface. Your build system will exclude tests when building a release binary.

Of course sometimes you need to have truly private methods, not accessible to anything but the defining class. I hope all such methods are very small. In general, keeping the methods small (e.g. below 20 lines) helps a lot: testing, maintenance and just understanding the code becomes easier.


答:
Units

I think I can pinpoint exactly where the problem started:

I figured, I'll need a method that finds all the non-numerical fields in a line.

This should be immediately followed with asking yourself "Will that be a separate testable unit to gatherNonNumericColumns or part of the same one?"

If the answer is "yes, separate", then your course of action is simple: that method needs to be public on an appropriate class, so it can be tested as a unit. Your mentality is something like "I need to test drive out one method and I also need to test drive out another method"

From what you say though, you figured that the answer is "no, part of the same". At this point, your plan should no longer be to fully write and test findNonNumericFields then write gatherNonNumericColumns. Instead, it should be simply to write gatherNonNumericColumns. For now, findNonNumericFields should just be a likely part of the destination you have in mind when you're choosing your next red test case and doing your refactoring. This time your mentality is "I need to test drive out one method, and while I do so I should keep in mind that my finished implementation will probably include this other method".

Keeping a short cycle

Doing the above should not lead to the problems you describe in your penultimate paragraph:

Because if I start out by writing a test for a public method, there will be several minutes (or hours, or even days in very complex cases) before I get all the details in the private methods to work so that the test testing the public method passes.

At no point does this technique require you to write a red test which will only turn green when you implement the entirety of findNonNumericFields from scratch. Much more likely, findNonNumericFields will start as some code in-line in the public method you're testing, which will be built up over the course of several cycles and eventually extracted during a refactoring.

Roadmap

To give an approximate roadmap for this particular example, I don't know the exact test cases you used, but say you were writing gatherNonNumericColumns as your public method. Then most likely the test cases would be the same as the ones you wrote for findNonNumericFields, each one using a table with only one row. When that one-row scenario was fully implemented, and you wanted to write a test to force you to extract out the method, you'd write a two-row case which would require you to add your iteration.


问:
Can the author of an MIT licensed project convert it to a commercial licensed one?
I came across bootstrapvalidator project on Github which was released under MIT license in the past. In the contributors list, I can see a lot many people other than the main author of the project. The latest releases of the project are under a commercial license.

Is it legal for the author to change the license from MIT license to a commercial one, if he is the only contributor?

Is it legal to change the license from MIT license to a commercial one, if there are other contributors involved?

答:
The MIT license is considered a fairly permissive license for a number of reasons, including the sublicense clause:

Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.

Emphasis mine

It's this portion of the MIT license that allows anyone to take an MIT license and re-license so long as they maintain the requirements stated with The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Is it legal for the author to change the license from MIT license to a commercial one, if he is the only contributor?

Yes, as the sole author of the project, they own the copyright to the project.  Owning the copyright allows them to re-license the project to a commercial license.

In this particular case, the copyright owner to the project can re-license as they wish and does not need to maintain the copyright or permission notices from the MIT license.

Is it legal to change the license from MIT license to a commercial one, if there are other contributors involved?

The project could be re-licensed in any of the following cases:

If the other contributors assigned their copyright to the project or the original author.

If the other contributors didn't assign copyright but they all agreed to the re-license.

Someone chooses to exercise the sublicense clause of the MIT license that the project was released under.

In the first two cases, the copyright owner(s) can re-license without maintaining the copyright and permission notices.

In the third case, the person re-licensing the project must obey the terms of the license and they must maintain the copyright and permission notices.

Also note that the MIT license is not a copyleft license, so there is no obligation to share the associated source code.

Likewise, just because someone chooses to fork and re-license a project, that re-licensing applies only to the forked project.  The re-licensing has no bearing upon the original project or how the original project is licensed.


答:
You are encountering a common misconception with testing in general.

Most people who are new to testing start out thinking this way:

write a test for function F

implement F

write a test for function G

implement G using a call to F

write a test for a function H

implement H using a call to G

and so on.

The problem here is that you in fact have no unit test for the function H. The test that is supposed to test H is actually testing H, G and F at the same time.

To solve this you have to realize that testable units must never depend on each other, but rather on their interfaces. In your case, where the units are simple functions the interfaces are just their call signature. You must therefore implement G in such a way, that it can be used with any function having the same signature as F.

How exactly this can be done depends on your programming language. In many languages you can pass functions (or pointers to them) as arguments to other functions. This will enable you to test each function in isolation.


问:
To convert to accurate data types or maintain default type of string
Scenario:

I have a web application that records and checks data against two temp tables (1 table being a temp source and the other being a destination for the application). These temp tables are synced up each night with their respective destination/source sql views.

The Issue:

The source/destination views have char/nvarchar data types however the actual content inside these views are mostly integers. How should I construct my model for the temp tables within the application; should I convert the data to their real types (converting the types during sync time) or just keep them in the form of strings?

Important:

There is no validation needed for the types, it will be impossible for the user to enter invalid data. The true data types of the content will hold constant for each column with no accidental variation. So the question comes down to, is there anything wrong with processing integers as strings? Other than it being annoying as hell.

答:
Store them in the database as the respective data types.  Instead of storing "1234" as a string, store the int 1234.

This does a couple of things for you.

It prevents data consumers from having to do the conversion and possible mistakes (not only will this prevent mistakes, but it'll maximize performance for the data consumers.  Convert the data before it is dumped into the table so it doesn't have to be continuously converted upon retrieval)

It will allow bad data to fail fast and fail early, as you wouldn't be able to put bad data in the source table (i.e. on an int column, if you didn't expect bad data but attempted to throw "123a4" in there it would fail.  That's a good thing)

Store the data as it is expected.  It will alleviate a lot of complications.


答:
For a long time, I used to implement a complicated system of checks to be able to use database transactions.  The transaction logic goes as follows:  open a transaction, perform the database operations, rollback upon error or commit on success.  The complication comes from what happens when you want an additional operation to be performed within the same transaction.  You'd either need to write a second method entirely which does both operations, or you could call your original method from a second, opening a transaction only if one hasn't already been opened and committing/rolling back changes only if you were the one to open the transaction.

For example:

```<code>public void method1() {
    boolean selfOpened = false;
    if(!transaction.isOpen()) {
        selfOpened = true;
        transaction.open();
    }

    try {
        performDbOperations();
        method2();

        if(selfOpened)
            transaction.commit();
    } catch (SQLException e) {
        if(selfOpened)
            transaction.rollback();
        throw e;
    }
}

public void method2() {
    boolean selfOpened = false;
    if(!transaction.isOpen()) {
        selfOpened = true;
        transaction.open();
    }

    try {
        performMoreDbOperations();

        if(selfOpened)
            transaction.commit();
    } catch (SQLException e) {
        if(selfOpened)
            transaction.rollback();
        throw e;
    }
}
</code>```

Please note, I'm not advocating the above code by any means.  This should serve as an example of what not to do!

It seemed silly to create a second method to perform the same logic as the first plus something extra, yet I wanted to be able to call the database API section of the program and seal off problems there.  However, while this partially solved my problem, every method I wrote involved adding this verbose logic of checking if a transaction is already open, and committing/rolling back changes if my method opened it.

The problem was conceptual.  I shouldn't have attempted to embrace every possible scenario.  The proper approach was to house transaction logic in a single method taking a second method as a parameter that would perform the actual database logic. That logic assumes the transaction is open and does not even perform a check.  These methods could be called in combination so that these methods weren't cluttered with unnecessary transaction logic.

The reason I mention this is because my mistake was to assume that I needed to make my method work in any situation.  In doing so, not only was my called method checking if a transaction was open, but also those that it called.  In this case, it is not a major performance hit, but if say, I needed to verify the existence of a record in the database before proceeding, I would be checking for every method which requires it when I should have just assumed all along that the caller should be made aware that the record should exist.  If the method is called anyway, this is undefined behavior and you need not worry about what happens.

Rather you should provide plenty of documentation, and write what you expect to be true before a call is made to your method.  If it is important enough, add it as a comment before your method so that there should be no mistake (javadoc provides nice support for this sort of thing in java).

I hope that helps!

Title: performance versus reusability

Body:
For a long time, I used to implement a complicated system of checks to be able to use database transactions.  The transaction logic goes as follows:  open a transaction, perform the database operations, rollback upon error or commit on success.  The complication comes from what happens when you want an additional operation to be performed within the same transaction.  You'd either need to write a second method entirely which does both operations, or you could call your original method from a second, opening a transaction only if one hasn't already been opened and committing/rolling back changes only if you were the one to open the transaction.

For example:

public void method1() {
    boolean selfOpened = false;
    if(!transaction.isOpen()) {
        selfOpened = true;
        transaction.open();
    }

    try {
        performDbOperations();
        method2();

        if(selfOpened)
            transaction.commit();
    } catch (SQLException e) {
        if(selfOpened)
            transaction.rollback();
        throw e;
    }
}

public void method2() {
    boolean selfOpened = false;
    if(!transaction.isOpen()) {
        selfOpened = true;
        transaction.open();
    }

    try {
        performMoreDbOperations();

        if(selfOpened)
            transaction.commit();
    } catch (SQLException e) {
        if(selfOpened)
            transaction.rollback();
        throw e;
    }
}

Please note, I'm not advocating the above code by any means.  This should serve as an example of what not to do!

It seemed silly to create a second method to perform the same logic as the first plus something extra, yet I wanted to be able to call the database API section of the program and seal off problems there.  However, while this partially solved my problem, every method I wrote involved adding this verbose logic of checking if a transaction is already open, and committing/rolling back changes if my method opened it.

The problem was conceptual.  I shouldn't have attempted to embrace every possible scenario.  The proper approach was to house transaction logic in a single method taking a second method as a parameter that would perform the actual database logic. That logic assumes the transaction is open and does not even perform a check.  These methods could be called in combination so that these methods weren't cluttered with unnecessary transaction logic.

The reason I mention this is because my mistake was to assume that I needed to make my method work in any situation.  In doing so, not only was my called method checking if a transaction was open, but also those that it called.  In this case, it is not a major performance hit, but if say, I needed to verify the existence of a record in the database before proceeding, I would be checking for every method which requires it when I should have just assumed all along that the caller should be made aware that the record should exist.  If the method is called anyway, this is undefined behavior and you need not worry about what happens.

Rather you should provide plenty of documentation, and write what you expect to be true before a call is made to your method.  If it is important enough, add it as a comment before your method so that there should be no mistake (javadoc provides nice support for this sort of thing in java).

I hope that helps!


问:
Real world T4 usage
How many of you have ever used (or even know of)  the Visual Studio Text Templating Engine?

I mean, T4 templates have been around for quite some years now. The where initially included in Visual Studio 2005 SDK, and they where moved to Visual Studio 2008 core just before releasing it.

What I want to know is if this is really used out there. I mean, why doesn't the VS team invested in a descent minimal editor for the templates? It doesn't even have syntax couloring!
I know there are a couple of good T4 editors out there, but as they don't come built in, I tend to think that this is an unknown feature for most developers.

Have you ever used T4 templates in any of your projects? I'm really interested in answers that explain how they created their own T4 to accelerate, automate, or generate artifacts for your project.

答: I agree, the support in Visual Studio is extremely lacking but the T4 framework is very useful and flexible.  So much so I created an extension that makes creating, organizing, and running templates easier.  It supports simple parameter prompting and allows you to completely control the output location of your rendered results.  You can download it from my website or the vs gallery.  You can use the community edition for free but to use some of the more advanced features requires a full license which cost money.</p>

Title: Real world T4 usage


答:
There are tradeoffs to consider...

If the data will always remain integers, you might consider conversion to integers.  But beware of predicting the future.
If the data needs to be compared or sorted, or otherwise analyzed by range depending on the numeric value, then you might consider conversion to integers.
If the data may need to be flexible with regard to formatting, you might consider keeping the strings.

Sometimes things that look like numbers end up needing some descriptive prefix or suffix added later, and that will break your conversions.  If they are not really numeric values that mean anything, for instance they are simply identifiers, then they are much easier to deal with as strings.  This gives you full flexibility in formatting them and you don't have to worry about numeric validity checking.  You can trim the strings, validate the digits by their location within the string - the options are limitless.

Assume you have highway 70 in the database with 70 in the highway number column.  You might have a direction column that can contain, NSEW values.  What if you want to add Hwy "70 Alt" South?  The "Alt" can't go in the direction column, yet it breaks the conversion of the highway number.  The 70 in the highway number doesn't mean it is greater than highway 65 or less than highway 75.  It should be a string both in the database and in your code.

A column that contains a specific mile marker on Hwy 70 should be a number, though.

Title: To convert to accurate data types or maintain default type of string

Body:
Scenario:

I have a web application that records and checks data against two temp tables (1 table being a temp source and the other being a destination for the application). These temp tables are synced up each night with their respective destination/source sql views.

The Issue:

The source/destination views have char/nvarchar data types however the actual content inside these views are mostly integers. How should I construct my model for the temp tables within the application; should I convert the data to their real types (converting the types during sync time) or just keep them in the form of strings?

Important:

There is no validation needed for the types, it will be impossible for the user to enter invalid data. The true data types of the content will hold constant for each column with no accidental variation. So the question comes down to, is there anything wrong with processing integers as strings? Other than it being annoying as hell.


答: I occasionally have bumped private methods to protected to allow finer grained testing (tighter than the exposed public API).  This should be the (hopefully very rare) exception rather than the rule, but it can be helpful in certain specific cases that you may run across.  Also, that's something you would not want to consider at all when building a public API, more of "cheat" that one can use on internal use software in those rare situations.</p>


答:
Optimisation (besides micro-optimization) is directly at odds with modularity.

Modularity works by isolating code from it's global context, whereas performance optimization exploits global context to minimise what the code has to do. Modularity is the benefit of low-coupling, whereas (the potential for) very high performance is the benefit of high-coupling.

The answer is architectural. Consider the pieces of the code that you are going to want to reuse. Perhaps it's the price calculation component, or configuration validation logic.

Then you should write the code that interacts with that component for reusability. Within a component where you can never use just part of the code you can optimise for performance since you know no one else will be use it.

The trick of it is determining what your components are.

tl;dr: between components write with modularity in mind, within components write with performance in mind.

Title: performance versus reusability


答:
The tests that you write during Test Driven Development are supposed to make sure that a class correctly implements its public API, while simultaneously making sure that that public API is easy to test and use.

You can by all means use private methods to implement that API, but there is no need to create tests through TDD – the functionality will be tested because the public API will work correctly.

Now suppose your private methods are complicated enough that they merit standalone tests – but they make no sense as part of your original class's public API. Well, this probably means that they should actually be public methods on some other class – one that your original class takes advantage of in its own implementation.

By only testing the public API, you are making it far easier to modify the implementation details in future. Unhelpful tests will only annoy you later when they need to be rewritten to support some elegant refactoring you have just discovered.


答:
There are times when a private method could be made a public method of another class.

For example, you might have private methods that are not thread-safe and leave the class in an temporary state. These methods can be moved to a separate class which is held privately by your first class. So if your class is a Queue, you could have an InternalQueue class which has public methods, and the Queue class hold the InternalQueue instance privately. This lets you test the internal queue, and it also makes clear what the individual operations on the InternalQueue is.

(This is most obvious when you imagine there was no List class, and if you tried to implement the List functions as private methods in class that uses them.)


问:
What makes BEM better than using a nestable style sheet language like LESS?
A colleague of mine is heavily pushing the BEM (Block Element Modifier) method for the CSS in a project he's helming, and I just cannot comprehend what makes it better than the LESS CSS we've been writing for years.

He claims "higher performance", but I can't imagine how performance could even matter for the kinds of web apps we write in this code shop. We're not making Twitter or Facebook, here. I'd be very surprised if our highest use apps have more than 10000 hits a month, and most are well under 1000.

He claims "readability" and "re-use", but LESS already does that much better, in my opinion. And I feel that BEM mangles the markup so badly with dozens of extra characters dedicated to these super-long class names that it radically reduces readability.

He claims "nested CSS is an anti-pattern." What does "anti-pattern" even mean, and why is nested CSS bad?

He claims that "everyone is moving toward using BEM, so we should too." My counter is "If everyone was jumping off a bridge, would you follow?" But he's still totally adamant about this.

Could someone please explain in detail what makes BEM better than LESS? My colleague is completely failing to convince me, but I don't know if I have a choice but to follow. I'd really rather be able to appreciate BEM, than to grudgingly accept it.

答:
A colleague of mine is heavily pushing the BEM (Block Element Modifier) method for the CSS in a project he's helming, and I just cannot comprehend what makes it better than the LESS CSS we've been writing for years.

BEM is a CSS methodology. Others include OOCSS and SMACSS. These methodologies are used to write modular, extensible, reusable code that performs well at scale.

LESS is a CSS preprocessor. Others include Sass and Stylus. These preprocessors are used to convert their respective sources into expanded CSS.

BEM and LESS are not comparable as being "better" than one another, they are tools that serve different purposes. You wouldn't say that a screwdriver is better than a hammer, except when considering utility to solve a specific problem.

He claims "higher performance"...

Performance would need to be measured between a classical CSS style of:

```<code>.widget .header
</code>```

and BEM style of:

```<code>.widget__header
</code>```

but generally speaking, CSS selector performance is not a bottleneck, and does not need to be optimized.

BEM "performance" is usually with regard to a developer's performance writing code. If the BEM methodology is used consistently and correctly, it is easy for groups of developers to simultaneously author distinct modules without style collisions.

He claims "readability" and "re-use"...

I don't know that I would tell a new developer that BEM is more readable. I can say that it provides some well-defined guidelines as to the meaning and structure of classes.

Seeing a class like

```<code>.foo--bar__baz
</code>```

Tells me that there is a foo block that is in the bar state, and contains a baz element.

I would absolutely say that BEM is more reusable than a classical model.

If two developers create blocks (foo and bar), and both of those blocks have headings, they can safely reuse their blocks in different contexts without worry of a naming collision.

That's because, in a classical context, .foo .heading and .bar .heading would conflict, and introduce a specificity conflict that would need to be resolved, possibly on a case-by-case basis.

In a BEM site, the classes would be .foo__heading and .bar__heading, which would never conflict.

He claims "nested CSS is an anti-pattern." What does "anti-pattern" even mean, and why is nested CSS bad?

An "anti-pattern" is a coding pattern that's easier for inexperienced developers to learn and use than a more appropriate alternative.

As far as why nested CSS is bad: Nesting increases a selector's specificity. The higher the specificity, the more effort it takes to override. Inexperienced developers often worry that their CSS might affect multiple pages, so they use selectors like:

```<code>#something .lorem .ipsum .dolor ul.sit li.amet a.more
</code>```

When an experienced developer would worry that their CSS might not affect multiple pages, so they use selectors like:

```<code>.more
</code>```

He claims that "everyone is moving toward using BEM, so we should too."...

That is a bandwagon fallacy, so ignore that as a bad argument. Don't fall trap to the fallacy fallacy, because a bad argument in support of BEM isn't a reason to believe that BEM can't be good.

Could someone please explain in detail what makes BEM better than LESS?

I covered this before, BEM & LESS are not comparable. Apples and oranges, etc.

My colleague is completely failing to convince me, but I don't know if I have a choice but to follow.

I recommend taking a look at OOCSS, SMACSS, and BEM, and weighing the pros and cons of each methodology...as a team. I use BEM because I like its strictness in format, and don't mind the ugly selectors, but I can't tell you what's right for you or for your team. Don't let one outspoken individual run the show. If you're not comfortable with BEM, be aware that there are other alternatives that might be easier for your team to support. You may need to defend your position with your coworker, but long-term it will likely have a positive effect on the outcome of your projects.

I'd really rather be able to appreciate BEM, than to grudgingly accept it.

I wrote an answer on StackOverflow that describes how BEM works. The important thing to understand is that your ideal selectors should have a specificity of 0-0-1-0 so that they are easy to override and extend.

Choosing to use BEM doesn't mean you need to give up LESS! You can still use variables, you can still use @imports, and you can certainly continue to use nesting. The difference is you want the rendered output to become a single class, rather than a descendant chain.

Where you might have had

```<code>.widget {
    .heading {
        ...
    }
}
</code>```

With BEM you can use:

```<code>.widget {
    &__heading {
        ...
    }
}
</code>```

Additionally, because BEM revolves around individual blocks, you can easily separate code into separate files. widget.less would contain styles for the .widget block, while component.less would contain styles for the .component block. This makes it much easier to find the source for any particular class, although you may still wish to be using source maps.

Body:
A colleague of mine is heavily pushing the BEM (Block Element Modifier) method for the CSS in a project he's helming, and I just cannot comprehend what makes it better than the LESS CSS we've been writing for years.

BEM is a CSS methodology. Others include OOCSS and SMACSS. These methodologies are used to write modular, extensible, reusable code that performs well at scale.

LESS is a CSS preprocessor. Others include Sass and Stylus. These preprocessors are used to convert their respective sources into expanded CSS.

BEM and LESS are not comparable as being "better" than one another, they are tools that serve different purposes. You wouldn't say that a screwdriver is better than a hammer, except when considering utility to solve a specific problem.

He claims "higher performance"...

Performance would need to be measured between a classical CSS style of:

.widget .header

and BEM style of:

.widget__header

but generally speaking, CSS selector performance is not a bottleneck, and does not need to be optimized.

BEM "performance" is usually with regard to a developer's performance writing code. If the BEM methodology is used consistently and correctly, it is easy for groups of developers to simultaneously author distinct modules without style collisions.

He claims "readability" and "re-use"...

I don't know that I would tell a new developer that BEM is more readable. I can say that it provides some well-defined guidelines as to the meaning and structure of classes.

Seeing a class like

.foo--bar__baz

Tells me that there is a foo block that is in the bar state, and contains a baz element.

I would absolutely say that BEM is more reusable than a classical model.

If two developers create blocks (foo and bar), and both of those blocks have headings, they can safely reuse their blocks in different contexts without worry of a naming collision.

That's because, in a classical context, .foo .heading and .bar .heading would conflict, and introduce a specificity conflict that would need to be resolved, possibly on a case-by-case basis.

In a BEM site, the classes would be .foo__heading and .bar__heading, which would never conflict.

He claims "nested CSS is an anti-pattern." What does "anti-pattern" even mean, and why is nested CSS bad?

An "anti-pattern" is a coding pattern that's easier for inexperienced developers to learn and use than a more appropriate alternative.

As far as why nested CSS is bad: Nesting increases a selector's specificity. The higher the specificity, the more effort it takes to override. Inexperienced developers often worry that their CSS might affect multiple pages, so they use selectors like:

#something .lorem .ipsum .dolor ul.sit li.amet a.more

When an experienced developer would worry that their CSS might not affect multiple pages, so they use selectors like:

.more

He claims that "everyone is moving toward using BEM, so we should too."...

That is a bandwagon fallacy, so ignore that as a bad argument. Don't fall trap to the fallacy fallacy, because a bad argument in support of BEM isn't a reason to believe that BEM can't be good.

Could someone please explain in detail what makes BEM better than LESS?

I covered this before, BEM & LESS are not comparable. Apples and oranges, etc.

My colleague is completely failing to convince me, but I don't know if I have a choice but to follow.

I recommend taking a look at OOCSS, SMACSS, and BEM, and weighing the pros and cons of each methodology...as a team. I use BEM because I like its strictness in format, and don't mind the ugly selectors, but I can't tell you what's right for you or for your team. Don't let one outspoken individual run the show. If you're not comfortable with BEM, be aware that there are other alternatives that might be easier for your team to support. You may need to defend your position with your coworker, but long-term it will likely have a positive effect on the outcome of your projects.

I'd really rather be able to appreciate BEM, than to grudgingly accept it.

I wrote an answer on StackOverflow that describes how BEM works. The important thing to understand is that your ideal selectors should have a specificity of 0-0-1-0 so that they are easy to override and extend.

Choosing to use BEM doesn't mean you need to give up LESS! You can still use variables, you can still use @imports, and you can certainly continue to use nesting. The difference is you want the rendered output to become a single class, rather than a descendant chain.

Where you might have had

.widget {
    .heading {
        ...
    }
}

With BEM you can use:

.widget {
    &__heading {
        ...
    }
}

Additionally, because BEM revolves around individual blocks, you can easily separate code into separate files. widget.less would contain styles for the .widget block, while component.less would contain styles for the .component block. This makes it much easier to find the source for any particular class, although you may still wish to be using source maps.


问:
Using Django to Create Child Sites
I am creating a series of small sites, I'm using the django framework.  The theory goes a user comes to a master site, signs up, then he gets his own child site.

Example:

navigate to example.com

user creates an account "mysite"

user then gets his own site:  mysite.example.com and he can configure this all he wants

My question:
* would it be better to have a "gold" version of the site that gets created for each site?

for instance:
cp ~/goldsite ~/mysite  and change the database pointers appropriately
** the downside is if I ever have to do maintenance on a file, I would have to change all subsites.

...or
* have one host and configure the database to support multiple sites.  The DB might get messy.

Any feedback would be great.

答:
My suggestion would be to create a separate django base server which will serve as a web service api.

This web server will use rpcdjango which, when used with any method as a decorator, converts it to a HTTP callable method.

You will have to put little more effort on database design so that it does not become too complex.

Then create your individual web application using any technology (I prefer AngularJS and Bootstrap) which will connect to the django server using Ajax methods.

Here is an example django rpc4django:

First, you need to add a new URL pattern to your root urls.py file. You can replace r’^RPC2$’ with anything you like.

urls.py

```<code>urlpatterns = patterns(’’,
    # rpc4django will need to be in your Python path
    (r’^RPC2$’, ’rpc4django.views.serve_rpc_request’),
)
</code>```

Second, add rpc4django to the list of installed applications in your settings.py.

settings.py

```<code>INSTALLED_APPS = (
    ’rpc4django’,
)
</code>```

Lastly, you need to let rpc4django know which methods to make available. Rpc4django recursively imports all the apps in INSTALLED_APPS and makes any methods importable via __init__.py*** with the @rpcmethod decorator available as RPC methods. You can always write your RPC methods in another module and simply import it in __init__.py.

testapp/__init__.py

```<code>from rpc4django import rpcmethod
# The doc string supports reST if docutils is installed
@rpcmethod(name=’mynamespace.add’, signature=[’int’, ’int’, ’int’])
def add(a, b):
    ’’’Adds two numbers together
    >>> add(1, 2)
    3
    ’’’
    return a+b
</code>```

rpc4django documentation

Title: Using Django to Create Child Sites

Body:
My suggestion would be to create a separate django base server which will serve as a web service api.

This web server will use rpcdjango which, when used with any method as a decorator, converts it to a HTTP callable method.

You will have to put little more effort on database design so that it does not become too complex.

Then create your individual web application using any technology (I prefer AngularJS and Bootstrap) which will connect to the django server using Ajax methods.

Here is an example django rpc4django:

First, you need to add a new URL pattern to your root urls.py file. You can replace r’^RPC2$’ with anything you like.

urls.py

urlpatterns = patterns(’’,
    # rpc4django will need to be in your Python path
    (r’^RPC2$’, ’rpc4django.views.serve_rpc_request’),
)

Second, add rpc4django to the list of installed applications in your settings.py.

settings.py

INSTALLED_APPS = (
    ’rpc4django’,
)

Lastly, you need to let rpc4django know which methods to make available. Rpc4django recursively imports all the apps in INSTALLED_APPS and makes any methods importable via __init__.py*** with the @rpcmethod decorator available as RPC methods. You can always write your RPC methods in another module and simply import it in __init__.py.

testapp/__init__.py

from rpc4django import rpcmethod
# The doc string supports reST if docutils is installed
@rpcmethod(name=’mynamespace.add’, signature=[’int’, ’int’, ’int’])
def add(a, b):
    ’’’Adds two numbers together
    >>> add(1, 2)
    3
    ’’’
    return a+b

rpc4django documentation


答:
The author can change the license going forward. Proponents of the license consider this a major selling point. The sole author of a project can change the license at any time. Others can include it in their own products, and change the license at any time.

The author can continue to use other people's MIT-licensed code in the new, non-MIT-licensed version. The other people's code is still MIT-licensed, but as long as the author abides by the licenses for these other people's code, there is no problem.

Or the author can ask the contributors to relicense their code too. There was a point when Mozilla wanted to change the license to its code, and it had to go around asking the contributors for permission. If everyone agrees, good; you can relicense. If someone says no, then you've got a problem.

What the author can't do is change the license going backward. If Version 2 of a project is MIT-licensed, and then the maintainer changes the license for Version 3, then that's the maintainer's prerogative: starting from Version 3, the new license applies. But Version 2 is still MIT-licensed, and people can still use and/or fork that version if they wish. That genie is out of the bottle.

Title: Can the author of an MIT licensed project convert it to a commercial licensed one?

Body:
I came across bootstrapvalidator project on Github which was released under MIT license in the past. In the contributors list, I can see a lot many people other than the main author of the project. The latest releases of the project are under a commercial license.

Is it legal for the author to change the license from MIT license to a commercial one, if he is the only contributor?

Is it legal to change the license from MIT license to a commercial one, if there are other contributors involved?


问:
Internationalization on a service layer of an application
My specific problem is how to handle internationalization of specific messages from an architecture layer that is not the view layer(e.g service layer).

I've created an architecture based on technology to be used (e.g. jsf, primefaces, spring, postgres and mybatis). So to avoid rewriting code i've defined a project to be a jar (with maven) that has all generic (abstract) classes that one should implement (based on interfaces). Something like (to keep it short I will focus in one functionality and I will not add the dao classes)

```<code>com.arch
 |_ service
 |   |_ GenericService.java
 |   |_ AbstractGenericServiceImpl.java
 |   |_ GenericServiceException.java
 |_ domain
 |   |_ GenericDomain.java
 |_ view
     |_ AbstractGenericManagedBean.java
</code>```

With this in a jar file I can create an application that will abstract all the repetitive operations like add, edit, delete, list, etc.

In my AbstractGenericServiceImpl all operations throws GenericServiceException with a message based on the original exception like this:

```<code>@Override
public void add(E entity) throws D {
    try {
        getGenericDao().add(entity);
    } catch (DuplicateKeyException ex) {
        throw getNewException("Duplicate registry. Can not add.");
    }
}
</code>```

This is just one of many exceptions that I catch and throw as my GenericServiceException.

So in my web application I have all necessary structure to handle internationalization as the JSF 2.x specification recommend the i18n package with the properties files whithin e.g. (messages.properties, messages_en.properties, messages_pt_BR.properties and so on.) and it is configured on the faces-config.xml it all works fine FOR MY XHTML files but what about my service files which is decoupled of my web app? How can I change my messages from the getNewException("Duplicate registry. Can not add.") to something like

```<code>getNewException(WebAppChoosedLanguage.getMessage(WebAppMessages.DUPLICATE_REGISTRY))
</code>```

Is this a good approach or I should let the generic service always throw every exception to be handled by the managed beans that called the service?

I'm asking this because every question that I find about it only speak on the view layer.

Code for the method getNewException:

```<code>private D getNewException(String message) {
    try {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class<D> theType = (Class<D>) type.getActualTypeArguments()[2];
        Constructor<D> constructor = theType.getConstructor(String.class);
        return constructor.newInstance(message);
    } catch (NoSuchMethodException | SecurityException
                 | InstantiationException
                 | IllegalAccessException
                 | IllegalArgumentException
                 | InvocationTargetException e) {
        logger.error("Erro ao executar o reflection para exceção. " + e.getMessage());
    }
    return null;
}
</code>```

答:
The type of the exception that is thrown should not be specific to the human language domain.

Throw some exception that's named in English, and look up an internationalized string for the exception description.


答:
I think the right answer is the conclusion you came to about starting with the public methods.  You would start by writing a test that calls that method.  It would fail so you create a method with that name that does nothing.  Then you maybe right a test that checks for a return value.

(I'm not entirely clear as to what your function does.  Does it return a string with the file contents with the non-numeric values stripped out?)

If your method returns a string then you check for that return value.  So you just continue to build it up.

I think anything that happens in a private method should be in the public method at some point during your process, and then only moved into the private method as part of a refactoring step.  Refactoring doesn't require having failing tests, as far as I know.  You only need failing tests when adding functionality.  You just need to run your tests after the refactor to make sure they all pass.


问:
How deeply can a JSON object be nested?
I was watching a video on a website that said json objects can be nested deeply.  How far can a JSON object be nested before it will create an error?</p>

答:
There is no theoretical limit to how deep JSON objects can be nested, but there usually is a practical limit based on the decoder being used. For example, PHP's json_decode() has a default limit of 512 levels, though it can be adjusted. Read the documentation for the code using the JSON to determine the max depth.

If your JSON is actually hitting depth limits, you probably need to reconsider how your JSON is structured.

Title: How deeply can a JSON object be nested?


答:
I agree with your reviewers and with @utnapistim. You can use system_error approach when you implement cross-platform things when some errors require special handling. But even in this case, it is not a good solution, but less evil solution.

One more thing. When create exception hierarchy, do not make it very deep. Create only those exception classes, that can be processed by clients. In most cases I use only std::runtime_error and std::logic_error. I throw std::runtime_error when something goes wrong and and I can do nothing (user eject device from computer, he forgot that application still running), and std::logic_error when program logic broken (User tries to delete record from database that does not exist, but before delete operation he can check it, so he get logic error).

And as library developer, think about your users needs. Try to use it yourself and think, whether it comfort for you. Than you can explain your position to your reviewers with examples of code.

Title: Designing exception classes

Body:
I'm coding a small library and I'm having some trouble with designing the exception handling. I must say that I am (still) confused by this feature of the C++ language and I tried to read as much as possible on the subject to come to an understanding of what would I have to do to properly work with exception classes.

I decided to use a system_error type of approach taking inspiration from the STL implementation of the future_error class.

I have an enumeration containing the error codes:

```<code>enum class my_errc : int
{
    error_x = 100,
    error_z = 101,
    error_y = 102
};
</code>```

and a single exception class (backed up by an error_category type of structures and everything else needed by the system_error model):

```<code>// error category implementation
class my_error_category_impl : public std::error_category
{
    const char* name () const noexcept override
    {
        return "my_lib";
    }

    std::string  message (int ec) const override
    {
        std::string msg;
        switch (my_errc(ec))
        {
        case my_errc::error_x:
            msg = "Failed 1.";
            break;
        case my_errc::error_z:
            msg = "Failed 2.";
            break;
        case my_errc::error_y:
            msg = "Failed 3.";
            break;
        default:
            msg = "unknown.";
        }

        return msg;
    }

    std::error_condition default_error_condition (int ec) const noexcept override
    {
        return std::error_condition(ec, *this);
    }
};

// unique instance of the error category
struct my_category
{
    static const std::error_category& instance () noexcept
    {
        static my_error_category_impl category;
        return category;
    }
};

// overload for error code creation
inline std::error_code make_error_code (my_errc ec) noexcept
{
    return std::error_code(static_cast<int>(ec), my_category::instance());
}

// overload for error condition creation
inline std::error_condition make_error_condition (my_errc ec) noexcept
{
    return std::error_condition(static_cast<int>(ec), my_category::instance());
}

/**
 * Exception type thrown by the lib.
 */
class my_error : public virtual std::runtime_error
{
public:
    explicit my_error (my_errc ec) noexcept :
        std::runtime_error("my_namespace ")
        , internal_code(make_error_code(ec))
    { }

    const char* what () const noexcept override
    {
        return internal_code.message().c_str();
    }

    std::error_code code () const noexcept
    {
        return internal_code;
    }

private:
    std::error_code internal_code;
};

// specialization for error code enumerations
// must be done in the std namespace

    namespace std
    {
    template <>
    struct is_error_code_enum<my_errc> : public true_type { };
    }
</code>```

I only have a small number of situations in which I throw exceptions illustrated by the error code enumeration.

The above did not sit well with one of my reviewers. He was of the opinion that I should have created a hierarchy of exception classes with a base class derived from std::runtime_error because having the error code embedded in the condition mixes things - exceptions and error codes - and it would be more tedious to deal with a the point of handling; the exception hierarchy would also allow for easy customization of the error message.

One of my arguments was that I wanted to keep it simple, that my library did not need to throw multiple types of exceptions and that the customization is also easy in this case as it is handled automatically - the error_code has an error_category associated with it that translates the code to the proper error message.

I have to say that I did not defend well my choice, testament to the fact that I still have some misunderstandings regarding C++ exceptions.

I would like to know if my design makes sense. What would be the advantages of the other method over the one I chose as I have to admit I fail to see that also? What could I do to improve?